text:
Q: Contar linha na matriz que possuam números repetidos Queria adicionar a linhaPreta a quantidade de linhas somente com 0, e a linhaBranca somente com 1.
public class Pixel {
    public static void main(String[] args) {

        int[][] img = {
        { 1, 1, 1, 1, 1, 1, 1, 1 },
        { 0, 1, 0, 1, 1, 1, 0, 0 },
        { 0, 0, 0, 0, 0, 0, 0, 0 },
        { 1, 1, 1, 1, 1, 1, 1, 1 },
        { 1, 1, 1, 1, 1, 1, 1, 1 },
        { 1, 1, 1, 1, 1, 1, 1, 1 },
        { 1, 1, 0, 0, 1, 1, 1, 0 },
        { 0, 0, 0, 0, 0, 0, 0, 0 },};

        int ppreto = 0;
        int pbranco = 0;
        int linhaPreta = 0;
        int linhaBranca = 0;

        int i;
        int j = 0;

        for (i = 0; i < img.length; i++) {
            for (j = 0; j < img[i].length; j++) {

                if (img[i][j] == 0) {
                    ppreto++;
                }

                if (img[i][j] == 1) {
                    pbranco++;
                }

                if (img[i].length == 0) {
                    linhaPreta++;
                }
                if (img[i].length == 0) {
                    linhaBranca++;
                }
            }
        }

        System.out.print("qtde ponto preto = " + ppreto + "\n");
        System.out.print("qtde ponto branco = " + pbranco + "\n");
        System.out.print("Qtd linha preta = " + linhaPreta + "\n");
        System.out.print("Qtd linha branca= " + linhaBranca + "\n");
    }
}

A: Sugestão de solução simples:
Para cada "linha" da sua imagem, some os pixels. Se soma der zero (0) a linha é "toda preta". Se a soma der igual ao número de pixels na linha, a linha é "toda branca".
int[][] img = {
    { 1, 1, 1, 1, 1, 1, 1, 1 },
    { 0, 1, 0, 1, 1, 1, 0, 0 },
    { 0, 0, 0, 0, 0, 0, 0, 0 },
    { 1, 1, 1, 1, 1, 1, 1, 1 },
    { 1, 1, 1, 1, 1, 1, 1, 1 },
    { 1, 1, 1, 1, 1, 1, 1, 1 },
    { 1, 1, 0, 0, 1, 1, 1, 0 },
    { 0, 0, 0, 0, 0, 0, 0, 0 },};

int linhaPreta = 0;
int linhaBranca = 0;

for (int i = 0; i < img.length; i++) {

    int soma = 0;
    for (int j = 0; j < img[i].length; j++)
        soma += img[i][j];

    if(soma == 0)
        linhaPreta++;
    else if(soma == img[i].length)
        linhaBranca++;
}

A: A contagem das linhas está realmente toda errada. Não faz sentido o código usado. Você tem que comparar item por item para saber se uma linha é composta toda por 0 ou toda por 1.
Desta forma criei um contador para ir acumulando o que é 0 ou 1 em cada linha individualmente. Por isto o contador zera no final de cada linha.
E só no final da linha eu posso ver se todos os elementos são do mesmo número. Obviamente isto é obtido verificando se os itens contados na linha é igual ao tamanho da linha.
public class Main {
    public static void main(String[] args) {
        int[][] img = {
        { 1, 1, 1, 1, 1, 1, 1, 1 },
        { 0, 1, 0, 1, 1, 1, 0, 0 },
        { 0, 0, 0, 0, 0, 0, 0, 0 },
        { 1, 1, 1, 1, 1, 1, 1, 1 },
        { 1, 1, 1, 1, 1, 1, 1, 1 },
        { 1, 1, 1, 1, 1, 1, 1, 1 },
        { 1, 1, 0, 0, 1, 1, 1, 0 },
        { 0, 0, 0, 0, 0, 0, 0, 0 },};
        int ppreto = 0;
        int pbranco = 0;
        int linhaPreta = 0;
        int linhaBranca = 0;
        for (int i = 0; i < img.length; i++) {
            int itensPreto = 0;
            int itensBranco = 0;
            for (int j = 0; j < img[i].length; j++) {
                 if (img[i][j] == 0) {
                     ppreto++;
                     itensPreto++;
                }
                if (img[i][j] == 1) {
                    pbranco++;
                    itensBranco++;
                }
            }
            if (itensPreto == img[i].length) linhaPreta++;
            if (itensBranco == img[i].length) linhaBranca++;
        }
        System.out.print("qtde ponto preto = " + ppreto + "\n");
        System.out.print("qtde ponto branco = " + pbranco + "\n");
        System.out.print("Qtd linha preta = " + linhaPreta + "\n");
        System.out.print("Qtd linha branca= " + linhaBranca + "\n");
    }
}

Veja funcionando no ideone. E no repl.it. Também coloquei no GitHub para referência futura.


text:
Q: php hide attributes on casting to array I coded a php class to represent a query-result. On an incoming query I cast it to an array, convert it to JSON (per json_encode) and return it to the user.
Now I want to define a class intern "debug" attribute, which souldn't be in the output - how can I hide attributes on casting a class to an array?

A: Remove the element from the resulting array with unset.

A: Declare it private or protected.
class Foo
{
   public $bar = 'bar';
   private $baz = 'baz';
   protected $quux = 'quux';
}

$f = new Foo();

echo json_encode($f);

Result:
{"bar":"bar"}

NB. Requires PHP 5, see Visibility in the PHP manual.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Nest can't resolve dependencies of the AuthGuard (Guard decorator) I've a AuthGuard who check the JWT token in controllers. I want use this Guard in controllers to check authentication. I've this error:

Nest can't resolve dependencies of the AuthGuard (?, +). Please make sure that the argument at index [0] is available in the current context.

TestController.ts
import {
  Controller,
  Post,
  Body,
  HttpCode,
  HttpStatus,
  UseInterceptors,
  UseGuards,
} from "@nestjs/common";
import { TestService } from "Services/TestService";
import { CreateTestDto } from "Dtos/CreateTestDto";
import { ApiConsumes, ApiProduces } from "@nestjs/swagger";
import { AuthGuard } from "Guards/AuthGuard";

@Controller("/tests")
@UseGuards(AuthGuard)
export class TestController {
  constructor(
    private readonly testService: TestService,
  ) {}

  @Post("/create")
  @HttpCode(HttpStatus.OK)
  @ApiConsumes("application/json")
  @ApiProduces("application/json")
  async create(@Body() createTestDto: CreateTestDto): Promise<void> {
    // this.testService.blabla();
  }
}

AuthGuard.ts
import { CanActivate, ExecutionContext, Injectable } from "@nestjs/common";
import { AuthService } from "Services/AuthService";
import { UserService } from "Services/UserService";

@Injectable()
export class AuthGuard implements CanActivate {
    constructor(
        private readonly authService: AuthService,
        private readonly userService: UserService,
    ) {}

    async canActivate(dataOrRequest, context: ExecutionContext): Promise<boolean> {
        try {
            // code is here
            return true;
        } catch (e) {
            return false;
        }
    }
}

A: AuthService (the dependency that could not be resolved) must be available in the scope containing the controller which uses the guard.
What does it mean?
Include AuthService in the providers of the module loading your controller.
e.g.
@Module({
  controllers: [TestController],
  providers: [AuthService, TestService, UserService],
})
export class YourModule {}

EDIT - Forgot to mention that an other clean way (maybe cleaner, depending on the context) consists in importing the module that offers (exports) the service.
e.g.
@Module({
  providers: [AuthService],
  exports: [AuthService],
})
export class AuthModule {}

@Module({
  imports: [AuthModule],
  controllers: [TestController],
  providers: [TestService, UserService],
})
export class YourModule {}


text:
Q: Delphi. How to disable Vcl Themes for TFileOpenDialog and TOpenDialog How to disable Vcl Themes for TFileOpenDialog and TOpenDialog ?
I try
procedure TForm1.FormCreate(Sender: TObject);
var
  chosenDirectory: String;
  openDialog : TFileOpenDialog;
begin

  TStyleManager.Engine.RegisterStyleHook(TFileOpenDialog, TStyleHook);

  chosenDirectory:='';

  try
    openDialog:=TFileOpenDialog.Create(Self);
    openDialog.Options := [fdoPickFolders];
    // var 2
    // Not works
    //TStyleManager.Engine.RegisterStyleHook(TFileOpenDialog, TStyleHook);

    if openDialog.Execute then
      chosenDirectory:=openDialog.FileName;
  finally
    openDialog.Free;
  end;
end;

but it's not work.
I try variation 2. It's not work too.

A: It does not work because FileOpenDialog is system windows dialog, rather than implemented in VCL, so you'll need add system hook based on class name. Plus you'll need to add hooks to class names of all Windows controls on this dialog.
Try something like this. Note that this will affect all system dialogs.
  TStyleManager.Engine.RegisterSysStyleHook('#32770', TSysStyleHook);
  TStyleManager.Engine.RegisterSysStyleHook('ReBarWindow32', TSysStyleHook);
  TStyleManager.Engine.RegisterSysStyleHook('Static', TSysStyleHook);
  TStyleManager.Engine.RegisterSysStyleHook('Edit', TSysStyleHook);
  TStyleManager.Engine.RegisterSysStyleHook('ScrollBar', TSysStyleHook);
  TStyleManager.Engine.RegisterSysStyleHook('ToolbarWindow32', TSysStyleHook);
  TStyleManager.Engine.RegisterSysStyleHook('ComboBox', TSysStyleHook);

A: The proper way of disable the styling of the common dialogs is removing the shDialogs element of the  TStyleManager.SystemHooks property.
TStyleManager.SystemHooks := [shMenus, shToolTips];


text:
Q: Remove a String from Json Object I am trying to convert an Avro Kafka Event to Json and need to manipulate The Avro Event by Removing Strings from this Event.
I am using GSON Library to manipulate the Json String Object but somehow its not removing the intended String.
JsonElement je = new Gson().fromJson(matchRequest, JsonElement.class);
        JsonObject jo = je.getAsJsonObject();
        jo.remove("com.XXX.XXXX");
        jo.remove("com.XXX.XXX");
        jo.remove("com.XXX.XXX");

        System.out.println("#################"+jo);

Json String I am Receiving as matchRequest is
{"interaction_id":"321","customer_id":"32","context_id":"123","work_id":"ewq","work_request_id":"213","task_type":"123","match_type":"wert","resource_list":{"com.xxx.xxxx":{"rank":1,"resource_data":{"com.xxx.xxxx":{"account_id":1,"source_name":"Mankind","channel_id":"voice"}}}},"service_list":{"com.xxx.xxxx":{"rank":5,"priority":1,"resource_count":"gvk","min_proficiency":"10","max_proficiency":"1","attributes":{"com.xxx.xxxx":{"category":"edw","value":"33232"}},"resource_offered":{"com.xxx.xxxx":{"agent_id":"rewq","account_id":"123","source_name":"wqe","resource_address":"ewq","source_address":"rewq","channel_id":"212","channel_provider":"wqe"}}}},"matching_state":"OFFERED"}

JSON Format
    "interaction_id": "321",
  "customer_id": "32",
  "context_id": "123",
  "work_id": "ewq",
  "work_request_id": "213",
  "task_type": "123",
  "match_type": "wert",
  "resource_list": {
    "com.XXXXXX": {
      "rank": 1,
      "resource_data": {
        "com.XXXX": {
          "account_id": 1,
          "source_name": "Mankind",
          "channel_id": "voice"
        }
      }
    }
  },
  "service_list": {
    "com.XXXX": {
      "rank": 5,
      "priority": 1,
      "resource_count": "gvk",
      "min_proficiency": "10",
      "max_proficiency": "1",
      "attributes": {
        "com.XXXX": {
          "category": "edw",
          "value": "33232"
        }
      },
      "resource_offered": {
        "com.XXXX": {
          "agent_id": "rewq",
          "account_id": "123",
          "source_name": "wqe",
          "resource_address": "ewq",
          "source_address": "rewq",
          "channel_id": "212",
          "channel_provider": "wqe"
        }
      }
    }
  },
  "matching_state": "OFFERED"
}

A: When you look at the documentation of the remove() method, it needs a key from the JSON object in parameter.
However, the JSON you are receiving does not contain "com.xxx.xxxx" as key, but some keys, like "resource_list", are linked to another JSON object containing "com.xxx.xxxx" as a key.
You may want to look recursively into the JSON object you receive to remove the intended String.

A: You need to perform your operation over your array:
jo.getAsJsonObject("resource_list").remove("com.XXX.XXXX");

This should do the trick.


text:
Q: Can someone explain why viewing a tagged commit in GitHub lists tags the way it does? In GitHub, when viewing the latest commit on a specific tag, the commit displays something like the following:

In the image above, the commit was tagged with v.16.52.0, but v.17.7.0 is a more recent tag in the repo. I'm curious why that one is bolded, and not the tag the commit was actually tagged with.
Expanding the ellipsis between those tag values displays all tags between the two. I'm not sure exactly what this is conveying.
Specifically, why is the most recent tag bolded, and not the tag the commit is actually tagged with?


text:
Q: Flask Error: Values is not an instance of  (got str)" I am getting BadValueException error on Flask with the usage of Flask and MongoAlchemy. The issue I am having is requesting POST data from date. I tried encoding to UTF8, however is returning string, instead being instance of datetime.datetime.
Error:
BadValueException: Bad value for field of type "date_deadline".  Reason: "Value is not an instance of <type 'datetime.datetime'> (got: str)".
Python
app = Flask(__name__)
db = MongoAlchemy(app)

class Model(db.Document):
    name = db.StringField()
    date_added = db.DateTimeField()

@app.route('/form', methods=['GET', 'POST'])
def form():
    if request.form.get('submit'):
        get_name = request.form.get('name')
        get_date = request.form.get('date').encode('utf8')

        new_model = Model(name = get_name, date = get_date)
        new_model.save()
    return render_template('form.html')

HTML
Name
<input type="text" name="name">

Date
<input type="datetime-local" name="date">

A: You can use the dateutil module to convert the string date to datetime type
from dateutil import parser

get_date = parser.parse(request.form.get('date'))

A: The data coming in from the form is already a string. What you need to do is convert it to a datetime format.
https://docs.python.org/2/library/datetime.html#datetime.datetime.strptime
I don't know how your datetime string is formatted, but assuming it's something like yyyy-mm-dd, then your conversion might look like this:
get_date = datetime.strptime(request.form.get('date'), '%Y-%m-%d')


text:
Q: Find folders of a given age, then filter for a given size and delete the matching folders? I've been having trouble with this for some time. Here is what I finally came up with that seems to work, though I have very limited abilities with piping.
I'm guessing this is a poor way to achieve my goal, are there some simpler ways I could do this that would be more efficient?
$ find /home/data/cam*/* -maxdepth 0 -type d -mtime +30 \
    -exec du -sm {} \;| awk '{if ( $1 > 3000 ) print $2}' | xargs rm -rf

A: It's pretty good actually.  Assuming the /home/data/cam*/* -maxdepth 0 part is fine, and assuming your directory names don't contain newlines, I'd do it like this:
find /home/data/cam*/* -maxdepth 0 -type d -mtime +30 -exec du -sm {} + | \
    awk '$1 > 3000' | cut -f 2- | xargs rm -rf

-exec du -sm {} + is an optimisation, it doesn't run du for each directory.  And awk '$1 > 3000' | cut -f 2- makes sure this still works if your directory names contain spaces.


text:
Q: convert nested array to JSON string in js? I have a set of array like this : [["Sarah"],["Jamie"],["B"],["148"]]
and I want to convert this into JSON string with specific  element for each vaues. For example,
{ "name":"Sarah", "grade":"148", "School":"B"...}

How should I proceed? I tried to toString the array then bind with this element but it doesn't work out well..
Original Json
   "Data":{
      "Table":[
         {
            "Name":[
               "Jamie"
            ],
            "School":[
               "A"
            ],
            "grade":[
               "99"
            ]

         },
         {
            "Name":[
               "Mike"
            ],
            "School":[
               "B"
            ],
            "grade":[
               "148"
            ]
         }
      ]
   }
}

A: You can try with the simple forEach

var data =   {"Data": {"Table": [{"Name": ["Jamie"],"School": ["A"],"grade": ["99"]},{"Name": ["Mike"],"School": ["B"],"grade": ["148"]}]}};

var items = [];
data['Data']['Table'].forEach(function(item){
  items.push({name: item.Name[0], grade: item.grade[0], school: item.School[0]});
});

console.log(JSON.stringify(items));

A: You can use reduce to do this!
let newData = data.Data.Table.reduce(function(arr, obj) {
    let newObj = {};
    for (let key in obj) {
        newObj[key] = obj[key][0]
    }

    arr.push(newObj);
    return arr;
}, [])

Demo: https://jsfiddle.net/500eo2gp/

A: let newDataArray = this.data.Data.Table.reduce(function(arr, obj) {
  let newObj = {};
  for (let key in obj) {
    newObj[key] = obj[key][0]
  }

  arr.push(newObj);
    return arr;
  }, []
);
newData =JSON.stringify(newDataArray);

JSON.stringify(newDataArray) array from tymeJV 's code snippet will give you the JSON string as follows.
[{"Name":"Jamie","School":"A","grade":"99"},{"Name":"Mike","School":"B","grade":"148"}]
Demo:
http://plnkr.co/edit/wPhVTOFhRgERLXKCuoYl?p=preview


text:
Q: jQuery, como alterar o z-index do datepicker Quando eu faço um $('#man_dia').datepicker(); a tag com id='man_dia' é apenas um input, e o jQuery insere sozinho os demais elementos no DOM, eu até consigo o id que o jQuery gera para alterar via css, mas o problema é que o jQuery declara o z-index dentro do elemento, então mesmo eu fazendo um css assim:
#ui-datepicker-div { z-index: 999; }

Porque o stilo assume o que esta na tag, que ele gera assim:
<div class="ui-datepicker ui-widget ui-widget-content ui-helper-clearfix ui-corner-all" id="ui-datepicker-div" style="position: absolute; top: 132px; left: 707.7px; display: block; z-index: 1;">

O Que eu já tentei fazer foi assim:
$('#man_dia').datepicker(function(){
    $(this).css('z-index','999'); // nao resolveu
});
///////////////////////////////////////////////
$('#man_dia').datepicker(); // criar calendário primeiro
$('#man_dia').css('z-index','999'); // passar o css depois também nao resolveu
//////////////////////////////////////
$('#man_dia').datepicker();
$('#ui-datepicker-div').css('z-index','999'); // passar o ID que o jQuery gera não resolveu

A: Use o !important no z-index do elemento desejado. Assim ele ignora caso haja outro valor definido anteriormente.
#ui-datepicker {
    z-index:999 !important;
}


text:
Q: The meaning(s) of "for" I wonder what the meaning(s) of "for"s in the following sentences/phrases are.

*

*I have a lot of homework for tomorrow.

*I have a lot of homework for English.

*The schedule for next week.

*What are we going to do for our music history class?

*To wait for someone.

*Keep it for me.

*I got the square root of 3 for problem number 6.

It really confuses me. Can you explain it to me? Thank you in advance!

A: The simple answer is that it provides context. If you let left it off it would beg a question to provide more information. Prepositions in languages though have a brilliant capability for inventing the rules as they go along.
1 and 3 you have (noun) for (time period). Here it qualifies the time it applies to (no one cares when hoework is given, only its due date matters)
2 (noun) for (noun). The second qualifies the first. "English homework" would do just as good.
4-6 are a bit different. It is a verb being qualified. In 5 "for" is used as wait takes a time period as an object when not using a preposition (wait half an hour). Here it is a thing waited for. 6 though is interesting as it changes the meaning of the verb more than others.
There are many more examples that will create even more confusion:
I'm done with this place for good.
What is the therefore there for?
The stackexchange community is here for you.


text:
Q: Multi color cell formatting I am trying to have a column of cells fill with one of 3 colors based on it's value in relation to another cell or the sum of other cells.
Column A, Column B and Column C. Column A is the colored column.
A to be green if A is greater than B
A to be orange if A is less than B but A+C is greater than B
A to be red if A is less B and less than A+C.
I have tried using standard fill of green with also conditional formatting "use a formula to determine which cells to format 2 color scale but have been unsuccessful.
I appreciate any help you may give.

A: It is really straightforward, but you need to realise that you can have different rules within conditional formatting. Let me show you in a screenshot (sorry for the Dutch, "Celwaarde" means "cell value"):

In order to create one rule, you might do it as follows (use the second option):


text:
Q: Error in pdfminer library installation in conda environment I installed "pdfminer" in virtual environment of conda.
I installed and reinstalled the library with following commands :
conda install -c conda-forge pdfminer
conda install -c conda-forge/label/cf201901 pdfminer
conda install -c conda-forge/label/cf202003 pdfminer

I got the same error all the time. It was like this:
/home/hamza/anaconda3/envs/my/bin/python /home/hamza/PycharmProjects/practice/pdf_info.py
20191125
Traceback (most recent call last):
  File "/home/hamza/PycharmProjects/practice/pdf_info.py", line 67, in <module>
    from pdfminer.high_level import extract_text
  File "/home/hamza/anaconda3/envs/my/lib/python3.7/site-packages/pdfminer/high_level.py", line 14, in <module>
    from .utils import open_filename
ImportError: cannot import name 'open_filename' from 'pdfminer.utils' (/home/hamza/anaconda3/envs/my/lib/python3.7/site-packages/pdfminer/utils.py)

Process finished with exit code 1

Is there any alternate way to install this library or what we can do this resolve this error


text:
Q: setTimeout of a forEach loop with datetime countdown? I'm trying to create a script that loops through an array of html elements, and creates a countdown for each of them, using a setTimeout. I don't really know why this does not work, but here is my code, and the console.log it gives me.
Console log >
-1481055605166  testing.html:61:5
End  testing.html:64:5
days-> -17142-hours->-21-minutes->-21-second->-6  testing.html:75:5
NaN  testing.html:61:5
days-> NaN-hours->NaN-minutes->NaN-second->NaN  testing.html:75:5
NaN  testing.html:61:5
days-> NaN-hours->NaN-minutes->NaN-second->NaN*

Here is the code >

  var productos = document.querySelectorAll(".producto.med");

  function recorrido() {
    productos.forEach(function(item) {
      var hora = item.querySelector("#hasta");
      cdtd(hora);
    });
  }
  var timer = setTimeout(recorrido, 2000);

  function cdtd(dia) {
    var xmas = new Date(dia);
    var now = new Date();
    var timeDiff = xmas.getTime() - now.getTime();
    console.log(timeDiff);
    if (timeDiff <= 0) {
      clearTimeout(timer);
      console.log("End");
      // Run any code needed for countdown completion here
    }
    var seconds = Math.floor(timeDiff / 1000);
    var minutes = Math.floor(seconds / 60);
    var hours = Math.floor(minutes / 60);
    var days = Math.floor(hours / 24);
    hours %= 24;
    minutes %= 60;
    seconds %= 60;
    var total = 'days-> ' + days + '-hours->' + hours + '-minutes->' + minutes + '-second->' + seconds;
    console.log(total);
  }

id}}'>

uno

    ruta_imagen}}" alt="producto">

desde: {{$producto->fecha_inicio}}

hasta: 2016-12-12 15:45:00

tiempo restante:

12hs 43m 03s
//JS PARA COUNTDOWNL

  Ofertar ahora

id}}'>

dos

    ruta_imagen}}" alt="producto">

desde: {{$producto->fecha_inicio}}

hasta: 2017-12-12 15:45:00

tiempo restante:

12hs 43m 03s
//JS PARA COUNTDOWNL

  Ofertar ahora

id}}'>

tres

    ruta_imagen}}" alt="producto">

desde: {{$producto->fecha_inicio}}

hasta: 2016-12-12 15:45:00

tiempo restante:

12hs 43m 03s
//JS PARA COUNTDOWNL

  Ofertar ahora

A: *

*The first product has a "hasta1" for id value. This should be "hasta"

*HTML elements should have unique ids.
This can be achieved by
a) Using "data-id" attributes instead of "id" attributes, changing all

   into

b) Make the selector find these elements by changing
       var hora = item.querySelector("#hasta");

  to
       var hora = item.querySelector("[data-id=hasta]");

*The Nan values indicate the data value used for Date is invalid: this is because an HTMLSpan element is being passed to cdtd, not a string. One way to fix this is to add a statement at the beginning of cdtd
  function cdtd(dia) {

   // get text before creating date

      dia = dia.textContent || dia.innerText;
      var xmas = new Date(dia);

   // ... and continue

*Changing setTimeout to setInterval, as in
var timer = setInterval(recorrido, 2000);

should repeatedly call recorrido until the timer is stopped in cdtd (not tested). Stopping the timer can use clearInterval for clarity, although calling clearTimeout does the same thing as clearInterval.

Update: Warning: avoid using class selectors to find elements if the class name is also used for styling. Use of data attributes provide an alternative.

In this example, both
 and
 match a selector for .tiempo. If elements with this class name have their content set to show the time remaining, the list element will be updated first and destroy  the child element with the data-id="hasta" attribute. This produces a dia value of null.

A: It appears you are looking for something listed in the page: http://www.htmlgoodies.com/html5/javascript/calculating-the-difference-between-two-dates-in-javascript.html#fbid=S_-Ojf9buFk

As long as you can calculate the number of milliseconds in an
  interval, you can come up with a number by dividing the total number
  of milliseconds by the number of milliseconds in the desired interval.
  What's more, we can apply the modulus (%) operator to strip out that
  value to determine the next larger interval. The key is to always go
  from the smallest interval - milliseconds - to the largest - days:

Date.daysBetween = function( date1, date2 ) {
  //Get 1 day in milliseconds
  var one_day=1000*60*60*24;

  // Convert both dates to milliseconds
  var date1_ms = date1.getTime();
  var date2_ms = date2.getTime();

  // Calculate the difference in milliseconds
  var difference_ms = date2_ms - date1_ms;
  //take out milliseconds
  difference_ms = difference_ms/1000;
  var seconds = Math.floor(difference_ms % 60);
  difference_ms = difference_ms/60;
  var minutes = Math.floor(difference_ms % 60);
  difference_ms = difference_ms/60;
  var hours = Math.floor(difference_ms % 24);
  var days = Math.floor(difference_ms/24);

  return days + ' days, ' + hours + ' hours, ' + minutes + ' minutes, and ' + seconds + ' seconds';
}


text:
Q: Conversion of anonymous XML datatypes to named datatypes I have the following snippet from an XML Schema:
<xs:element name="textSelection">
    <xs:complexType>
        <xs:sequence>
            <xs:element name="path" type="xs:string"/>
            <xs:element name="color" minOccurs="0">
                <xs:simpleType>
                    <xs:restriction base="xs:string">
                        <xs:enumeration value="yellow"/>
                        <xs:enumeration value="green"/>
                        <xs:enumeration value="light blue"/>
                        <xs:enumeration value="orange"/>
                        <xs:enumeration value="fucsia"/>
                    </xs:restriction>
                </xs:simpleType>
            </xs:element>
            <xs:element name="contentRef" type="xs:string" minOccurs="0"/>
        </xs:sequence>
    </xs:complexType>
</xs:element>

As one can see there are two anonymous datatypes.
One being a <xs:complexType> with 3 elements inside and the other being <xs:simpleType>which has 5 enumerations.
Since this is not a very good solution, namely both being anonymous I tried to convert them to named datatypes and this is what I thought of:
<xs:complexType name="textSelection">
    <xs:sequence>
        <xs:element name="path" type="xs:string"/>
        <xs:element name="color" type="color" minOccurs="0"/>
        <xs:element name="contentRef" type="xs:string" minOccurs="0"/>
    </xs:sequence>
</xs:complexType>

<xs:simpleType name="color">
    <xs:restriction base="xs:string">
        <xs:enumeration value="yellow"/>
        <xs:enumeration value="green"/>
        <xs:enumeration value="light blue"/>
        <xs:enumeration value="orange"/>
        <xs:enumeration value="fucsia"/>
    </xs:restriction>
</xs:simpleType>

So now to my actual questions:

*

*Did I do the conversion correctly or did I made any mistakes?

*Is it OK for <xs:element name="color" type="color"
minOccurs="0"/> to have both the name and the type of color?

A: Yes, the following XSD that reflects your named type conversion is correct:
<?xml version="1.0" encoding="UTF-8"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"
           elementFormDefault="qualified">

  <xs:element name="textSelection">
    <xs:complexType>
      <xs:sequence>
        <xs:element name="path" type="xs:string"/>
        <xs:element name="color" type="color" minOccurs="0"/>
        <xs:element name="contentRef" type="textSelection" minOccurs="0"/>
      </xs:sequence>
    </xs:complexType>
  </xs:element>

  <xs:complexType name="textSelection">
    <xs:sequence>
      <xs:element name="path" type="xs:string"/>
      <xs:element name="color" type="color" minOccurs="0"/>
      <xs:element name="contentRef" type="xs:string" minOccurs="0"/>
    </xs:sequence>
  </xs:complexType>

  <xs:simpleType name="color">
    <xs:restriction base="xs:string">
      <xs:enumeration value="yellow"/>
      <xs:enumeration value="green"/>
      <xs:enumeration value="light blue"/>
      <xs:enumeration value="orange"/>
      <xs:enumeration value="fucsia"/>
    </xs:restriction>
  </xs:simpleType>
</xs:schema>

And, yes, it is ok to have an element and a type with the same name.  Many conventions would avoid that in some manner, however, such as using colorType for the type, for example.


text:
Q: Pick event class wrapped into a function cannot work Please see the following code:
class PickCursor(object):
    def __init__(self, collection, alpha_other=0.3, tolerance=5):
        self.collection = collection
        self.alpha_other = alpha_other

        self.pts= collection.get_offsets()
        self.num_pts = len(self.pts)
        # Need to set a tolerance to make it take effect
        self.collection.set_picker(tolerance)

        # Ensure that we have separate colors for each object
        self.fc = collection.get_facecolors()
        if len(self.fc) == 0:
            raise ValueError('Collection must have a facecolor')
        elif len(self.fc) == 1:
            self.fc = np.tile(self.fc, (self.num_pts, 1))
        # self.fc is a 2d array every row follows [r, g, b, a]

        self.ind = None
        self.point_selected = None
        self.canvas = ax.figure.canvas
        self.canvas.mpl_connect('pick_event', self.onselect)

    def onselect(self, event):
        self.ind = event.ind[0]
        self.point_selected = self.pts[self.ind]
        # Change alpha of other points
        self.fc[:, -1] = self.alpha_other
        self.fc[self.ind, -1] = 1
        self.collection.set_facecolors(self.fc)
        self.canvas.draw_idle()

fig, ax = plt.subplots(1, 1, figsize=(8, 8))
x = np.arange(0, 10)
y = np.arange(0, 10)
scat = ax.scatter(x, y, s=15)
PickCursor(scat)

The above code works! Basically, it will make points unselected transparent. However, if I wrap the code into a function like this:
def func():
    fig, ax = plt.subplots(1, 1, figsize=(8, 8))
    x = np.arange(0, 10)
    y = np.arange(0, 10)
    scat = ax.scatter(x, y, s=15)
    PickCursor(scat)

func() ## this line does not work!!!

Anyone please shred some light on this? Thanks!

A: Your class is being garbage collected because you don't retain a reference to it.
def func():
    # ...
    return PickCursor(scat)

pc = func()


text:
Q: Cypress mochawesome reporter Report - how to send report We are currently running the cypress tests on production and reports are being generated at the cypress dashboard . but my team wants me to use mochawesome reports . I have mochawesome implemented without any problem.
But I want to know how to share these HTML reports with my team :

*

*Can I upload the HTML reports on slack channel ?

*Can I automate such in a way that at the end of test run , HTML reports are sent as an email?

*Can I share these HTML reports on notion?

Please suggest me what should be easiest solution to this.


text:
Q: .Net solution or IDE problem I have a weird situation with .Net.
I have 3 different projects
 - 1st is Main server project.
 - 2nd is the Communication class which uses Sockets to communicate with server.
 - 3rd is the Client application.
Everything works fine in Windows 7 but when it comes to Win xp it behaves abnormaly.
My client application sends sometime messages to server thru communcation project and doesnt recevies at all but server do send the messages.
But if I make a new project and copy all the code and files only for client application then it works 100% fine from IDE. That means from IDE If I run the newly made client application in debug or release mode it communicates fine.
But the moment instead of starting from IDE if i start the exe from debug or release folder everythign stops working even from IDE that means server sometimes gets the messages and client never receives the messages from server.
But If I make a new project it works fine only from IDE.
But everything works from windows 7 even from IDE or from direct exe.
Any help will be appreciated.

A: Sounds like you should check the project's settings to ensure that nothing is being specified based off of the Windows 7 machine. One thing that Visual Studio does not seem to handle well is switching between x86 and x64 machines. Ensure that x86 is select for CPU Type if that's what is intended.
There could be other issues at play here, but the CPU type is the most common issue I have had with Visual Studio when going between Windows 7 and Windows XP.


text:
Q: How do I get the number of users of a facebook application, and my facebook fan page, programatically? Sites like appdata dot com, provide detailed stats on usage of thousands of facebook applications.  How do they collect such data?
From what I understand, FB provides app developers with stats for their apps (same with fan page admins).  But how do I get these data programatically, is there any API for these?

A: Facebook does provide all of this through the graph api, which is at graph.facebook.com. To get all the extended data, you will need an access token.
Details, at least for applications (an can probably be expanded to pages, since the graph api works for all "objects" on FB) is found at http://developers.facebook.com/docs/api#analytics


text:
Q: Button lost WM_LBUTTONUP after a modal dialog window show up I have a win32 application, there is an button on the main window.
When i click the mouse left button, i receive the WM_LBUTTONDOWN message, when i release the mouse left button, i receive the WM_LBUTTONUP message, that is normal.
However, if in the processing of message WM_LBUTTONDOWN, (while i am holding the mouse left button), the program show a modal dialog window, the button will never receive the WM_LBUTTONUP.
This becomes an issue because in the WM_LBUTTONDOWN the program did something that needs to be clear up in the WM_LBUTTONUP.  Now because of the modal dialog, there is no chance to clear up anymore.
Is there a better way to handle this? I tried SetCapture, seems still can not receive the WM_LBUTTONUP.

A: This is quite reasonable. When you show the modal dialog it starts its own modal message loop. And so it will receive the WM_LBUTTONUP message.
The fundamental problem that you have is that you are showing the modal dialog in response to WM_LBUTTONDOWN, when in fact you should show it in response to WM_LBUTTONUP. Try pressing buttons in other applications and note that the action occurs only when the button goes up. You should do likewise and follow the platform standards.


text:
Q: Chaining whereField() filters I'm trying to filter my posts such that I only get the ones that have time that is in the future and that don't include the users posts. So my code is:
func fetchAllPosts() async throws -> [Post] {
  try await fetchPosts(from: postsReference.whereField("time", isGreaterThan: Date()).whereField("author.id", isNotEqualTo: user.id))
}

However when I run the code I get this error:

Thread 2: "Invalid Query. All where filters with an inequality (notEqual, lessThan, lessThanOrEqual, greaterThan, or greaterThanOrEqual) must be on the same field. But you have inequality filters on 'time' and 'author.id'".

So does this mean that there is no way to filter my posts using inequality filters that work on two or more fields?
Thanks!


text:
Q: Preload WooCommerce star.woff Font Google's PageSpeed Insights is telling me that WooCommerce star.woff font is making my site load slower and suggests me to use <link rel=preload> tag to save an estimated of 1.95s. Can someone please show me how can I apply this tag to a WooCommerce font without messing around with the plug-in's files?

A: After a couple of days I've found a solution. I'm not sure if this is the best solution but it worked for me, so I'll leave it here in case it helps somebody.
Add the following hook to your functions.php to enqueue the font and WordPress will add the link to the header with the <link rel=preload> tag.
// Enqueue Your Font
function my_queue_items() {
wp_enqueue_style( 'rating-stars', '/wp-content/plugins/woocommerce/assets/fonts/star.woff', array(), null );
}
add_action( 'wp_enqueue_scripts', 'my_queue_items', 99 );

// Add Crossorigin Attribute To Your Font
function style_attributes( $html, $handle ) {
if ( 'rating-stars' === $handle ) {
return str_replace( "media='all'", "media='all' crossorigin='anonymous'", $html );
}
return $html;
}
add_filter( 'style_loader_tag', 'style_attributes', 10, 2 );

This saved me 1s load speed.

A: The better solution is just to add the following line into [your-theme]/header.php
<link rel="preload" href="Font URL Showing in PageSpeed" as="font" crossorigin="anonymous">


text:
Q: What is alternative to `variant.resValue` with AGP 7.0.0+? I am trying to migrate to Android Gradle Plugin 7.
I have the following code that needs migration:
applicationVariants.all { variant ->
  // do some processing to obtain string apiKeyValue
  variant.resValue "string", "api_key", apiKeyValue
}

I have looked at the migration blog post here android developers blog but still no clear reference to how to create dynamic

resValue

Any thoughts?
I also tried to use something similar to
androidComponents {
    onVariants(selector().all(), { variant ->
      // do some processing to obtain string apiKeyValue
      addResValue("api_key", "string", apiKeyValue, "Value from variant")
    })
}

But no luck as

addResValue

method is not found.

A: After a bit of searching and trial and error, the following code worked for me:
androidComponents {
  onVariants(selector().all(), { variant ->
    // do some processing to obtain string apiKeyValue
    variant.resValues.put(variant.makeResValueKey("string", "api_key"), new ResValue(apiKeyValue, "Variant Name"))
  })
}

The above code is a snippet from my build.gradle file. I took inspiration from here gradle-recipes

A: For groovy and AGP 7.2.1 old way still works. Only keys for resValues now have type prefix ie "string/app_name". instead of "app_name".
android{
    applicationVariants.all{ variant ->
        def strRes = variant.mergedFlavor.resValues.get("string/app_name")
        if(strRes != null){
            println( "string/app_name = " + strRes.getValue())
            variant.resValue 'string', 'app_name', "${strRes}New"
        }
    }
}


text:
Q: multiplication of positive matrix and non negative matrix Assume $A>0$ and $H\le0$ are two real matrices
I need to prove that $\mbox{trace}(AH)\le0$
I tried to diagonalize $A$ with an orthogonal matrix but I didn't get any results.
Thanks.

A: Hints:
== A positive (non-positive) definite matrix has all its eigenvalues positive (non-positive)
== The trace of a matrix is the sum of all its eigenvalues (counted with multiplicity)

A: This kind of exercises are rather standard.

*

*Let $B=\sqrt{A}$ be the unique positive definite square root of $A$. (That is, $A=B^2$ and $B>0$. Why does $B$ exist? Think orthogonal diagonalization.)

*Show that $AH$ is similar to $BHB$ and hence they have the same traces.

*Argue that $BHB\le0$ (here we need the positive definiteness of $B$) and hence $\operatorname{tr}(BHB)\le0$.


text:
Q: Delegate/forward Kerberos tickets with Spring Security I'm trying to find information whether the Spring Security implementation of Kerberos handles delegation/forwarding of ticket granting tickets so that my app server can call other Kerberos services reusing the principals TGT? Any documentation on this would be highly appreciated. Cheers!

A: This is possible since the release of Spring Security Kerberos 1.0.0.
The SunJaasKerberosTicketValidator can be configured to store the authentication context:
ticketValidator.setHoldOnToGSSContext(true);

Here's some code to get you started:
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();

if (authentication instanceof KerberosServiceRequestToken) {
    KerberosServiceRequestToken token = (KerberosServiceRequestToken) authentication;

    if (token.getTicketValidation() == null) {
        // No delegation possible...
    } else {
        GSSContext context = token.getTicketValidation().getGssContext();

        // ...
    }
}

A: Spring security does not implement any Kerberos functionality. If you are referring to the kerberos extension then the answer is no. It only does authentication and it's just a wrapper around the Java JAAS API Krb5LoginModule.

A: As Koraktor mentioned, SunJaasKerberosTicketValidator class has the details which are equivalent to the JAAS config file. However, SunJaasKerberosTicketValidator has isInitiator flag set to false. This causes context.getCredDeleg() to return false, and you can not delegate the credentials.
I have done a POC where my observation is the delegation/forward works only if isInitiator is set to true.
I solved this issue by writing my own TicketValidator, everything from SunJaasKerberosTicketValidator kept as it is, except, changed the entry of isInitiator flag to  options.put("isInitiator", "true");


text:
Q: doInBackground Method is Not Working private void registerBackground(){

           Log.v(TAG,"-----regbackgroud method call---");

     new AsyncTask<Void, Void, String>() {

          @Override
          protected String doInBackground(Void... params) {

              String msg = "";

                try {
                    if (gcm == null) {
                        gcm = GoogleCloudMessaging.getInstance(context);
                  }
                    regid = gcm.register(SENDER_ID);

                    msg = "Device registered, registration id=" + regid;

                    setRegistrationId(context, regid);

                } catch (IOException ex) {
                    msg = "Error ::" + ex.getMessage();

                }
                return msg;

            }

          @Override
          protected void onPostExecute(String msg) {
              super.onPostExecute(msg);

          }

          @Override
          protected void onPreExecute() {
              super.onPreExecute();

          }
      }.execute(null, null, null);

}

Here My My code In this
1) Preexecuted Method Executed And
2) doInbackground() method does not executed.
please suggest me what should i have to do
and Any Error Occure When JNI Is On ...

A: No need to call in background
Try  Call this method
public void enableGCM() {

        try {
            GCMRegistrar.checkDevice(this);
            GCMRegistrar.checkManifest(this);
            final String regId = GCMRegistrar.getRegistrationId(this);
            if (regId.equals("")) {
                GCMRegistrar.register(this, SENDER_ID);
            } else {
                Log.v("GCM", "Already registered");
            }
        } catch (Throwable e) {
            e.printStackTrace();
        }
    }


text:
Q: prevent a form to be submitted multiple times - django I am submitting a form. After that i am doing HttpResponseRedirect so that the form wont be submitted if one i refresh the page. BUT, if i go back in browser and submit the form again, the form will be saved multiple times. How can i prevent this?
I thought of session, meaning i set a session name like this:
if request.session.get('saved', False):
    return HttpResponseRedirect('/already_saved/')
entry.save() # <-- pseudo save
request.session['saved'] = True

but this causes that the user can never send another form in my page in his actual session.
how can I create unique sessions for each form, so that one form doesnot get submitted multiple times but it is still possible to submit another forms?

A: An approach would be making a hash of the form's field and when the server receives the request you check if the hash of the form is already there (e.g. form already submitted). Something like this:
import hashlib
from django.shortcuts import Http404
sha512 = hashlib.sha512()
sha512.update(form_fields_stringfied)

if not request.session['forbidden_data']:
    request.session['forbidden_data'] = []

hashed_form = sha512.hexdigest()
if hashed_form not in request.session['forbidden_data']:
    request.session['forbidden_data'].append(hashed_form)
else:
    raise Http404

where hashed_form is the form data concatenated or in anyway you like
thus, no two forms considered equal will ever be submitted


text:
Q: '%s' % myobject: overloading As you know Python supports string formatting, but I want to speak about how it was realised in Python 2. If we type a=u'абв'; b='abc'; c='%s%s', then c variable will have a unicode type, so formatting returns unicode object. Is it possible for me to have my own class myobject, where variable c will have myobject type? In other words, can I overload this operator? The answer must work on Python 3 and Python 2, but it was more simple to describe what I want with Python 2. Thanks!
class ustream(object):
  '''ustream class provides an easy access for basic operations with Unicode
  streams. The main advantage of this class is that it already has built-in
  support for regular expressions and transliteration.'''
  __slots__ = ['_stream_', 'array', 'stream']

  def __init__(self, stream='', encoding=ENCODING['default']):
    '''ustream.__init__([stream[, encoding]]) -> ustream'''
    if isinstance(encoding, bstream):
      encoding = encoding.stream
    elif isinstance(encoding, ustream):
      encoding = encoding.stream
    if isinstance(stream, bytes):
      stream = stream.decode(encoding)
    elif isinstance(stream, string):
      stream = string(stream)
    elif isinstance(stream, bstream):
      stream = stream.stream.decode(encoding)
    elif isinstance(stream, ustream):
      stream = stream.stream
    else: # if unknown type
      typename = type(stream).__name__
      raise(TypeError('stream must be bytes or string, not %s' % typename))
    self._stream_ = stream

  @property
  def array(self):
    '''unicode stream as array'''
    return([ord(char) for char in self.stream])

  @property
  def stream(self):
    '''unicode stream as string'''
    return(self._stream_)

  def __mod__(self, stream):
    '''ustream.__mod__(stream) <==> ustream % stream'''
    result = self.stream % ustream(stream).stream
    result = ustream(result)
    return(result)

  def __rmod__(self, stream):
    '''ustream.__rmod__(stream) <==> stream % ustream'''
    stream = ustream(stream)
    stream = stream.stream
    result = stream % self.stream
    result = ustream(result)
    return(result)

This is a code sample from my laptop. string == str for Python 3 and unicode for Python 2. Just backward compatibility.
Here is what I want to get.
>>> src = ustream('a stream')
>>> add = 'Hello man'
>>> result = '%s! Look here: we have %s!' % (add, src)
>>> type(result)
utstream
>>> print(result)
Hello man! Look here: we have a stream!

A: I'm not exactly clear on what you mean, but you can define __mod__  (or __rmod__) to allow a class to overload the % operator...

In response to your edit, when I run your code:
a = stream('%s')
b = a % ('foo')
print (type(b)) #<class '__main__.stream'>

It works just fine.  What's the problem?

(and since the above code was edited again), here's the original code I tested:
class stream(object):
  def __init__(self, data):
    if isinstance(data, unicode):
      self.data = data
    elif isinstance(data, bytes):
      self.data =data.decode('UTF-8')
    else:
      raise TypeError('invalid data')
  def __mod__(self, data):
    data = stream(data).data
    result = self.data.__mod__(data)
    result = stream(result)
    return(result)

The reason you can't get what you want is because when python goes to resolve an operator (any operator), it looks at the object on the left of the operator and asks "Does this object provide a suitable implementation for that operator?".  If the answer is yes, then python calls that implementation and returns the result.  If the answer is no, it looks at the object on the right side of the operator and asks the same question.  If the answer is yes, it calls the right object's implementation and returns the result.  If the answer is no, it raises an exception.
Now in your desired output, you have "this is a string"%( obj1, streamobject ).  However, when python looks at that expression, it sees a string on the left hand side which has a defined __mod__, so python will always call that method instead of your user defined methods.  As I said in my comments, the only way to get your object to take precedence is to switch the order (Your object goes before the string).  I can see why you wouldn't want to do this (it's difficult to format more than one item this way).  You'd have to write it as:
myobj % ( "this is the format string %o %d %d %d", 1, 2, 3 )  #yuck

or similar where %o will get replaced by 'myobj.data' somehow.  Ultimately, this is getting really messy and I think it's worth asking why do you want to do this?.  (you could provide a convenience function to do all of this really easily).
My final comment on the subject is that you might want to look into overriding a template for string formatting.  It's not used very often, but may be of use here ...

A: You have to implement __format__.


text:
Q: Triggered Send Data Extensions deleted on a yearly basis I work in my client's Salesforce instance, and we have an API set up that triggers transactional sends from our system to Salesforce. Last year, several of the data extensions tied to those triggers disappeared. This year it happened again, on the same date. And no one can figure out what happened. The API doesn't have permission to delete data extensions. My client insists they didn't delete them manually.
The fact that this happens yearly on the same day makes me think it's an automated process, not just someone deleting what they think is old data. I've been googling and I can't find any sort of data retention policy that might cause a data extension to be deleted entirely. Does anyone have any other ideas of what might have happened?
EDIT: I have considered contacting salesforce support, but would they even be able to see what happened if the Data Extension no longer exists?


text:
Q: where is "registry-1.docker.io" ? I do anything i can.
Not in daemon.json,maybe in some docker binary file.
   # cat /etc/docker/daemon.json

     {
        "registry-mirrors": [
        "https://d8b3zdiw.mirror.aliyuncs.com"
        ],

         "insecure-registries": [
       "https://ower.site.com"

This is docker info
[root@k8s-master ~]# docker info
Client:
 Context:    default
 Debug Mode: false
 Plugins:
  app: Docker App (Docker Inc., v0.9.1-beta3)
  buildx: Docker Buildx (Docker Inc., v0.7.1-docker)
  scan: Docker Scan (Docker Inc., v0.12.0)

Server:
 Containers: 25
  Running: 20
  Paused: 0
  Stopped: 5
 Images: 13
 Server Version: 20.10.12
 Storage Driver: overlay2
  Backing Filesystem: xfs
  Supports d_type: true
  Native Overlay Diff: true
  userxattr: false
 Logging Driver: json-file
 Cgroup Driver: systemd
 Cgroup Version: 1
 Plugins:
  Volume: local
  Network: bridge host ipvlan macvlan null overlay
  Log: awslogs fluentd gcplogs gelf journald json-file local logentries splunk syslog
 Swarm: inactive
 Runtimes: io.containerd.runc.v2 io.containerd.runtime.v1.linux runc
 Default Runtime: runc
 Init Binary: docker-init
 containerd version: 7b11cfaabd73bb80907dd23182b9347b4245eb5d
 runc version: v1.0.2-0-g52b36a2
 init version: de40ad0
 Security Options:
  seccomp
   Profile: default
 Kernel Version: 3.10.0-1160.el7.x86_64
 Operating System: CentOS Linux 7 (Core)
 OSType: linux
 Architecture: x86_64
 CPUs: 4
 Total Memory: 3.701GiB
 Name: k8s-master
 ID: P6VN:S2FI:AU6D:LBCO:PPX7:KREJ:7OIQ:2K2J:XISF:MZGT:YSDB:XFIG
 Docker Root Dir: /data/docker
 Debug Mode: false
 Registry: https://index.docker.io/v1/
 Labels:
 Experimental: false
 Insecure Registries:
  127.0.0.0/8
 Live Restore Enabled: false

Disconnect the network,exec "kubectl create configmap nginx-config --from-file=nginx.conf",then,exec "kubectl describe pod nginx1-5c9f6bbd8c-4jmx2.
The messages display
Events:
  Type     Reason     Age                From               Message
  ----     ------     ----               ----               -------
  Normal   Scheduled  34s                default-scheduler  Successfully assigned default/nginx1-5c9f6bbd8c-4jmx2 to k8s-master
  Warning  Failed     33s                kubelet            Failed to pull image "nginx": rpc error: code = Unknown desc = Error response from daemon: Get "https://registry-1.docker.io/v2/": read tcp 10.15.29.150:51492->54.85.133.123:443: read: connection reset by peer

I want to know where is "registry-1.docker.io".

A: You are showing an issue with kubernetes, but making your configuration on docker. While these both run containers, they have separate configurations. For configuring the mirroring, it depends on how you run your containers in kubernetes. The most popular runtime being containerd's CRI, which has documentation on configuring their registry settings:
/etc/containerd/config.toml:
version = 2

[plugins."io.containerd.grpc.v1.cri".registry.mirrors]
  [plugins."io.containerd.grpc.v1.cri".registry.mirrors."docker.io"]
    endpoint = ["https://registry-1.docker.io"]

Which has been replaced with:
/etc/containerd/config.toml:
[plugins."io.containerd.grpc.v1.cri".registry]
   config_path = "/etc/containerd/certs.d"

and
/etc/containerd/certs.d/docker.io/hosts.toml:
server = "https://docker.io"

[host."https://registry-1.docker.io"]
# ...

As for where registry-1.docker.io comes from, it's the DNS name for the Docker Hub registry, which is the default when you do not specify a registry in your image name.


text:
Q: Matrix operations that preserve the nullspace of a matrix? Context: Let $A$ be matrix of nullity $> 0.$ I want to compute the nullspace of $A.$ But in certain cases, it's easier to transform $A$ into another matrix, then compute the nullspace of the resulting matrix, given that the transformation preserves the nullspace. For example: $\mbox{nullspace}(A) = \mbox{nullspace}(A^t A).$
My Question: In addition to multiplying $A$ by its transpose, what are the other matrix operations that preserve the nullspace of $A$?

A: $A \to SA$ where $S$ is an invertible matrix, or more generally a matrix such that the intersection of the nullspace of $S$ and the column space of $A$ is $\{0\}$ (this includes the case $S = A^t$, as well as the elementary row operations).


text:
Q: How to target Elements through Directives which are rendered by Angular Material using class selector I am testing out a simple use case, wherein i have created a directive(selector being a class name), while everything runs as expected when i try to target simple classes, the directive doesn't get initialised incase of Angular Material elements, for the test case i have used a simple MatMenu, while it is open it renders a div with the class cdk-overlay-container which is my target and source of the problem that is the directive doesn't get called.
Any help would be great,
Link to Code: StackBlitz

A: Angular's directive with a class selector can only target static element in the DOM. It can't target class names that are dynamically inserted into the DOM.
In your case, cdk-overlay-container is dynamically inserted into the DOM when you click on the menu. Hence, a simple static class worked.


text:
Q: How to update GridView on UI before method ends I am running a small app in SharePoint that produces the data needed for someone in our company. In short it pulls data from an Azure database into a data-table, and then converts that data-table to excel. This can take about a minute or two and sometimes, because we are in New Zealand and are using a remote server in the USA, they get timeouts and one of the worksheets won't load.
So what it does when it builds the excel is it iterates through a list of suppliers, and a list of financial weeks getting the data for each and creating a separate worksheet in excel per data-table. Ideally, what I would like to add a new row to a grid view that the user sees, as the report is being built,  stating whether that financial week and supplier was successfully added, or not, as the excel report is creating in the back-end. This would allow the user to be more aware of the progress, and allow them to know if there has been a problem rather than guessing.
It's a lot of code so I will try to show you the relevant parts.
Method that pulls and creates excel
    public void excelThreadCall()
    {
        DataTable updateDataTable = new DataTable();
        gridView.DataSource = updateDataTable;
        //Payments only download chosen Financial Week
        using (XLWorkbook workbook = new XLWorkbook())
        {
            //gradeWeek = selectedGradeWeek.SelectedValue;
            foreach (ListItem supplier in selectedSuppliers.Items)
            {
                if (supplier.Selected)
                {
                    foreach (ListItem fWeek in selectedfWeeks.Items)
                    {
                        if (fWeek.Selected)
                        {
                            string checkEmptyTableSQL = @"SELECT COUNT(*) FROM FleshvGraded WHERE Supplier_Code = '" + supplier.Value + "' AND PO_Revision = " + fWeek.Value;
                            int rowCount = Convert.ToInt32(getVariable(checkEmptyTableSQL));

                            if (rowCount > 0)
                            {

                                foreach (ListItem report in selectedReports.Items)
                                {
                                    //SQL Strings
                                    string sqlIntakeDate = @"SELECT Week_Ending_Date FROM Fiscal_Calendar WHERE Fiscal_Week = LEFT(" + fWeek + ", 2) AND Fiscal_Year = CONCAT(20, RIGHT(" + fWeek + ", 2))";
                                    string sqlPO = @"SELECT DISTINCT PO_No FROM FvGSummaryAll WHERE Supplier_Code = '" + supplier.Value + "' AND f_Week = " + fWeek.Value;
                                    string sqlAllSerials = "SELECT * FROM FvGData WHERE Supplier_Code = '" + supplier.Value + "' AND f_Week = " + fWeek.Value

                                    //variables
                                    DateTime weekEnding = Convert.ToDateTime(getVariable(sqlIntakeDate));
                                    DateTime weekStarting = weekEnding.AddDays(-5);
                                    string fWeekString = fWeek.ToString();
                                    string poNoString = getVariable(sqlPO).ToString();
                                    string intakeDateString = weekStarting.Day + "/" + weekStarting.Month + "/" + weekStarting.Year + " to " + weekEnding.Day + "/" + weekEnding.Month + "/" + weekEnding.Year;

                                    //adds summary variables to dictionary
                                    Dictionary<string, string> summaryVariablesDict = new Dictionary<string, string>();
                                    summaryVariablesDict.Add("f Week", fWeekString);
                                    //other values added to Dict

                                    //Adds WorkSheets based on above data
                                    if (report.Selected && report.Value.Equals("allserials"))
                                    {
                                        string worksheetName = supplier.Value + " Data " + fWeek.Value;
                                        DataTable dataTable = getDataTable(sqlAllSerials);
                                        createWorkSheet(workbook, worksheetName, dataTable);
                                    }
                                    //Other Reports follow

                                    **//what I hope to do - need this to show in the grid view immediatley not end of method
                                    updateDataTable.Rows.Add(suppler, fweek, "successful");
                                    gridView.DataBind();**

                                }
                            }
                        }
                    }
                }
            }
            workbook.SaveAs(filePath);
        }
    }

So currently this exists in another class but it's no problem for me to move it to the aspx page, and so I have taken liberties to just show you what I need to do in this method. So if it doesn't make complete sense in that respect (i.e. I wouldn't declare the datasource for the grid in the method normally).
The problem I have is that it will wait until the end of the method before updating the grid view via the postback and then the user gets it all at once. I was hoping there is a way to update the gridview at each iteration or even every few seconds if we use a timer, but can't find a way to implement this.
So long story short, how can I update the gridview from this method where the results appear immediately on the users UI, and not wait until the end of the method.

A: I would do something along these lines:

*

*When the page first loads, start a background thread to start building the spreadsheet.

*When the page loads, call some JavaScript that kicks off a callback.

*In the method in your code-behind that's called by the callback, check the status of the building process. Have that process maintain a list of strings, each representing the HTML for a row in a table.

*Have the page (via JavaScript) perform a callback every few seconds. That callback will get the current list of rows. JavaScript on the page will receive the response and update the rendered table to include the new rows.

*When the spreadsheet is done (or when a error occurs that aborts the creation process), show a success or failure message to the user.

If it would be helpful, I can provide some simple callback samples to get you going.
Edit: Added code sample:
Markup:
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="CallBackWebForm.Default" %>

<!DOCTYPE html>

    <title></title>

    <form id="form1" runat="server">

            Sample page with some progress-y stuff

                Col 1
                Col 2
                Col 3

            All done!

    </form>

Code-behind:
using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using System.Web.UI;
using Newtonsoft.Json;

namespace CallBackWebForm
{
    public partial class Default : System.Web.UI.Page, ICallbackEventHandler
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            // Setup Callback javascript so that page can initiate callbacks and receive callback responses
            CreateClientSideCallbackFunction();

            if (!Page.IsPostBack)
                StartBuildingSpreadsheetTask();
        }

        #region Callback
        private void CreateClientSideCallbackFunction()
        {
            var cm = Page.ClientScript;

            // The Javascript function in the markup must exactly match the function name as entered below (ReceiveServerData)
            var cbReference = cm.GetCallbackEventReference(this, "arg", "ReceiveServerData", "");

            // The Javascript function to be placed in the markup which will be used to initiate the callback
            var callbackScript = "function CallServer(arg, context) {" + cbReference + "; }";
            cm.RegisterClientScriptBlock(this.GetType(), "CallServer", callbackScript, true);
        }

        ///
        /// Called when CallServer(arg, context) is called in javascript on the page
        ///
        /// <param name="eventArgument">Not used, but must be passed</param>
        public void RaiseCallbackEvent(string eventArgument)
        {

        }

        ///
        /// Called at the end of a callback; provides the response/result to the client
        ///
        /// <returns>JSON string representing an instance of the DataTransferClass</returns>
        public string GetCallbackResult()
        {
            // Serialize the DataTransferObject, then delete all TableRows so we don't send them to the browser again
            // Note: this is not currently thread-safe. You should add some sort of locking mechanism so the background thread
            //       doesn't modify the TableRows list while we're serializing it and deleting from it.
            var dtoJson = JsonConvert.SerializeObject(DataTransferObject);
            DataTransferObject.TableRows.Clear();
            return dtoJson;
        }

        public class DataTransferClass
        {
            public bool DoneLoadingSpreadsheet { get; set; }
            public List<string> TableRows { get; set; }
        }
        #endregion Callback

        #region Background Task
        // Sessions have unique IDs, but individual page views don't. So, create one for this page view.
        private string ViewID
        {
            get
            {
                if (string.IsNullOrEmpty(ViewState["_viewID"] as string))
                    ViewState["_viewID"] = Guid.NewGuid().ToString();
                return ViewState["_viewID"] as string;
            }
        }

        // Store all DataTransfer data and token sources in static dictionaries so the background task can get to them
        private static Dictionary<string, DataTransferClass> DataTransferDictionary = new Dictionary<string, DataTransferClass>();
        private static Dictionary<string, CancellationTokenSource> TokenSourcesDictionary = new Dictionary<string, CancellationTokenSource>();

        // Make the values in the dictionaries for this View easily accessible via Properties
        private DataTransferClass DataTransferObject
        {
            get
            {
                if (DataTransferDictionary.ContainsKey(ViewID))
                    return DataTransferDictionary[ViewID];
                else
                    return null;
            }
            set
            {
                if (DataTransferDictionary.ContainsKey(ViewID))
                    DataTransferDictionary[ViewID] = value;
                else
                    DataTransferDictionary.Add(ViewID, value);
            }
        }

        private CancellationTokenSource TokenSource
        {
            get
            {
                if (TokenSourcesDictionary.ContainsKey(ViewID))
                    return TokenSourcesDictionary[ViewID];
                else
                    return null;
            }
            set
            {
                if (TokenSourcesDictionary.ContainsKey(ViewID))
                    TokenSourcesDictionary[ViewID] = value;
                else
                    TokenSourcesDictionary.Add(ViewID, value);
            }
        }

        private void StartBuildingSpreadsheetTask()
        {
            DataTransferObject = new DataTransferClass() { DoneLoadingSpreadsheet = false, TableRows = new List<string>() };
            TokenSource = new CancellationTokenSource();
            var token = TokenSource.Token;
            (new TaskFactory()).StartNew(() => BuildSpreadsheet(ViewID, token), token);
        }

        private void BuildSpreadsheet(string viewID, CancellationToken token)
        {
            // Simulate work. Update DataTransferObject every 5 seconds, finish after 30 seconds (6 iterations with 5 second wait);
            for (int i = 0; i < 6; i++)
            {
                // Work for 5 seconds
                System.Threading.Thread.Sleep(5000);

                // Update DataTransferObject with new row (don't use the 'DataTransferObject' property; it relies up the 'ViewID' property, which in
                // turn relies upon ViewState, which isn't available from a background thread).
                DataTransferDictionary[viewID].TableRows.Add("
Val " + i + "	Val " + (i * 10) + "	Val " + (i * 100) + "
");
            }

            // All done; update DataTransferObject
            DataTransferDictionary[viewID].DoneLoadingSpreadsheet = true;
        }
        #endregion Background Task
    }
}

A couple notes:

*

*Add Json.Net NuGet package (Newtonsoft)

*Note that the page class implements the ICallbackEventHandler interface

Edit 2: Updated suggested process at the top to match what I actually did in the code sample.


text:
Q: How to secure read with the Bash "read" command? You know there is a built-in Bash command called read. What if I want to do this in my scripts:
read PASSWROD

When it prompts me to input, all my input is visible.
Is there an alternative command that can make the input invisible.

A: Time to learn how to manual bash (in the bash manual, that is; this is from the Bash 4.1 edition).  The relevant option is -s.

read
read [-ers] [-a aname] [-d delim] [-i text] [-n nchars] [-N nchars] [-p prompt]
[-t timeout] [-u fd] [name ...]
One line is read from the standard input, or from the file descriptor fd supplied
  as an argument to the -u option, and the first word is assigned to the first
  name, the second word to the second name, and so on, with leftover words and
  their intervening separators assigned to the last name. If there are fewer words
  read from the input stream than names, the remaining names are assigned
  empty values. The characters in the value of the IFS variable are used to split
  the line into words. The backslash character \ may be used to remove any
  special meaning for the next character read and for line continuation. If no
  names are supplied, the line read is assigned to the variable REPLY. The return
  code is zero, unless end-of-file is encountered, read times out (in which case the return code is greater than 128), or an invalid file descriptor is supplied as the argument to -u.
Options, if supplied, have the following meanings:
-a aname The words are assigned to sequential indices of the array variable
  aname, starting at 0. All elements are removed from aname before
  the assignment. Other name arguments are ignored.
-d delim The first character of delim is used to terminate the input line,
  rather than newline.
-e Readline (see Chapter 8 [Command Line Editing], page 93) is used
  to obtain the line. Readline uses the current (or default, if line
  editing was not previously active) editing settings.
-i text If Readline is being used to read the line, text is placed into the
  editing buffer before editing begins.
-n nchars read returns after reading nchars characters rather than waiting
  for a complete line of input, but honor a delimiter if fewer than
  nchars characters are read before the delimiter.
-N nchars read returns after reading exactly nchars characters rather than
  waiting for a complete line of input, unless EOF is encountered or
  read times out. Delimiter characters encountered in the input are
  not treated specially and do not cause read to return until nchars
  characters are read.
-p prompt Display prompt, without a trailing newline, before attempting to
  read any input. The prompt is displayed only if input is coming
  from a terminal.
-r If this option is given, backslash does not act as an escape character.
  The backslash is considered to be part of the line. In particular, a
  backslash-newline pair may not be used as a line continuation.
-s Silent mode. If input is coming from a terminal, characters are not
  echoed.
-t timeout
  Cause read to time out and return failure if a complete line of input
  is not read within timeout seconds. timeout may be a decimal
  number with a fractional portion following the decimal point. This
  option is only effective if read is reading input from a terminal,
  pipe, or other special file; it has no effect when reading from regular
  files. If timeout is 0, read returns success if input is available on
  the specified file descriptor, failure otherwise. The exit status is
  greater than 128 if the timeout is exceeded.
-u fd Read input from file descriptor fd.

Hence, with the typo fixed, you need:
read -s -p "Password: " PASSWORD

You may want to add an echo immediately after it since the newline isn't echoed either (though it is not included in the password).

A: You can use terminal settings to turn echo off:
#!/bin/bash
# Disable echo
stty -echo

#Prompt and read password
printf "Password: "
read PASSWORD

# Turn echo back on
stty echo
printf "\n"

A: You can use these few lines:
stty -echo
read -p "Password: " passw; echo
stty echo

This will turn echo on and off between password reading.

A: read -s -p "Password: " passw

works on bash


text:
Q: How to switch off DocFX in visual studio in debug mode while active in release mode? I added DocFX to visual studio to generate web documents for my C# code. However, for every compilation it creates new documents which takes long time. Is there a way to switch it off in visual studio when I don't need it?
I know it is possible to uninstall/install it but this is the last resort.

A: You can edit the .csproj and add this line
<BuildDocFx Condition=" '$(Configuration)'=='Debug' ">false</BuildDocFx>

to the first <PropertyGroup> to disable docfx during debug builds


text:
Q: How can I start a service of an app when the device boots? (Android) How can I write a service, which starts automatically when the device boots? For example: when I start my phone, I get my new WhatsApp Messages, without opening WhatsApp before.

A: Two addition to Himanshu's answer:

*

*A boot-listening app must not be installed on the sdcard. Remember that the device boot may be completed
before the sdcard is even mounted resulting in your app's boot listener not being activated

*The boot-listener will not be activated until the user will activate your
app for the first time. Starting 4.2 (not sure here) android prevents all services &
listeners declared by a newly installed app from being activated until it is explicitly activated by the user.
Explicitly activated as in user clicking the homescreen icon.

A: You can use this to make it working:
Your manifest file:
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.jjoe64">

    <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />

    <application>
        <receiver android:name=".BootCompletedIntentReceiver">
            <intent-filter>
                <action android:name="android.intent.action.BOOT_COMPLETED" />
            </intent-filter>
        </receiver>
        <service android:name=".BackgroundService" />
    </application>

</manifest>

Add this class BootCompletedIntentReceiver.java
public class BootCompletedIntentReceiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        if ("android.intent.action.BOOT_COMPLETED".equals(intent.getAction())) {
            Intent pushIntent = new Intent(context, BackgroundService.class);
            context.startService(pushIntent);
        }
    }
}

this will make it auto start your service after boot of device


text:
Q: How to iterate over a range of cells in Excel/VBA? Dim works As Worksheet
Set works = ThisWorkbook.Sheets("Sheet1")
Dim txt As Variant

myrange = works.Range("C1:C9")

For Each txt In myrange
        If InStr(1, txt, "£", vbTextCompare) > 0 Then
            Debug.Print txt.Value                    '<..Object required err
            Debug.Print works.Range("C" & txt).Value '<..Object required err
            Debug.Print works.Cells(txt, 1).Value    '<..Object required err
            Debug.Print txt.Offset(0, 1).Value       '<..Object required err

    End If

Next txt

I'm trying to get the value of the cell that contains the "£" and then delete it . I'm getting `the object defined error in any case. I've tried 3 different options and still getting the error. I'm new to VBA and still learning. How can I fix this, and why am I getting the error?

A: One problem is the line myrange = works.Range("C1:C9"). It should have Set before it, like:
Set myrange = works.Range("C1:C9")

This way you ensure you are making a reference assignment, instead of a value assignment. Without it, you're telling VBA that you want the value of the cells to go in your variable. With it, you're telling VBA that you want your variable to point to that range.
Since you did not explicitly declare myrange as a Range object, VBA implicitly declared it Variant and treated it as a String. So, in the loop, txt was a String too, not a Range as you expected. Hence your error.
If you had Dim myrange As Range in the beginning, your assignment without Set would have failed and you'd have fixed it immediately.
But there's a simple habit that prevents this kind of error: in the top of your module, insert Option Explicit. This way, you have to explicitly declare ALL your variables, which means VBA won't assume they're Variant.
You can even make that automatic by checking the relevant option in Tools > Options.


text:
Q: doGet in JSP file worked, but doPost does not work I am new to java, so I tried to build a simple web service. Basically user should send data to the server. And server sends another set to be displayed to the user.
If I want to use POST method to send data I am getting error 404. However I was able to run GET request, but POST does not work. I tried a lot of versions. It is confusing for me that on the internet is more than one possible solution.
I would be glad if anybody can give me a hint, what I am doing wrong.
My servlet file .java
@WebServlet("/HomeServlet")
public class HomeServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
RequestDao req = new RequestDao();
ResultDao res = new ResultDao();
int month = 0;
int year = 0;
double hours = 0;
private ResultDao execute;
private CalcMonthFlow calcMonthFlow;
public HomeServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

@Override
public void init() throws ServletException {
    System.out.println("Servlet " + this.getServletName() + " has started");
}
@Override
public void destroy() {
    System.out.println("Servlet " + this.getServletName() + " has stopped");
}

/**
 * @see HttpServlet#service(HttpServletRequest request, HttpServletResponse response)
 */
protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    super.service(request, response);
}

/**
 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
 */
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException {
        try {
            response.getWriter().println("AHOJ");
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
}

/**
 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
 */
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    String monthInput = request.getParameter("month");
    String yearInput = request.getParameter("year");
    String hoursInput = request.getParameter("hours");

    response.getWriter().println(monthInput);
    response.getWriter().println(yearInput);
    response.getWriter().println(hoursInput);

}

}
My JSP file
    <%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ page import="java.time.LocalDateTime" %>
<!DOCTYPE html>

        <title>Mandays</title>

        <meta name="viewport" content="width=device-width,initial-scale=1">

        <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">

            Mandays
            <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">

            </button>

                    Home (current)

                    API

                    Wiki

Kalkulačka spočítá počet dnů a hodin v zadaném měsíci a roce včetně a bez svátků.

            <form action="/submit" method="POST">

                        Měsíc

                    <input type="text" class="form-control" name="month" value="${data.month}" placeholder="05" aria-label="Month" aria-describedby="basic-addon1">

                        Rok

                    <input type="text" class="form-control" name="year" value="${data.year}" placeholder="2019" aria-label="Year" aria-describedby="basic-addon1">

                        Hodin

                    <input type="text" class="form-control" name="hours" value="${data.hours}" placeholder="7.5" aria-label="Hours" aria-describedby="basic-addon1" data-toggle="tooltip" data-placement="right" title="Použijte desetinnou tečku.">

                    <input type="submit" class="btn btn-primary btn-sm" value="Spočítej">

                </form>

And my web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns
/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee
/web-app_3_1.xsd" id="WebApp_ID" version="3.1">
<display-name>MandaysFigu</display-name>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list>

<servlet>
    <servlet-name>HomeServlet</servlet-name>
    <servlet-class>present.HomeServlet</servlet-class>
    <load-on-startup>1</load-on-startup>
</servlet>

<servlet-mapping>
    <servlet-name>HomeServlet</servlet-name>
    <url-pattern>/submit</url-pattern>
</servlet-mapping>

Thank you!

A: The action attribute of your <form> should include the context path of your webapp, or use a relative path (if your JSP is in the root of your webapp, you could use action="submit").
To include the context path, depending on what version of JSP are you using, you simply do:
<form action="${request.contextPath}/submit" ... >

A: I think in your JSP file at <form action="/submit" method="POST">, you need to replace action="/HomeServlet" because of @WebServlet("/HomeServlet") in Servlet file.


text:
Q: How do I run a function in the background on watchOS and iOS? I'm trying to run a function in the background on iOS and watchOS, and I found a code sample, but it didn't work for me.
I tried some sample code that I found on GitHub, and a dispatch thread function.
..........
    private func startWorkout() {
        let workoutConfiguration = HKWorkoutConfiguration()
        workoutConfiguration.activityType = .other

        do {
            workoutSession = try HKWorkoutSession(healthStore: healthStore, configuration: workoutConfiguration)
            workoutSession?.delegate = self
//            HKWorkoutSession.startActivity(workoutSession!)
            healthStore.start(workoutSession!)
        } catch {
            print(error)
        }
    }

    @objc fileprivate func vibrate() {
        WKInterfaceDevice.current().play(.success)
    }

........

extension InterfaceController: HKWorkoutSessionDelegate {
    func workoutSession(_ workoutSession: HKWorkoutSession, didFailWithError error: Error) {

    }

    func workoutSession(_ workoutSession: HKWorkoutSession, didGenerate event: HKWorkoutEvent) {

    }

    func workoutSession(_ workoutSession: HKWorkoutSession, didChangeTo toState: HKWorkoutSessionState, from fromState: HKWorkoutSessionState, date: Date) {
        switch toState {
        case .running:
            hapticFeedbackTimer = Timer(timeInterval: 0, target: self, selector: #selector(vibrate), userInfo: nil, repeats: true)
            RunLoop.main.add(hapticFeedbackTimer!, forMode: .default)
        default:
            hapticFeedbackTimer?.invalidate()
            hapticFeedbackTimer = nil
        }
    }
}```

I expected the function vibrate to be run in the background, but instead, nothing happened

A: to use the background thread you can use this extension:
extension DispatchQueue {
static func backgroundQueue(_ backgroundOperations: ( () -> Void )? = nil, completion: (() -> Void)? = nil) {
    DispatchQueue.global(qos: .background).async {
        backgroundOperations?()
        if let completion = completion {
            DispatchQueue.main.async {
                completion()
            }
        }
    }
}
}

so you can perform your actions in background and then, after the background finish, do something on main Thread


text:
Q: What is the natural start order for package-dependent OSGI bundles (under Karaf)? I have a problem on 2.2.8 version of Karaf (and most probably on the earlier versions too).
I'm going to use Karaf to host the system with dynamically deployed bundles. Bundles are deployed by users and i cannot know beforehand which are they.
I expect order of the BundleActivator.start() to exactly correspond to package dependencies between bundles (dependencies of import/export packages) and planning to expect that it will be safe to assume that bundle0 will be completely initialized before bundle1 is going to be started. But it is not so - it seems that BundleActivator.start() is invoked in a "random" order and disregards package dependencies between bundles.
Sample use-case, I have 3 libs
test-lib0 - defines testlib0.ITestRoot, exports testlib0 package
test-lib1 - defines testlib1.TestRoot implements ITestRoot,  exports testlib1 package
test-lib2 - uses both libs, ITestRoot and TestRoot

When Karaf is started, i see following sample output in console
karaf@root> TestLib1Activator.start()
TestLib2Activator.start()
        ITestRoot: interface com.testorg.testlib0.ITestRoot - 16634462
        TestRoot:  class com.testorg.testlib1.TestRoot - 21576551
TestLib0Activator.start()

but i expect it should be always in this order
TestLib0Activator.start()
TestLib1Activator.start()
TestLib2Activator.start()
        ITestRoot: interface com.testorg.testlib0.ITestRoot - 16634462
        TestRoot:  class com.testorg.testlib1.TestRoot - 21576551

I'm attaching sample project for tests. Test case: after "mvn install" just move jars from ./deploy folder to the same folder of Karaf, trace messages should appear in console.
(Note: it may work correctly from the first attempt, try one more time then :))
Sample test project
http://karaf.922171.n3.nabble.com/file/n4025256/KarafTest.zip
Note: this is cross-post from http://karaf.922171.n3.nabble.com/What-is-the-natural-start-order-for-dependent-bundle-td4025256.html

A: In OSGi the bundle lifecycle is installed → resolved → starting → started.
Import-Package and Export-Package only influence when the bundle goes from installed to resolved. So the framework makes sure all bundles you import packages from are resolved before your bundle but then your bundle only goes to the resolved state. Then in a second step the activators are called. So you can not assume the activators are called in the same order. If you need some initializations before your testlib2 can work then you should use OSGi services.
So If I understood your case correctly then you testlib0 defines an interface, testlib1 implements it and testlib2 wants to use the implementation. So the best way to achieve this is to publish the impl as an OSGi service in testlib1 and reference this service in testlib3. You can then use the service with a ServiceTracker or with e.g. blueprint. I have a small example that shows this: http://www.liquid-reality.de/x/DIBZ . So if you do your case like in my example blueprint makes sure that the context of testlib2 only gets started when the service is there. It will even stop testlib2 when the service goes away.


text:
Q: Perforce P4V Fetch Indicator Does p4v indicate somewhere that there is content to be fetched or alternatively, a way to preview what would be fetched (Outside of manually comparing history against the remote depot)?
Edit: I should have mentioned I'm using DVCS.

A: If you're working directly against a shared server, the UI automatically refreshes with file badges that show you whether there are new revisions you can sync, and there's a dashboard view that'll show you that information at the global changelist level.
If you're using the DVCS mode, the UI support is a little more bare-bones and generally operates against your local server in isolation.  You might want to use the p4 fetch -n command from the terminal, which will tell you whether you're up to date and whether there are any conflicts with the remote server.


text:
Q: Issue with mysqli_query in PHP - query works in phpmyadmin and not in PHP I am trying to run an insert query using PHP. As mentioned in the title it works in phpmyadmin but does not work in php code.
Below is the code:
if ($result) {

  session_start();
  $_SESSION['fname'] = $firstname;
  $firstname_sess = $_SESSION['fname'];
  $sql_uid = " SELECT id FROM users WHERE firstname = '" . $firstname_sess . "' ";
  var_dump($sql_uid);
  $sql_uid_result = mysqli_query($db, $sql_uid);
  $sql_uid_array = mysqli_fetch_array($sql_uid_result, MYSQLI_ASSOC);
  $sql_uid_final = $sql_uid_array['id'];
  var_dump($sql_uid_final);
  mysqli_query('SET foreign_key_checks = 0');
  $uo_uid = "INSERT INTO `user_order` (user_id) VALUES ('$sql_uid_final')";
  var_dump($uo_uid);
  $uo_uid_final = mysqli_query($db, $uo_uid);
  var_dump($uo_uid_final);
  if ($uo_uid_final) {

    echo "All good";
  } else {
    echo "Something went wrong 1";
  }
  //header('Location: productsform.php');

} else {
  echo "Somethingwentwrong2";
}

Code Explanation:

*

*There are two tables users and user_order

*Trying to fetch existing user's user id from users table to user_order table.

*user_order table has user_id as a foreign key referencing id(PK) field  in users table.

*Facing issue while inserting the value in user_order table.

Although the code works through PHP myadmin or terminal but is not working via PHP code.
I have gone through the similar links given below:
1. mysql DELETE works on phpmyadmin but not on php script
2. SQL query working in phpmyadmin but not in php
3. mysqli_query works in phpmyadmin but not in php
4. Query works in phpMyAdmin but not in php
And many more but could not find anything. Any help would really be appreciated.
Thank you in advance.

A: One problem I see in your code is this line:
mysqli_query('SET foreign_key_checks = 0');

You haven't provided $db as the first argument of mysqli_query.
If that's not the issue, could you provide the mylsqli_error() for the query that fails?


text:
Q: Can not get path while doing ajax call using PHP and Javascript I need some help. I am passing data to server side using ajax call but its giving me an error 'The required path not found'. I am using code igniter for the MVC. Sample code below:
var url="http://localhost/User/updateUserProfile/";
$.post(url,{"form_data":dataString},function(res){
console.log("res",res);
    var getList=JSON.parse(res);
    if(getList['status']==1){
                               document.location.assign('http://oditek.in/takeme/User/userProfile');
    }else{
        alert(getList['msg']);
        return false;
    }
});

Controller/userController.php:
function updateUserProfile(){
        $form_data=$_POST['form_data'];
        parse_str($form_data,$data);
        if(isset($data) && !empty($data)){
            $user_id=strip_tags(trim($data['user_id']));
            $user_name=strip_tags(trim($data['user_name']));
            $user_email=strip_tags(trim($data['user_email']));
            $user_mobile=strip_tags(trim($data['user_mobile']));
            $user_emergency_contact=strip_tags(trim($data['user_emergency_contact']));
            $user_address=strip_tags(trim($data['user_address']));
            $user_gender=strip_tags(trim($data['user_gender']));
            $values = array($user_name,$user_email,$user_mobile,$user_emergency_contact,$user_address,$user_gender);
            $columns = array("name","email","mobile","emergency","address","gender");
            $condn="pro_Id='".prepare_param($user_id)."'";
            $tablename="tm_user_list";
            $id=db_update($tablename,$fields,$values,$condn);
            if($id !=false){
                $data=array("status"=>1,"msg"=>"Updated Successfully");
            }else{
                $data=array("status"=>1,"msg"=>"Could not Updated");
            }
        }
        echo json_encode($data);
    }

I am calling the above function for sending data to server side. But here the error is coming http://localhost/User/updateUserProfile/ is not found. Please help me to resolve this issue.

A: Save your controller as  UserController.php.Notice that the first letter is in uppercase having function updateUserProfile().Then in ajax set your url like this...
var url="http://localhost/User/UserController/updateUserProfile/";

Hope it works.


text:
Q: Connect Windows Phone and Windows 8 apps to SQL Server What is the best method to connect a Windows Phone app or Windows 8 app directly to an SQL Server?
The apps must not use a proxy/IIS etc. and was hoping to connect directly using SQL like with normal desktop applications.
Thanks.

A: You can't directly connect to a SQL Server, because of the Metro-Apps-Sandbox concept. They only can comunicate with a server through a service. The only way around this limitation that I know of is a SQLite integration into Windows 8 Apps.
In my opinion the best way (if you use Visual Studio) is the EntityFramework. It seems a bit complex at the beginning, but the ORM really helps while developing (less mistakes through intellisens, more security against injections). Then you wrap it up into a WCF Data Service and you are ready to use any SQL-Database in your application.

The Entity Framework enables developers to work with data in the form of domain-specific objects and properties, such as customers and customer addresses, without having to concern themselves with the underlying database tables and columns where this data is stored. With the Entity Framework, developers can work at a higher level of abstraction when they deal with data, and can create and maintain data-oriented applications with less code than in traditional applications

You can decide between two ways:

*

*Model first - Design your DB inside Visual Studio or SQL Server Management Studio

*Code first - Design your DB based on Classes

However there are some downsides:

*

*If you use Windows Azure you cannot use n:m relationship direct because of some restrictions to Azure Databases.

*You need to call the database async for Windwos 8 development. Therefore, there are always some confusing between the old client side use of EF and the new use in Windows 8.

Here is the Page of the EF-Project. You should start there to dive into it.