text:
Q: Como hacer que se muestren todos los datos en mysql y no solo el último EL problema es el siguiente: Yo hago un SELECT en el cual obtengo todos los valores de una tabla que sean iguales a un nombre, y lo almaceno en la variable $gruposcookies. Luego, hago otro SELECT en el obtengo todos los valores de otro tabla que tengan una columna que sea igual a alguna de las palabras contenidas en la variable $gruposcookies. Cuando imprimo la variable $gruposcookies me da el siguiente valor: JavaProgramación (general)Futbol. Pero cuando imprimo el valor de $publicacion, que es la variable en la que se almacena lo que devuelve el SELECT, solo muestra los datos cuya columna es igual a Fubol, la ultima palabra de $gruposcookies, pero no aquellos datos cuya columna sea igual a Java o a Programación. Es como si solo se almacenara en la variableecon el ultimo valor, pero cuando posteriormente se imprime esta variable si que imprimieran el resto de datos.
Si alguien sabe cual es el error y como podrías solucionarlo estaría muy agradecido.
Este es el codigo:
<?php
    $sql = "SELECT * FROM cookies_grupos WHERE usuario = '".$usuario."'";
    $result = mysqli_query($conn,$sql);
    while($mostrar=mysqli_fetch_array($result)) {
        $gruposcookies = $mostrar['grupo'];
        $sql="SELECT * FROM publicaciones WHERE nombre = '".$autor."' AND grupo LIKE '%".$gruposcookies."%' ORDER BY RAND() limit 1";echo $gruposcookies;
    }
    $result = mysqli_query($conn,$sql);
    if($mostrar=mysqli_fetch_array($result)){
        $publicacion = $mostrar['publicacion'];
    }
    echo $publicacion;

?>

A: No entiendo mucho de php, pero creo que tienes un error muy simple, la segunda consulta debe estar dentro del bucle while.
<?php
    $sql = "SELECT * FROM cookies_grupos WHERE usuario = '".$usuario."'";
    $result = mysqli_query($conn,$sql);
    while($mostrar=mysqli_fetch_array($result)) {
        $gruposcookies = $mostrar['grupo'];
        $sql="SELECT * FROM publicaciones WHERE nombre = '".$autor."' AND grupo LIKE '%".$gruposcookies."%' ORDER BY RAND() limit 1";echo $gruposcookies;
        $result = mysqli_query($conn,$sql);
        if($mostrar=mysqli_fetch_array($result)){
           $publicacion = $mostrar['publicacion'];
        }
        echo $publicacion;
    }
?>


text:
Q: cant get the facebook-tornado connection i've a problem, am a beginer and i try to make a simple asynchronous program that posts to facebook, i use the tornado example and the tornado-facebook-sdk, here is the code:
class MainHandler(BaseHandler, tornado.auth.FacebookGraphMixin):
    @tornado.web.authenticated
    @tornado.web.asynchronous
    def get(self):
        self.facebook_request("/me/home", self.print_callback, access_token=self.current_user["access_token"])
        a = self.current_user["access_token"]
        #print a

    def print_callback(data):
        print data
        ioloop.stop()
        graph.get_object('/facebook', callback=print_callback)

and i get this error:
TypeError: print_callback() takes exactly 1 argument (2 given)

because i want to understand this example to get the token, and then use the example:
def callback(response):
    # ...
graph.put_object('me', 'feed', message="Maoe!!", callback=callback)

to write something on my facebook's wall, i did it with the synchronous library, but sadly this is blocking!
UPDATE: still getting and error:
class MainHandler(BaseHandler, tornado.auth.FacebookGraphMixin):
    @tornado.web.authenticated
    @tornado.web.asynchronous
    def get(self):
        self.facebook_request("/me/home", self.print_callback, access_token=self.current_user["access_token"])
        a = self.current_user["access_token"]
        print a

    def print_callback(self, data):
        graph.post_wall(self, "heloooooooo")

and got this error:
[E 121009 14:28:47 web:1108] Uncaught exception GET / (::1)
HTTPRequest(.....)
Traceback (most recent call last):
File "C:\Python27\lib\site-packages\tornado-2.4.post1-py2.7.egg\tornado\web.py", line 1043, in _stack_context_handle_exception
   raise_exc_info((type, value, traceback))
   File "C:\Python27\lib\site-packages\tornado-2.4.post1 py2.7.egg\tornado\stack_context.py", line 237, in _nested
    yield vars
  File "C:\Python27\lib\site-packages\tornado-2.4.post1-py2.7.egg\tornado\stack_context.py", line 210, in wrapped
    callback(*args, **kwargs)
  File "C:\Python27\lib\site-packages\tornado-2.4.post1-py2.7.egg\tornado\gen.py", line 405, in inner self.set_result(key, result)
  File "C:\Python27\lib\site-packages\tornado-2.4.post1-py2.7.egg\tornado\gen.py", line 335, in set_result
    self.run()
  File "C:\Python27\lib\site-packages\tornado-2.4.post1-py2.7.egg\tornado\gen.py", line 365, in run
    yielded = self.gen.send(next)
  File "build\bdist.win-amd64\egg\facebook\graphapi.py", line 129, in _make_request
    raise GraphAPIError(data)
GraphAPIError: (#200) This API call requires a valid app_id.

and when i go to Facebook, i see that it's a valide key that i'm using, i even use the generated Token (here the a variable), and pasting it to Api Debug, and i got everything works fine:
 Valid : True
 Origin : Web
 Scopes : create_note photo_upload publish_actions publish_stream read_stream share_item status_update video_upload

A: Add self to print_callback.
def print_callback(self, data):
    print data
    ioloop.stop()
    graph.get_object('/facebook', callback=print_callback)

redpajama_set_name: RedPajamaStackExchange


text:
Q: Translating method into stored expression I just wanted to make my code and linq queries to look better, and made an extension method for my Bank entity, as I would like to make queries look something like this
db.Banks.Where(x => x.SomeBooleanParam).Select(x => x.ToSummary())

But I run into exception

Linq-to-Entities does not recognize the method 'X.X.Summary ToSummary(X.X.Models.Bank)' method, and this method cannot be translated into a store expression.

My question: is it possible to somehow modify my ToSummary() function, so it is possible to use it on entities in queries? I have provided how my db would look like in JSON format, how simple select looks like and how summary looks like. I have read, that the function must return something like Expression<Func<somethingHere, bool>> but I have never understood it..
//How it looks in the DB
Items: [
    {Id: 1, Name: "Item1"},
    {Id: 2, Name: "Item2"},
    {Id: 3, Name: "Item3"}
]

Banks: [
    {Id: 1, Name: Bank1, SomeBooleanParam: true}
]

BankChanges: [
    {Id: 1, BankId: 1},
    {Id: 2, BankId: 1}
]

BankItems: [
    {Id: 1, ItemId: 1, BankChangeId: 1, Added: 10, Generated: 0},
    {Id: 2, ItemId: 2, BankChangeId: 1, Added: 1, Generated: 1}
    {Id: 3, ItemId: 1, BankChangeId: 2, Added: -10, Generated: 0},
    {Id: 4, ItemId: 2, BankChangeId: 2, Added: 3, Generated: 0},
    {Id: 5, ItemId: 3, BankChangeId: 2, Added: 7, Generated: 0}
]

// How simple select looks like, by including everything
simpleSelect:
[{
    Id: 1,
    Name: Bank1,
    BankChanges: [
        {
            Id: 1,
            BankItems: [
                {
                    Id: 1,
                    Item: {Id: 1, Name: "Item1"},
                    BankChangeId: 1,
                    Added: 10,
                    Generated: 0
                },
                {
                    Id: 2,
                    Item: {Id: 2, Name: "Item2"},
                    BankChangeId: 1,
                    Added: 1,
                    Generated: 1
                }
            ]
        },
        {
            Id: 2,
            BankItems: [
                {
                    Id: 3,
                    Item: {Id: 1, Name: "Item1"},
                    Added: -10,
                    Generated: 0
                },
                {
                    Id: 4,
                    Item: {Id: 2, Name: "Item2"},
                    Added: 3,
                    Generated: 0
                },
                {
                    Id: 5,
                    Item: {Id: 3, Name: "Item3"},
                    Added: 7,
                    Generated: 0
                }
            ]
        }
    ]
}]
// How summary looks like
summary:
[{
    Id: 1,
    Name: Bank1,
    ItemSummaries: [
        // Note: No Item1, because total of Item1 = 0 or less
        {
            Item: "Item2",
            TotalAdded: 4,
            TotalGenerated: 1,
            Total: 5
        },
        {
            Item: "Item3",
            TotalAdded: 7,
            TotalGenerated: 0,
            Total: 7
        }
    ]
}]

public static class BankExtensions {
    public static Summary ToSummary(this Bank bank)
    {
        return new Summary
        {
            Id = bank.Id,
            Name = bank.Name,
            ItemSummaries = bank.BankChanges
                                .SelectMany(x => x.BankItems)
                                .GroupBy(x => x.Item)
                                .Select(x => new ItemSummary
                                {
                                    Item = x.Key.Name,
                                    TotalAdded = x.Sum(y => y.Added),
                                    TotalGenerated = x.Sum(y => y.Generated),
                                    Total = x.Sum(y => y.Added) + x.Sum(y => y.Generated)
                                })
                                .Where(x => x.Total > 0)
        };
    }
}

A: Something like:
public static class BankExtensions
{
    public static IQueryable<Summary> ToSummary(this IQueryable<Bank> b)
    {
        return b.Select(bank => new Summary
            {
                Id = bank.Id,
                Name = bank.Name,
                ItemSummaries = bank.BankChanges
                                    .SelectMany(x => x.BankItems)
                                    .GroupBy(x => x.Item)
                                    .Select(x => new ItemSummary
                                    {
                                        Item = x.Key.Name,
                                        TotalAdded = x.Sum(y => y.Added),
                                        TotalGenerated = x.Sum(y => y.Generated),
                                        Total = x.Sum(y => y.Added) + x.Sum(y => y.Generated)
                                    })
                                    .Where(x => x.Total > 0)
            }
        );
    }
}

And then you use it like:
db.Banks.Where(x => x.SomeBooleanParam).ToSummary()


text:
Q: Upload file in angular2: Body (FormData) empty I'm trying to upload a picture with Angular2 to my REST Service (Loopback).
The Loopback service works (tested with Postman) and accepts files with the x-www-form-urlencoded header.
Here's a simplified service method that sends the POST request:
public uploadFile(url : string, file: File): Observable<any> {
  let headers: Headers = new Headers();
  headers.append('Content-Type', 'application/x-www-form-urlencoded');

  let formData = new FormData();
  formData.append('file', file);

  let options: RequestOptionsArgs = { headers: headers };

  return this.http.post(url, formData, options)
  .map((res: any) => (res.text() != "" ? res.json() : {}));
}

Note that I've set the header to application/x-www-form-urlencoded and send the formData containing the file in the body.
In Angular, up until the point where I http.post the request, the formData is populated with the file, the file content is present, everyting's fine:
Data before Request
But in the request, the body is an empty object {}:
Request
I assume, Angular is trying to do JSON.stringify(formData), at least, when I try this, I also get "{}" as output.
I've seen plenty of posts doing exactly the same (http.post(url, formData)). So what am I missing?

A: Just remove headers.append('Content-Type', 'multipart/form-data'); can solve problem.
See here
2017-08-24

A: From this How to inspect FormData? SO answer and this MDN documentation outputing FormData in the console just results in a {}.
FormData can directly be used in a for ... of structure, instead of entries(): for (var p of myFormData) is equivalent to for (var p of myFormData.entries()).

A: There is another solution is to use base64 and convert it in back-end side:
`
var reader = new FileReader();
    reader.readAsDataURL(file);
    let res;
    reader.onload = function () {
    let headers = new Headers();
    headers.append("Content-type","application/x-www-form-urlencoded");
    headers.append('Accept', 'application/json');
    let options = new RequestOptions({ headers: headers });
    return this.http.post(config.serverUrl+"/index.php",
      {
         "file":reader.result}, options)
         .toPromise()
         .then(this.extractData)
         .catch(this.handleError);
      }
    };
    reader.onerror = function (error) {
        console.log('Error: ', error);
    };`

A: In my case i used formData.set() instead of formData.append()
please see example below :
 UploadFile(fileToUpload: File): Observable<boolean> {
     const endpoint = 'api/image/upload';
     var formData = new FormData();
     formData.set('file', fileToUpload);
     return this._http
     .post(endpoint, formData)
     .map(() => { return true; })
     .catch((e) => this.handleError(e));
 }


text:
Q: IRI Mapping and referencing in JSON-LD I am trying to design an ontology using JSON-LD but i'm having trouble getting the syntax right. I looked at https://www.w3.org/TR/json-ld but couldn't find exactly the piece of information I am looking for, which is this: How to nest IRI's in the context, and how to reference them in the body?
{
  "@context":{
    "@base":"http://example.com/",
    "instances":"base:instances",
    "animals":"base:animals",
    "plants":"base:plants"
  },
  "@graph":[
    {
      "@id": "instances:1",
      "@type": "Plant",
      "plants:numleaves": "8",
      "plants:speciesname": "sunflower"
    },
    {
      "@id": "instances:2",
      "@type": "Animal",
      "animals:numlegs": "4",
      "animals:speciesname": "dog",
      "animals:eats": "instances:1"
    }
  ]
}

I want the id of the first element to be http://example.com/instances#1, but when I run it through http://json-ld.org/playground/ , it's expanded form is base:instances1. How do I make it right?

A: It doesn't work the way you want, because you define @base and then try to use it as a prefix.
Also the hash (#) won't just magically appear. You must include it in your base URI.
To sum up you would have to change your context to:
"@context":{
  "base":"http://example.com/",
  "instances":"base:instances#",
  "animals":"base:animals#",
  "plants":"base:plants#"
}

Now instances:1 is a concatenation of http://example.com/ + instances# + 1 as you ask for.


text:
Q: Forcefully revoking authorization in Hybridauth I've connected with Google using Hybridauth. But once I've given authorization for the app to access my account, it doesn't ask for it again even if I logout from all providers and destroy the session.
Sure, it does ask me to log in if I've logged out of my Google account. But doesn't ask for authorization again.
Highlights of the Logout code:
session_start();

require_once( "hybridauth/Hybrid/Auth.php" );

$hybridauth = new Hybrid_Auth('hybridauth/config.php');

$hybridauth->logoutAllProviders();

session_destroy();

Is there a way in which the user will have to re-authorize the app (Allow | Deny) every time he logs out? Or doesn't Hybridauth provide an option to forcefully revoke the authorization code (or refresh token)?

A:     $config = array(
          .
          .

           "approval_prompt" => "force",     // optional
          .

        )));

The approval_prompt option takes care of forcefully asking authorization every time the user logs in. It's not ideal for production environment of course, but just to test out your app on the local server.
The approval_prompt Can be "force or auto". The default is auto, so a given user should only see the consent page for a given set of scopes the first time through the sequence. If the value is force, then the user sees a consent page even if they have previously given consent to your application for a given set of scopes.


text:
Q: Using R to create a function,. to return the corresponding quarter of a specific date I need to create a function called date_quarter that accepts any vector of dates as its input and then returns the corresponding quarter for each date
Examples:

*

*"2019-01-01" should return "Q1"

*"2011-05-23" should return "Q2"

*"1978-09-30" should return "Q3"

etc.
Using the flights data set from the nycflights13 package in R to test the function by creating a new column called quarter using mutate.
Tried to make the function, but it doesn't return the quarter.

A: I ended up figuring out,
date_quarter <- function(dates){
  quarter = quarters.Date(dates)
  result = str_c(quarter)
  return(result)
}


text:
Q: Azure ComputeManagementClient doesn't return response when list of snapshots is requested I am trying to get list of snapshots in azure subscription using below code. But ComputeManagementClient doesn't return response when list of snapshots is requested. The for loop is not iterate over list of snapshots.
    rg_list=resource_client.resource_groups.list()
    for item in rg_list:
        logging.info(item.name)
        snap_list=compute_client.snapshots.list_by_resource_group(item.name)
        logging.info(snap_list)
        for snap in snap_list:
            logging.info(snap.name)

OUTPUT:
RGA-ResGrp
[06/08/2020 03:16:05] <azure.mgmt.compute.v2019_11_01.models._paged_models.SnapshotPaged object at 0x7f7d538fa1d0>

A: Could not reproduce your issue, there are three incremental snapshots in my resource group, it works on my side.

Try the code works for me:
from azure.mgmt.compute import ComputeManagementClient
from azure.common.credentials import ServicePrincipalCredentials

credentials = ServicePrincipalCredentials(
    tenant='<tenant-id>',
    client_id='<client-id>',
    secret='<client-secret>')

compute_client = ComputeManagementClient(credentials, "<subscription-id>")
snap_list=compute_client.snapshots.list_by_resource_group("<resource-group-name>")
print(snap_list)
for snap in snap_list:
    print(snap.name)

Update:
To iterate over list of snapshots, make sure the service principal have the enough permission e.g. Contributor role in the subscription.


text:
Q: What is the best practice for capturing all inner exception details? What is the best practice for logging complete exception details including all possible inner exceptions?
Currently, I use the following code:
try
{
    //some code that throws an exception
}
catch(Exception ex)
{
    do
    {
        Console.WriteLine(ex.Message+ex.StackTrace);
        ex=ex.InnerException;
    }while(ex!=null)
}

Are there any scenarios where this code may fail?

A: Have you tried  just using ex.ToString()?  It gives most (if not all) of the data you need to diagnose - including the message details, stack trace, and inner exceptions:
From MSDN:

ToString returns a representation of the current exception that is
  intended to be understood by humans. Where the exception contains
  culture-sensitive data, the string representation returned by ToString
  is required to take into account the current system culture. Although
  there are no exact requirements for the format of the returned string,
  it should attempt to reflect the value of the object as perceived by
  the user. The default implementation of ToString obtains the name of
  the class that threw the current exception, the message, the result of
  calling ToString on the inner exception, and the result of calling
  Environment.StackTrace. If any of these members is null, its value is
  not included in the returned string.

A: I have this extension method which suits my purposes just fine.
public static class ExceptionExtensions {
    public static string ToMessageAndCompleteStacktrace(this Exception exception) {
        Exception e = exception;
        StringBuilder s = new StringBuilder();
        while (e != null) {
            s.AppendLine("Exception type: " + e.GetType().FullName);
            s.AppendLine("Message       : " + e.Message);
            s.AppendLine("Stacktrace:");
            s.AppendLine(e.StackTrace);
            s.AppendLine();
            e = e.InnerException;
        }
        return s.ToString();
    }
}

And use it like this:
using SomeNameSpaceWhereYouStoreExtensionMethods;
try {
    // Some code that throws an exception
}
catch(Exception ex) {
    Console.WriteLine(ex.ToMessageAndCompleteStacktrace());
}

Update
Since I'm receiving upvotes for this answer I want to add that I stopped using this extension method, and now I'm just using exception.ToString(). It gives more information. So please, stop using this method, and just use .ToString(). See the answer above.


text:
Q: Python3.7 thread using 100% CPU and causing process to hang. How to avoid it? I'm running a Python script that is spawning threads in which it's analyzing text with complicated regex patterns using the re module. In some situations when the input string is very long, the Python interpreter takes up to 100% of CPU of my t2.micro EC2 machine (1 vCPU, 1 GB of RAM) and the script stops working (probably because of the lack of resources).
I was trying to find a way to kill a thread after some timeout - but in my case it's not possible to check any flag in the loop, since the thread never exits the regex function. Also it is crucial to not to kill the whole process - ideally the application should be running 24/7.
Maybe it is possible to somehow monitor the resources that are taken by the thread and raise some kind of exception after specified threshold?
The very, very simplified example of my script is this code:
from concurrent.futures import ThreadPoolExecutor
import re

pool = ThreadPoolExecutor(max_workers)

def check_difficult_regex(pattern, string):
    # time-consuming operations in here

pool.submit(check_difficult_regex, pattern, text)


text:
Q: scrap bulk images with puppeteer from awebpage isn't work Heloo, I'm trying here to scrap images from specific part of the body of webpage but it's scrape the images I want
const puppeteer = require('puppeteer');
const fs = require('fs');

(async () => {
  const browser = await puppeteer.launch();
  const page = await browser.newPage();

  let counter = 0;
  page.on('response', async (response) => {
    const matches = /.*\.(jpg)$/.exec(response.url());
    console.log(matches);
    if (matches && (matches.length === 2)) {
      const extension = matches[1];
      const buffer = await response.buffer();
      fs.writeFileSync(`images/image-${counter}.${extension}`, buffer, 'base64');
      counter += 1;
    }
  });

  await page.goto('https://example.com');

  await browser.close();
})();

I want to scrap bulk images from a part of the body of page or like scraping images from selector
I did try this code but it's scrap just images out of the area I want


text:
Q: Python 2.7: double backslash comparison I'm trying to know if I have a string with two backslash or more. My problem is that after some string treatment, I have my string to check like:

*

*'\string' when it has only one backslash charater (it should be '\\string' insteed).

*'\\string' when it has two bakslashes (it should be '\\\\string').

Is there any way to check the number of backslashes the string have? As '\string' == '\\string' is True.


text:
Q: Erro ao importar registros do banco pra gráfico No meu sistema antigo eu tinha um gráfico hightcharts que importa os valores de registros da minha tabela do banco de dados, porém, ao usar o mesmo modelo em outro sistema, começou a aparecer o seguinte erro:

Notice: Undefined index: SCJan in C:\Program Files
(x86)\EasyPHP5.2.10\www\Sis_Tam\indicadorS.php
Notice: Undefined index: SDJan in C:\Program Files
(x86)\EasyPHP5.2.10\www\Sis_Tam\indicadorS.php
Notice: Undefined index: SEJan in C:\Program Files
(x86)\EasyPHP5.2.10\www\Sis_Tam\indicadorS.php

Segue o código da minha página com o gráfico:
Parte em php responsável por fazer a importação:

    <?php
    /*-------------------------------------Janeiro ---------------------------------*/
    require_once("strcon.php");
    $totaSAJ = 0;
    $totaSBJ = 0;
    $totaSCJ = 0;
    $totaSDJ = 0;
    $totaSEJ = 0;

    $SAJ = "SELECT COUNT(ID) AS SAJan FROM pedidos WHERE SERVICO = 'Serviço A' and MES = 'JAN' and ANO = '2018'";
    $SBJ = "SELECT COUNT(ID) AS SBJan FROM pedidos WHERE SERVICO = 'Serviço B' and MES = 'JAN' and ANO = '2018'";
    $SCJ = "SELECT COUNT(ID) AS SCJan FROM pedidos WHERE SERVICO = 'Serviço C' and MES = 'JAN' and ANO = '2018'";
    $SDJ = "SELECT COUNT(ID) AS SDJan FROM pedidos WHERE SERVICO = 'Serviço D' and MES = 'JAN' and ANO = '2018'";
    $SEJ = "SELECT COUNT(ID) AS SEJan FROM pedidos WHERE SERVICO = 'Serviço E' and MES = 'JAN' and ANO = '2018'";

    $consultasaj = mysqli_query($strcon, "SELECT COUNT(ID) AS SAJan FROM pedidos WHERE SERVICO = 'Serviço A' and MES = 'JAN' and ANO = '2018'");
    $consultasbj = mysqli_query($strcon, "SELECT COUNT(ID) AS SBJan FROM pedidos WHERE SERVICO = 'Serviço B' and MES = 'JAN' and ANO = '2018'");
    $consultascj = mysqli_query($strcon, "SELECT COUNT(ID) AS SCJan FROM pedidos WHERE SERVICO = 'Serviço C' and MES = 'JAN' and ANO = '2018'");
    $consultasdj = mysqli_query($strcon, "SELECT COUNT(ID) AS SDJan FROM pedidos WHERE SERVICO = 'Serviço D' and MES = 'JAN' and ANO = '2018'");
    $consultasej = mysqli_query($strcon, "SELECT COUNT(ID) AS SEJan FROM pedidos WHERE SERVICO = 'Serviço E' and MES = 'JAN' and ANO = '2018'");

    if ($consultasaj = mysqli_query($strcon, $SAJ)) {
        if ($rowsaj = mysqli_fetch_assoc($consultasaj)) {
            $totaSAJ = $rowsaj['SAJan']; //Seta o total
        }
        mysqli_free_result($consultasaj);
    } else {

    }
    if ($consultasbj = mysqli_query($strcon, $SBJ)) {
        if ($rowsbj = mysqli_fetch_assoc($consultasbj)) {
            $totaSBJ = $rowsbj['SBJan']; //Seta o total
        }
        mysqli_free_result($consultasbj);
    } else {

    }
    if ($consultascj = mysqli_query($strcon, $SCJ)) {
        if ($rowscj = mysqli_fetch_assoc($consultascj)) {
            $totaSCJ = $rowsbj['SCJan']; //Seta o total
        }
        mysqli_free_result($consultascj);
    } else {

    }
    if ($consultasdj = mysqli_query($strcon, $SDJ)) {
        if ($rowsdj = mysqli_fetch_assoc($consultasdj)) {
            $totaSDJ = $rowsbj['SDJan']; //Seta o total
        }
        mysqli_free_result($consultasdj);
    } else {

    }
    if ($consultasej = mysqli_query($strcon, $SEJ)) {
        if ($rowsej = mysqli_fetch_assoc($consultasej)) {
            $totaSEJ = $rowsbj['SEJan']; //Seta o total
        }
        mysqli_free_result($consultasej);
    } else {

    }

Parte responsável pelo gráfico:

AS LINHAS QUE DÃO ERRO SÃO:

$totaSCJ = $rowsbj['SCJan'];
$totaSDJ = $rowsbj['SDJan'];
$totaSEJ = $rowsbj['SEJan'];

OBS: Eu fiz um código igual ao do mês de janeiro para os outros meses, por isso aparecem mais meses no gráfico, mas como todos dão o mesmo erro só achei necessário colocar o código de um dos meses pra facilitar o entendimento.
Eu preciso muito resolver esse problema hoje ainda, então se puderem me ajudar eu ficaria muito grata. :)
-------------------------------- ATUALIZAÇÃO -------------------------------
TODOS OS ERROS FORAM RESOLVIDOS QUANDO EU COLOQUEI UM ISSET ANTES DAS $ROW $totaSCJ = ISSET($rowsbj['SCJan']); MAS AINDA ASSIM O GRÁFICO NÃO APARECE NA TELA.


text:
Q: Queries in MS-Access:formatting a field in the middle of an sql UPDATE code I am having yet another problem with my data in ms-access.
Basically, what i'm doing is using multiple sql statements to pull, sort, and staight up change/manipulate data. The problem that im having currently is that i am trying to use a sql code like this:
UPDATE analyzedCopy2 SET analyzedCopy2.DateRange = #4/21/2009# to #4/29/2009#

but i can't figure out how to reformat DateRange (which is currently a date) to Text in the sql statement. I can't simply set the format manually because the sql code before this one is pulling in all of the data from another table and when that happens it changes the format of DateRange to date automattically since that is the type it is where it is coming from.
If anyone knows how to format a column with vba code then that would be fine too since i'm creating a vba code to run the queries in the order i want.
If anyone needs a better explanation of anything just let me know.

A: You can use SQL (DDL) to change some aspects of a table:
 ALTER TABLE TableName ALTER COLUMN  ColumnName Text(50)


text:
Q: How do I store duplicate email addresses? Using parse.com's API, how do I store multiple email addresses?
Currently if two users set the same email address I get the following error:

Error: the email address has already been taken

Is it possible to allow duplicate values? If so, how?

A: The email field on ParseUser is special and is validated against other email addresses for uniqueness.  However, you can always store email addresses in a custom field e.g. [[PFUser current] setObject:@"someDuplicate@email.com" forKey:@"contactEmail"], which won't be validated, allowing you to have duplicates.

A: If the parse.com API is returning this error then it's a restriction on their side, in which case the answer is: you can't.  If this is an error your own database is returning, then you need to offer more information as to why.


text:
Q: Convert modify time from stat into timestamp I just started my journey into bash scripting and I wrote a little script which copies certain files to my USB stick and external harddrive as a backup. So far it copies the entire directory with all files including those which I didn't change which naturally takes quite some time. In order to change that, I want it to compare the two files (on the pc and on the USB stick) with regards to the time when they were modified. So now I wonder how I can convert the output from

stat -c %y /test_folder/test.txt

into the format "YmDHMS"? Or maybe someone knows a better way to compare the files.

A: For comparison purposes you are probably better off using seconds since epoch (i.e. stat -a %Y) directly or even simpler use one of the bash built-in file tests [[ FILE1 -nt FILE2 ]] or [[ FILE1 -ot FILE2 ]] instead:
   file1 -nt file2
          True if file1 is newer (according  to  modification  date)  than
          file2, or if file1 exists and file2 does not.
   file1 -ot file2
          True  if file1 is older than file2, or if file2 exists and file1
          does not.

However since the question as asked is about conversion, since %y is modification time, if you have a recent version of GNU date you could cheat and use that instead. From man date:
-r, --reference=FILE
       display the last modification time of FILE

So
$ date +%Y%m%d%H%M%S -r file
20170111075620

Alternatively, you could pass the seconds-since-epoch from stat to date:
$ date +%Y%m%d%H%M%S -d "@$(stat -c '%Y' file)"
20170111075620

A: For comparing modification (or access or inode change) time of files, you should use seconds since Epoch, it is easier to handle in comparisons. stat's -c option has %Y format specifier for getting the modification time in seconds since Epoch.
To compare two files based on modification time, you can write a small function:
chk_mod () { (( $(stat -c '%Y' "$1") > $(stat -c '%Y' "$2") )) && echo "$1 is newer" \
            || echo "$2 is newer" ;}

Input the two input files as first and second positional parameters, and the function will output which one is newer; when they have exactly the same modification times, no output will be shown.
Example:
$ chk_mod () { (( $(stat -c '%Y' "$1") > $(stat -c '%Y' "$2") )) && echo "$1 is newer" || echo "$2 is newer" ;}

$ chk_mod foobar spamegg
spamegg is newer


text:
Q: Restrict label size from theme CSS in GTK? I'm trying to create themes for a program for GNOME that uses GtkLabel in a widget. I see that GTK Label already has a function for constraining the maximum length of a label, similar to the standard CSS text-overflow: ellipsis. GTK uses _ellipsize and max-width-chars.
However, I need to access these properties EXCLUSIVELY from my gtk.css, without changing the source code of the program. I don't even need to use these properties directly, I just want to take advantage of the fact that GTK already has that capability. If there's an indirect way of using them (i.e.: using Pango attributes somehow...), it works.
Here's the source of the program I'm using: https://gitlab.xfce.org/apps/xfce4-notifyd/-/blob/master/xfce4-notifyd/xfce-notify-daemon.c
The part of the GTK code I believe to be relevant: https://code.woboq.org/gtk/gtk/gtk/gtklabel.c.html
I've only been able to find documentation about how to implement Ellipsize in HTML, python, etc. I haven't found a way to use it from CSS.
Is it possible to do this, or should I just try a different program?


text:
Q: Kafka docker and LEADER_NOT_AVAILABLE I use the following Kafka Docker image: https://hub.docker.com/r/wurstmeister/kafka/
I'm able to start Apache Kafka with the following properties:
<KAFKA_ADVERTISED_HOST_NAME>${local.ip}</KAFKA_ADVERTISED_HOST_NAME>
<KAFKA_ADVERTISED_PORT>${kafka.port}/KAFKA_ADVERTISED_PORT>
<KAFKA_ZOOKEEPER_CONNECT>zookeeper:2181</KAFKA_ZOOKEEPER_CONNECT>
<KAFKA_MESSAGE_MAX_BYTES>15000000</KAFKA_MESSAGE_MAX_BYTES>

but I see the following warning when trying to send the message into the topic:
WARN 9248 --- [ad | producer-1] org.apache.kafka.clients.NetworkClient   : [Producer clientId=producer-1] Error while fetching metadata with correlation id 4 : {post.sent=LEADER_NOT_AVAILABLE}

I saw a few articles on the internet that told that this issue can be related to old properties like KAFKA_ADVERTISED_HOST_NAME and KAFKA_ADVERTISED_PORT and I should reconfigure to KAFKA_ADVERTISED_LISTENERS and KAFKA_LISTENERS. But when I start the Kafka container with the following properties:
<KAFKA_ADVERTISED_LISTENERS>PLAINTEXT://${local.ip}:${kafka.port}</KAFKA_ADVERTISED_LISTENERS>
<KAFKA_LISTENERS>PLAINTEXT://${local.ip}:${kafka.port}</KAFKA_LISTENERS>
<KAFKA_ZOOKEEPER_CONNECT>zookeeper:2181</KAFKA_ZOOKEEPER_CONNECT>
<KAFKA_MESSAGE_MAX_BYTES>15000000</KAFKA_MESSAGE_MAX_BYTES>

my application unable to connect to Kafka:
2018-08-25 16:20:57.407  INFO 17440 --- [           main] o.a.kafka.common.utils.AppInfoParser     : Kafka version : 1.1.0
2018-08-25 16:20:57.408  INFO 17440 --- [           main] o.a.kafka.common.utils.AppInfoParser     : Kafka commitId : fdcf75ea326b8e07
2018-08-25 16:20:58.513  WARN 17440 --- [| adminclient-1] org.apache.kafka.clients.NetworkClient   : [AdminClient clientId=adminclient-1] Connection to node -1 could not be established. Broker may not be available.
2018-08-25 16:20:59.567  WARN 17440 --- [| adminclient-1] org.apache.kafka.clients.NetworkClient   : [AdminClient clientId=adminclient-1] Connection to node -1 could not be established. Broker may not be available.

How to properly reconfigure the Docker Kafka in order to be able to use KAFKA_ADVERTISED_LISTENERS and KAFKA_LISTENERS?

A: From this awesome post, here's a good explanation about these properties:

LISTENERS are what interfaces Kafka binds to. ADVERTISED_LISTENERS are how clients can connect.

When your application connects to one of the addresses from LISTENERS the Kafka returns the correspondent KAFKA_ADVERTISED_LISTENER to that LISTENER you choosed. The KAFKA_ADVERTISED_LISTENER returned is the address that your application you will really use to communicate with Kafka.
So, you have to use in your application what you set on LISTENERS Kafka property for PLAINTEXT.
Using this configuration as you put:
<KAFKA_ADVERTISED_LISTENERS>PLAINTEXT://${local.ip}:${kafka.port}</KAFKA_ADVERTISED_LISTENERS>
<KAFKA_LISTENERS>PLAINTEXT://${local.ip}:${kafka.port}</KAFKA_LISTENERS>

You have to use on your application:
As you used on Kafka docker ${local.ip}:${kafka.port} you have to get the assigned kafka docker container IP and use it in your application.
Just to fill the variables for this scenario, let's suppose your kafka docker container IP 192.250.0.1 and the kafka port used is 9092, so your application bootstrap.servers property would be: 192.250.0.1:9092
Here's a command to see what Kafka returns to you when you try to connect using one of kafka's listener:
$ kafkacat -b 192.250.0.1:9092 -L
kafkacat is a very useful tool for test and debug kafka.


text:
Q: Script to convert Excel worksheet to 'XML Document' file type (Save as type'XML Spreadsheet 2003') I have a requirement to convert excel worksheets(.xlsx) to 'XML Document'(.xlsx) file type. Currently manually opening each worksheet and saving them as 'XML Spreadsheet 2003', I am looking for powershell script or excel-VBA macro to reduce manual efforts.
Below code convert .xlsx file to .xml
$Path = "C:\dev\"

$dev = Get-ChildItem -Path "$Path*" -Include "*.xls","*.xlsx"

If ($dev.Count -gt 0) {
    Write-Host "Excel files found:" $dev.Count
Foreach ($File in $dev) {
          $XLXMLSpreadsheet = 46
          $Excel = New-Object -ComObject Excel.Application
          $WorkBook = $Excel.Workbooks.Open($File.FullName)
          $Destination = $Path + $File.BaseName + ".xml"
          $WorkBook.SaveAs($Destination, $XLXMLSpreadsheet)
          $Excel.Quit()
          }
          Stop-Process -Name EXCEL
                      }
Else {Write-Warning "Could not find any excel files. Please ensure this path is correct and
the files exist:`n'$Path'"}

This code convert.xml file as 'XM File' but my requirement is to convert to 'XML Document' file type.
I tried looking for excel save as value for 'XML Spreadsheet 2003' format but no luck.
Any ideas in converting .xlsx file to .xml('XML Document') would be great help.


text:
Q: setuid bit on, yet program can't open a superuser file I have a file superuser.cpp created by the superuser with access permissions 770. Now, the superuser creates a file setuidDemonstration.cpp in which superuser.cpp is opened using open("superuser.cpp", O_RDONLY). The .cpp and the object file of setuidDemonstration.cpp have permissions rwxrwxr-x. Now, my questions are:-

*

*When I ran the program setuidDemonstration, in both normal and superuser mode it could not open superuser.cpp. Why? At least, the superuser mode should have succeeded in opening it.

*Now, I do sudo chmod 4775 setuidDemonstration. This should allow the program to open superuser.cpp even in normal mode because it would get euid of superuser during execution as the setuid bit has been set when sudo chmod 4775 setuidDemonstration had been run. But it couldn't. Also, when I printed euid while running it from normal mode, it printed 1000 and not 0. Why?
UPDATE:
Thanks for pointing out the mistake. I have removed '/' from the file path and now it does work for superuser. But even now after  sudo chmod 4775 setuidDemonstration, the normal mode run program falis to open the file. Pls explain.

A: Because /superuser.cpp is the name of a file in the filesystem root, not in the current working directory. Use superuser.cpp or ./superuser.cpp if the file is in the same path as you are when you run the program.


text:
Q: Calling reports from forms without displaying the form As the title says, I would like to call the reports from forms without actually displaying the form. I am very new to Oracle forms. I tried to do the following but it didn't work:
1)Inserted the code to call the reports in WHEN-NEW-FORM-INSTANCE trigger.
2)Removed the canvas so that the form won't be displayed.
But I got the error

RM-30173: Module contains no canvases

Is it possible to  do this?. I am trying to display the report when a menu item in an oracle forms application is clicked which in turn would call the above form but directly displaying
the report instead of displaying an UI.
Update:
I am using Forms Builder 10.1.2.
As for why I don't want to do this directly in the menu(MMB), the menu doesn't have an option to attach a report and I've already got a working form that generates an report but the code to call the report is written in a button-pressed trigger.
In,
http://forums.oracle.com/forums/thread.jspa?threadID=1107427&tstart=45, I am trying to do what  Andreas Weiden, suggested in that thread.

A: I think your problem may be in limiting your menu options to only opening forms.
For example, you could instead have the menu in your form execute a form trigger which would call the report. Or a web.show_document to the url for the Report.
What version of Forms are you on? It's been a while since I did much with Forms, but this may give you a start.

A: I am only familiar with Reports 6i, and it was simple to just run the report from the menu.
We created a menu item that was PL/SQL Command Type, dropped the code to run the report module in the Menu Item Code box, and all was good. I'd be surprised if you couldn't do something similar in 10g reports.

A: Move the code from the form's button into a procedure in a common library. Attach the library to the form and to the menu module. Call the procedure from both the form button as well as the menu.

A: I solved the problem by creating a blank canvas in the 'dummy form' as 'FRM-30173: Module contains no canvases' was returned when no canvas was found in the form.
The approach suggested by Andreas Weiden here: http://forums.oracle.com/forums/thread.jspa?threadID=1107427&tstart=45 works well.

A: You could have also just created the report and just call it behind the menu option but hiding the report parameter form and the report would automatically begin to generate. In the menu option just before you call the report name just set the report paramform to hide and destype to screen. This would have save the trouble of creating a  blank canvas and maybe having to suppress error messages if any was thrown.


text:
Q: Spring.boot: binding request parameter to data object with nested Optional Working with a vanilla @RestController in Spring.Boot, how can you use the default databinding and properly bind to nested Optional attributes in a data object?
In terms of code, this is the data class (using lombok to reduce the boilerplate)
@Data
public class SomeData {
   Optional<String> name;
}

which is used as a request parameter in a GET route, like this
@GetMapping("/something")
public void getSomething(SomeData data) {
  ...
}

The problem: if no corresponding parameter is given in the request, then data.name is null instead of Optional.empty.
What I found so far:
* Optional is handled properly when you just use it directly, like getSomething(Optional<String> name)
* Additional annotations like @RequestParam or @Valid don't affect this behavior


text:
Q: How to write NOT EQUAL (!=) To Query For Implode Or explode I have a SQLquery equal to is working but when I try to change and run as != its not working Please  Help .
SELECT * FROM Database1 WHERE JobLevel IN != ('".$JobLevel_filter."')

I have to add not equal to query (!=) to job level .

A: Try to use "<>" or "not like 'ABC'" instead of "!="


text:
Q: Failing to send checkbox value to MySQL database? I'm trying to store a Boolean value in my database based off a checkbox(Watched) in a form. If the checkbox isn't checked on form submit, it should send a 0; Otherwise a 1.
However, it sends a value of 0 no matter if it's checked or not. The Title Field and Genre field send perfectly, however the Watched conditional is not working correctly. I'm stumped and having a hard time wrapping my head around this, any thoughts?
<?php

    require 'config/config.php';
    require 'config/db.php';

    // Check for Submit
    if(isset($_POST['submit'])) {
        // Get Form Data
        $title = mysqli_real_escape_string($conn, $_POST['title']);
        $genre = mysqli_real_escape_string($conn, $_POST['genre']);
        if (isset($_POST['watched']) && ($_POST['watched'] == "value")) {
            $watched = 1;
        } else {
            $watched = 0;
        }

        $query = "INSERT INTO movies(name, genre, watched) VALUES('$title', '$genre', '$watched')";

        if (mysqli_query($conn, $query)) {
            header('Location: '.ROOT_URL.'');
        } else {
            echo "ERROR: " . mysqli_error($conn);
        }
    }

?>

                <form method="POST" action="<?php $_SERVER['PHP_SELF']; ?>">

                        <input type="text" id="form1" class="form-control" name="title">
                        Title

                        <input type="text" id="form1" class="form-control" name="genre">
                        Genre

                        <input type="checkbox" id="checkbox1" name="watched">
                        Have you watched it already?

                    <input type="submit" name="submit" value="submit" class="btn btn-primary">

                </form>

A: You never set an actual value for the checkbox in your form HTML, so the value of the checkbox will never exist which means your if statement will always return false.
Simply change this:
<input type="checkbox" id="checkbox1" name="watched">

to this:
<input type="checkbox" id="checkbox1" name="watched" value="value">


text:
Q: WPF MVVM CheckBoxes I am pretty new to the MVVM style of programming. The problem I am having is that I am trying to set the property of a checkbox when the WPF window loads. I do not need the property to be able to be changed. I merely need to show that it is checked or not.
XAML:
UPDATE:
<Grid RenderTransformOrigin="0.492,0.519" DataContext="{Binding ClosingCost}" VerticalAlignment="Center" HorizontalAlignment="Center">
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="300"/>
            <ColumnDefinition Width="100"/>
        </Grid.ColumnDefinitions>
        <Grid.RowDefinitions>
            <RowDefinition Height="197"/>
            <RowDefinition Height="103"/>
        </Grid.RowDefinitions>
        <StackPanel Grid.Column="0">
            <Label x:Name="LineID" Content="LineID" Grid.Column="0"/>
            <Label x:Name="LineName" Content="Line Name" Grid.Column="0"/>
            <Label x:Name="ClosingCostType" Content="Closing Cost Type" Grid.Column="0"/>
            <Label x:Name="UpdateClosingCostAuto" Content="Update Closing Cost Automatically" Grid.Column="0"/>
            <Label x:Name="CopyEstToGFE" Content="Copy Estimate to GFE" Grid.Column="0"/>
            <Label x:Name="CopyEsttoComparison" Content="Copy Estimate to Comparison" Grid.Column="0"/>
            <Label x:Name="EstimateType" Content="Estimate Type" Grid.Column="0"/>
        </StackPanel>
        <StackPanel Grid.Column="1">
            <Label x:Name="LineIDResult" Content="{Binding HUDLineNo}" Grid.Column="1"/>
            <Label x:Name="LineNameResult" Content="{Binding LineName}"/>
            <Label x:Name="ClosingCostTypeResult" Content="{Binding LineName}" Grid.Column="1"/>
            <CheckBox x:Name="UpdateClosingCostAutoResult"  Grid.Column="1" IsHitTestVisible="False" Focusable="False" IsChecked="{Binding IsSelected, Mode=OneTime}" />
            <CheckBox x:Name="CopyEstToGFEResult" Content="{Binding CopyEstimateToGFE}" Grid.Column="1" IsEnabled="False"/>
            <CheckBox x:Name="CopyEsttoComparisonResult" Content="{Binding CopyEstimateToComparison}" Grid.Column="1" IsEnabled="False"/>
            <CheckBox x:Name="EstimateTypeResult" Content="{Binding EstimateType}" Grid.Column="1" IsEnabled="False"/>
        </StackPanel>
        <Label x:Name="Type" Grid.Row="1" RenderTransformOrigin="0.5,0.5" Content="{Binding HUDLineNo}"/>
    </Grid>

ViewModel:
UPDATE:
public class EditClosingCostViewModel : ViewModelBase
    {
        public EditClosingCostViewModel() : this(new ClosingCostDal(), new ClosingCostFilterResult())
        {

        }
        public EditClosingCostViewModel(ClosingCostDal closingCostDal, ClosingCostFilterResult closingCostFilterResult)
        {
            this.closingCostDal = closingCostDal;
            this.closingCostFilterResult = closingCostFilterResult;
        }

        private ClosingCostDal closingCostDal;
        private ClosingCostFilterResult closingCostFilterResult;

        public ClosingCostFilterResult ClosingCost
        {
            get
            {
                return closingCostFilterResult;
            }
            set
            {
                closingCostFilterResult = value;
                OnPropertyChanged("ClosingCost");
            }
        }

        public bool IsSelected
        {
            get
            {
                if (ClosingCost.AutoUpdate == true)
                {
                    return true;
                }
                else
                {
                    return false;
                }
            }
        }
    }

Not entirely sure if the ViewModel is correct or even remotely going in the right direction.

A: If you don't want to change the property from your view, a read-only property is enough.
public bool IsSelected { get; } = true;

A: <CheckBox x:Name="UpdateClosingCostAutoResult"  Grid.Column="1" enter code hereIsHitTestVisible="False" Focusable="False" IsChecked="{Binding IsSelected, Mode=OneTime}" /

And add the OneTime mode in your binding


text:
Q: Shell script error: How would I change a permission on a file in a Shell script I am trying to set up a cron on several AWS EC2 machines and would like to run a command on all of them at once, with the following shell script:
#!/bin/sh
cd /etc/cron.daily
touch ecs.sh
echo '#!/bin/sh' > /etc/cron.daily/ecs.sh
echo 'sudo yum update -y ecs-init' >> /etc/cron.daily/ecs.sh
echo 'sudo yum update -y' >> /etc/cron.daily/ecs.sh
sudo chmod 755 /etc/cron.daily/ecs.sh
cd ~
(crontab -u root -l; echo '0 0 * * * /etc/cron.daily/ecs.sh') | crontab -u root -
sudo yum update -y

The part that does not work is: chmod 755 /etc/cron.daily/ecs.sh
I am not sure, what am I missing.

A: If you can (have sufficient rights to) create a file, you do not need to sudo to change its permissions to 0755. Which would also likely prompt you to input your password and run non-interactively could be the reason why the action did not take place.
On the other hand, if the user running this did not have the necessary (write) permission, preceding lines creating the file would not happen either.
You also do not need to touch a file, because that > redirection will create it (always a new one).
You also should not cd somewhere and and continue performing actions without checking directory was changed as expected. But since on all action but the unnecessary touch you use absolute path names, you can just as well leave out both cd lines.
If you clean-up the script and it still does not perform expected action, it might be useful (assuming non-interactive execution) to save its output (redirect both standard > (or 1>) and error (2>) output to a file) and examine it for errors.


text:
Q: How to get the value from URL params in React Having the following component:
import { ChangeEvent, useCallback, useState } from 'react';

export function SearchComponent() {
  const [searchValue, setSearchValue] = useState<string>('');
  const updateSearchValue = useCallback((event: ChangeEvent<HTMLInputElement>) => {
    setSearchValue(event.target.value);
  }, []);
  return (

      <input value={searchValue} onChange={updateSearchValue} />

  );
}

It updates that state value, searchValue with the value introduced in the input.
With that value, the URL is updated like this:
window.location.hash = searchValue ? `?searchBy=${searchValue}` : '';

It add an extra # to the URL, before it was example.com/test, now it is example.com/test#?searchBy=my_input but it's not a big issue.
What I want is to be able modify directly the input and store that new value in the component, so I've tried like this:
const queryParams = new URLSearchParams(window.location.search);
const searchBy = queryParams.get('searchBy');

When logged, queryParams is an empty object while searchBy is null.
Is there a way to store the value from the URL if the user is going to edit that value?

A: Issue
The issue is that window.location.hash = searchValue ? `?searchBy=${searchValue}` : ''; updates the location hash, thus adding the "#" to the URL, and not the window.location.search, which is the queryString part of the URL.
Using window.location is also a bit of an anti-pattern as it mutates the location and forces a reload of the page. Better to use the tools available to you from react-router-dom to issue a navigation action instead of reloading the entire app.
Suggested Solution
Using react-router-dom@5 you will need to use the useHistory and useLocation hooks and access the location.search value and instantiate your own URLSearchParams object. Set the initial searchValue state from the queryString, and use a useEffect hook to update the search params and issue an imperative redirect to the current route with the updated queryString.
Example:
import { useLocation, useHistory } from 'react-router-dom';

export function SearchComponent() {
  const history = useHistory();
  const { pathname, search } = useLocation();
  const searchParams = React.useMemo(() => new URLSearchParams(search), [
    search
  ]);

  const [searchValue, setSearchValue] = useState<string>(
    searchParams.get("searchBy") || ""
  );

  useEffect(() => {
    searchParams.set("searchBy", searchValue);
    history.replace({
      pathname,
      search: searchParams.toString(),
    });
  }, [history, pathname, searchParams, searchValue]);

  const updateSearchValue = useCallback((event: ChangeEvent<HTMLInputElement>) => {
    setSearchValue(event.target.value);
  }, []);

  return (

      <input value={searchValue} onChange={updateSearchValue} />

  );
}


text:
Q: Recorded video is bugged . Good sound but video with green or purple line/bloky Hey, im trying to use mediaRecorder but on emulator i can't normal tested it. In emulators ddms and app sayd me about "prepare failed" but when i try to run it on phone - all ok ( problem only when video recorded - than i can see bug with video (bloky/lines on screen)
I run my app on 2 device : 1 device recorded video and sound - but have on screen bloky/lines with random colors ( sound are ok), on other device - when click on start record : i have error...(and app crashed) i think there error is  "prepare failed" .
Anyone know what is that  and how to fix it ?
Regards,Peter.
p.s. sorry for my bad english, hope u understand me

A: issue is solved , was problem with emulator


text:
Q: A Complex Function is Constant if It Satisfies One of These Properties I am given that a complex function $f(z) = u(x,y) + iv(x,y)$ is analytic in a region $\Omega$. I am also given a list of conditions and must show that if $f$ satisfies any one of those conditions in $\Omega$, then $f$ is constant in $\Omega$. These are the conditions that I am having trouble with:
a. $f(\Omega) = \{f(z) : z \in \Omega\}$ is a subset of a circle.
b. $u^n(x,y) = v(x,y)$ for some $n \in \mathbb{N}$.
c. $Re(f)$ is analytic on $\Omega$.
My thoughts for part a: is this property saying that f is bounded by the subset of the circle? If so, can I apply Liouville's Theorem and say that since f is bounded, it must be constant?
For part b., my approach was to substitute $u^n(x,y)$ in for $v(x,y)$ in the function, and then use the Cauchy Riemann equations (since $f(z)$ is analytic). Calculating the partial derivatives gave me $u_x = nu^{n-1}u_y$ and $u_y = -nu^{n-1}u_x$. I am not sure if I did the partial differentiation correctly, though, and I'm not sure where to go from here.
For part c., I understand what it means for a complex function to be analytic, but what does it mean for its real part to be analytic? And how does that show that $f$ is constant on the region $\Omega$?

A: A nice way to prove these results relies solely on the open mapping theorem.
One can prove the following, stronger result:
Let $G$ be a $\mathcal{C}^{1}(\mathbb{C},\mathbb{R})$ function such that $0$ is a regular value of $G$ (in particular $G^{-1}(0)$ cannot contain an open set). If $G(f)=0$ on a region $\Omega$, $f$ is constant.
The result is easy to prove: let $f$ be non constant. Then it is an open mapping, which contradicts the regularity of $0$ for $G$ .
This result suffices to prove a&b. For $c$, if $\text{Re}(f)$ is analytic it must be constant by the open mapping theorem, and this implies $\text{Re}(f(\Omega))=\{c\}$ and again by the open mapping theorem we obtain the result.

A: Your argument for (a) would be fine if $f$ was defined on all of $\mathbb{C}$. $\Omega$ could be the open unit disk, in which case your argument fails. Hint: no subset of the unit circle can be open in $\mathbb{C}$.
For (b), you're on the right track. You have $u_x = nu^{n-1} u_y$ and $u_y = -nu^{n-1}u_x$ which after substitution gives $u_x = -n^2 u^{2n-2} u_x$ or $u_x(1+n^2 u^{2n-2}) = 0$ (and similarly for $y$). Note that $1+n^2 u^{2n-2}$ is positive..
For (c), if $\operatorname{Re}(f)$ were (presumably) complex analytic, then it would satisfy the Cauchy-Riemann equations. Writing $g(x,y) = \operatorname{Re}(f(x,y))$, what would the Cauchy-Riemann equations lead you to concluding about $g$?


text:
Q: Proof about Noetherian rings I have to prove that every finite ring is Noetherian. I know examples of Noetherian rings which are not finite such as the field of complex numbers or a PIR like the integers. But anyway:
[Proof]:
I know by definition that for a ring R that satisfies the ascending chain condition (ACC), i.e. every sequence of ideals $$I_1 \subseteq I_2\subseteq I_3\subseteq ... $$ of R stablises. i.e. $\exists n_o$ such that $I_{n_0}=I_n$ for all n $\ge n_o$ then the ring R is Noetherian. So this would mean there is a finite number of ideals. Now assuming R is finite, this would mean it has a finite number of subsets and as an ideal $I$ is defined to be a $I\subseteq R $ , wouldn't this mean the ACC is always satisfied for a finite ring and thus all finite rings are Noetherian?
I don't know if any of this is right but would really appreciate any advice. Thanks for any help.

A: That's the right idea... in fact you've even proved that a finite ring is Artinian, which turns out to imply Noetherian (although that's not trivial.)

A: Suppose there is an ascending chain of $R$ ideals that is not stationary. Then, for each $n$ there is $m$, with $m> n$, so that $I_n$ is properly contained in $I_m$, which accounts for the finitude of $R$. Therefore, every ascending chain is stationary, and therefore, $R$ is Noetherian.


text:
Q: I don't have a problem [with] asking for help I've looked into COCA for citations of "problem asking for" and "problem with asking for", and I found references to both. But I have a feeling that one is more common that the other or one is more informal than the other, so which is which?

Example: I don't have a problem [with] asking for help from specific
  people.

A: The two expressions overlap, but are not always interchangeable.

*

*If you find it difficult to perform some action expressed as a verb you should ordinarily use the -ing form, thus:

I have a problem calculating derivatives.
  I have a problem asking for help.

*If you find it difficult to perform in some matter expressed as a noun—an academic subject, for instance, or a category of action—use the preposition phrase headed by with:

I have a problem with calculus.
  I have a problem with relationships at work.

*However, to have a problem with X can also have a different meaning: to have an objection to X. The idea expressed is not that X is difficult, but that it would create a difficulty—perhaps a practical difficulty, perhaps a moral or philosophical difficulty:

I have a problem with asking Herbert for help. Whenever you ask him for help on a project he tries to take it over and make it part of his empire building.

The lines between these can be fuzzy; but in general you should avoid using with with an -ing form unless you are speaking of your objection (3) rather than your incompetence (1).


text:
Q: Mobile navigation menu returns page to top when clicked Warning: Serious lack of jquery understanding
I have a mobile menu that extrudes from the left, 25% of my page width when opened. My problem is, if I have already scrolled down my page and then decide to open my mobile menu, the page returns to the top and the menu opens. How do I prevent the page from returning to the top and keep my scrolling placement.
I'm using a jquery plugin?
Thanks
;(function ($, window) {
"use strict";

var namespace = "shifter",
    initialized = false,
    hasTouched = false,
    data = {},
    classes = {
        handle: "shifter-handle",
        page: "shifter-page",
        header: "shifter-header",
        navigation: "shifter-navigation",
        isEnabled: "shifter-enabled",
        isOpen: "shifter-open"
    },
    events = {
        click: "touchstart." + namespace + " click." + namespace
    };

/**
 * @options
 * @param maxWidth [string] <'980px'> "Width at which to auto-disable plugin"
 */
var options = {
    maxWidth: "980px"
};

var pub = {

    /**
     * @method
     * @name close
     * @description Closes navigation if open
     * @example $.shifter("close");
     */
    close: function() {
        if (initialized) {
            data.$html.removeClass(classes.isOpen);
            data.$body.removeClass(classes.isOpen);
            data.$shifts.off( classify(namespace) );
            // Close mobile keyboard if open
            data.$nav.find("input").trigger("blur");
        }
    },

    /**
     * @method
     * @name enable
     * @description Enables navigation system
     * @example $.shifter("enable");
     */
    enable: function() {
        if (initialized) {
            data.$body.addClass(classes.isEnabled);
        }
    },

    /**
     * @method
     * @name destroy
     * @description Removes instance of plugin
     * @example $.shifter("destroy");
     */
    destroy: function() {
        if (initialized) {
            data.$html.removeClass(classes.isOpen);
            data.$body.removeClass( [classes.isEnabled, classes.isOpen].join(" ") )
                      .off(events.click);

            // Navtive MQ Support
            if (window.matchMedia !== undefined) {
                data.mediaQuery.removeListener(onRespond);
            }

            data = {};
            initialized = false;
        }
    },

    /**
     * @method
     * @name disable
     * @description Disables navigation system
     * @example $.shifter("disable");
     */
    disable: function() {
        if (initialized) {
            pub.close();
            data.$body.removeClass(classes.isEnabled);
        }
    },

    /**
     * @method
     * @name open
     * @description Opens navigation if closed
     * @example $.shifter("open");
     */
    open: function() {
        if (initialized) {
            data.$html.addClass(classes.isOpen);
            data.$body.addClass(classes.isOpen);
            data.$shifts.one(events.click, onClick);
        }
    }
};

/**
 * @method private
 * @name init
 * @description Initializes plugin
 * @param opts [object] "Initialization options"
 */
function init(opts) {
    if (!initialized) {
        data = $.extend({}, options, opts || {});

        data.$html = $("html");
        data.$body = $("body");
        data.$shifts = $( [classify(classes.page), classify(classes.header)].join(", ") );
        data.$nav = $( classify(classes.navigation) );

        if (data.$shifts.length > 0 && data.$nav.length > 0) {
            initialized = true;

            data.$body.on(events.click, classify(classes.handle), onClick);

            // Navtive MQ Support
            if (window.matchMedia !== undefined) {
                data.mediaQuery = window.matchMedia("(max-width:" + (data.maxWidth === Infinity ? "100000px" : data.maxWidth) + ")");
                data.mediaQuery.addListener(onRespond);
                onRespond();
            }
        }
    }
}

/**
 * @method private
 * @name onRespond
 * @description Handles media query match change
 */
function onRespond() {
    if (data.mediaQuery.matches) {
        pub.enable();
    } else {
        pub.disable();
    }
}

/**
 * @method private
 * @name onClick
 * @description Determines proper click / touch action
 * @param e [object] "Event data"
 */
function onClick(e) {
    e.preventDefault();
    e.stopPropagation();
    e.isPropagationStopped();

    if (!hasTouched) {
        if (data.$body.hasClass(classes.isOpen)) {
            pub.close();
        } else {
            pub.open();
        }
    }

    if (e.type === "touchstart") {
        hasTouched = true;

        setTimeout(resetTouch, 500);
    }
}

/**
 * @method private
 * @name resetTouch
 * @description Resets touch state
 */
function resetTouch() {
    hasTouched = false;
}

/**
 * @method private
 * @name classify
 * @description Create class selector from text
 * @param text [string] "Text to convert"
 * @return [string] "New class name"
 */
function classify(text) {
    return "." + text;
}

$[namespace] = function(method) {
    if (pub[method]) {
        return pub[method].apply(this, Array.prototype.slice.call(arguments, 1));
    } else if (typeof method === 'object' || !method) {
        return init.apply(this, arguments);
    }
    return this;
};

})(jQuery, window);


text:
Q: Are developers expected to have skills of business analysts? Our business analyst has left the team. We are now expected to do the work which was previously done by the business analyst, and the management thinks that a task which is done in three months by a business analyst can be done in one month by a developer.
My experience is in programming only, and I'm not familiar to the business intelligence tools. To me this seems like maybe an unfair comparison or expectation, and might even trivialize the role of a business analyst.
Has anyone else encountered this situation? How to deal with it?

A: I agree with gnat's comment. Also, the B.A. took 3 months not because she is not professional enough as a programmer. Most probably the time taken in analysis is significant because the amount of customer interaction required (which usually fits the customer timetable) and the time taken in writing down detailed documentation.
Most Business Analysis tools are not complex to learn for a programmer (given the right training). However, the business analysis concepts and the domain expertise can take time.
If the remaining work is not significant, maybe more than one developer could cooperate to finalize the work that has been done in a short time. But the rule set that if B.A. takes 3 months to do the job, then it takes the programmer 1 month is not valid as stated. It sounds like comparing a dentist work to a brain surgeon's work!
In any case, the project manager should flag this as a risk in the project.

A: I'm assuming that your business analyst is a subject matter expert - they understand the organization and the industry that the organization operates in extremely well, and they probably have a very good understanding of appropriate laws and regulations that apply to what the organization does.
I would expect a developer, especially one who has been with the organization for a while, to have begun to acquire some of the skills of a business analyst. Perhaps not necessarily how to use the tools they do, but at least the domain knowledge regarding the organization, the industry, and regulations. However, I wouldn't expect any developer to be a drop-in replacement for a business analyst, must less have the ability to perform work and have a higher productivity than a business analyst.
To me, the timetable sounds like a major project risk. In order for a developer to function as a business analyst, there must be time allocated to become much more familiar with the domain as well as the tools used before the developer can function at the same productivity as an equally dedicated and knowledgeable business analyst.
I would recommend sitting down with management - explain what you would need to do to become as familiar with the environment as the business analyst who left and estimate the time that it would take you to reach that level of familiarity. Only after that time can you do the work.

A: I agree with gnat's comment, too, but I have also seen a lot of situations where splitting the roles between analyst (with no programming tasks) and developers (who are not allowed to talk to the customer directly) lead to "Chinese whisper". To my experience, you can often save a lot of effort and misunderstanding if your analyst is a senior programmer who does some essential parts of the programming by himself, and talks to the rest of the team not just in plain English, but also by utilizing the programming languages of the team.
So the expectation of your management that you might save some time and effort with no BA might not be completely wrong.

A: In the positive side, if you get such an opportunity, you can utilize it well to improve yourself. It might be helpful to you when you get upgraded to a higher level. Obviously, it will be a great risk for the entire project since you can't concentrate on both of your positions, especially with a vague knowledge. Even though it's not your problem, if you really work hard, it would be easy for you to learn the tactics. However, if you find it really disgusting to do both at a time, then you have no other choice other than explaining your inability to your higher officials. Good Luck, then!!!


text:
Q: dpkg: error processing package sudo (--configure) I'm trying to set up a VM network using vmbuilder. When setting it up using Ubuntu 12.04 there are no problems. However, when trying any of the newer LTS (14.04 or 16.04) i get the following error when I try to build my KVM:
Configuration file '/etc/sudoers'
==> Modified (by you or by a script) since installation.
==> Package distributor has shipped an updated version.
What would you like to do about it ?  Your options are:
Y or I  : install the package maintainer's version
N or O  : keep your currently-installed version
  D     : show the differences between the versions
  Z     : start a shell to examine the situation
The default action is to keep your current version.
*** sudoers (Y/I/N/O/D/Z) [default=N] ? dpkg: error processing package sudo (--configure):
EOF on stdin at conffile prompt
Errors were encountered while processing:
sudo
E: Sub-process /usr/bin/dpkg returned an error code (1)

I have read a bunch of similar issues where the recommendation is more or less to blow out the whole system. This is however VERY undesirable in this case since we are running jobs on the computer each day. So please, if anyone knows a workaround??
FYI, this is how my VM.sh looks:
vmbuilder kvm ubuntu \
    --dest=/home/pett/VM \
    --overwrite \
    --mem=15000\
    --cpus=4 \
    --rootsize=10240\
    --swapsize=5000\
    --addpkg=openssh-server \
    --addpkg=vim \
    --addpkg=cron \
    --addpkg=acpid \
    --arch=amd64 \
    --suite=trusty\
    --flavour virtual \
    --components main,universe,restricted \
    --hostname Buri \
    --user pett \
    --pass hello \
    --libvirt qemu:///system ;

PS the following did NOT solve it:
sudo apt-get update

sudo apt-get clean

sudo apt-get autoremove

sudo apt-get update && sudo apt-get upgrade

sudo dpkg --configure -a

sudo apt-get install -f

A: I have exactly the same bug, on several fresh 1604 installations. I don't know why this doesn't get fixed, because it would come up if they ever tested this package.
The solution I found from another post is:

*

*change the word 'dist-upgrade' to 'update' in
/usr/lib/python2.7/dist-packages/VMBuilder/plugins/ubuntu/dapper.py

*delete /usr/lib/python2.7/dist-packages/VMBuilder/plugins/ubuntu/dapper.pyc
Annoying that the "solution" to a problem like this is to edit the installed package, but that's what it is.

A: Note that there is a slightly better maintained community fork of python-vm-builder at https://github.com/newroco/vmbuilder.
Instead of using the system package, you install it with sudo python setup.py install

A: From launchpad discussion:

can you find in file /usr/lib/python2.7/dist-packages/VMBuilder/plugins/ubuntu/dapper.py
  next string:
self.run_in_target('apt-get', '-y', '--force-yes', 'dist-upgrade',
and replace with:
self.run_in_target('apt-get', '-y', '--force-yes',
  '--option=Dpkg::Options::=--force-confnew', 'dist-upgrade',
and try to build new vm after that.
I describe similar situation on my blog
  http://anzhiganov.com/2016/11/02/869/. it was useful for me.


text:
Q: Use xvfb to automate X program I originally posted this question here, but upon second thoughts I decided here was a better place for this.
I sadly have to use this proprietary program that bundles a camera driver. I want to perform a specific action with it, which involves clicking a few buttons. And there is no CLI.
So, what is the easiest way to automate this? I though of using xvfb to open the program in a fake X environment, but then how would I go about performing input operations? It could be click pixel at (x, y), but it would be even nicer if I could reference buttons and menu items.
If there is a simpler way to do it, please tell! I'm not sure xvfb is the correct method. I don't even know the actual name of what I'm trying to accomplish, so searching is very hard...

A: You can use xdotool which can fake keyboard/mouse input, window management, and more.
See example.sh script for xcalc "4*9=", to view capture-result image:
#!/usr/bin/env bash

save="$DISPLAY"                          # save original X display number
export DISPLAY=:44                       # set random choosen display for xvfb
case "$1" in                             #         and x-programs called below
  start) Xvfb $DISPLAY &   ;;            # starting xvfb server on :44
   calc) xcalc &           ;;            # run x-calculator
    xdo) xdotool mousemove 1 1 click 1   # focus with click on x:y=1:1
         xdotool key 4 asterisk 9        # calc 4*9
         xdotool key equal ;;            #         =
   show) #capture root window ('36' result image) and display it to saved Xno
         xwd -root | xwud -display $save &                                   ;;
   stop) ps auxww | grep "Xvfb $DISPLAY" | awk '{print $2}' | xargs kill     ;;
    all) DISPLAY=$save; $0 start; $0 calc; sleep 1; $0 xdo; $0 show; $0 stop ;;
esac

Note: Individual options can be used for testing, or run all with ./example.sh all.


text:
Q: Cropping UIImage - change background color I have a function that crops a UIImage to the dimensions of a given rectangle. Sometimes part of the rectangle falls outside the image. After cropping, the default color of this extra part is white. Is it possible to change this color?
func crop(mainImage:UIImage, rectangle:CGRect) -> UIImage?{

    let rectSize = CGSize(width: floor(rectangle.width), height: floor(rectangle.height))
    UIGraphicsBeginImageContextWithOptions(rectSize, false, mainImage.scale)
    let context:CGContext = UIGraphicsGetCurrentContext()!;
    mainImage.draw(at: CGPoint(x: -rectangle.origin.x, y: -rectangle.origin.y))
    let croppedImage = UIGraphicsGetImageFromCurrentImageContext()!
    UIGraphicsEndImageContext()
    return croppedImage
}

A: You can use extension
    extension UIImage {
        func crop( rect: CGRect) -> UIImage {
            var rect = rect
            rect.origin.x*=self.scale
            rect.origin.y*=self.scale
            rect.size.width*=self.scale
            rect.size.height*=self.scale

            let imageRef = self.cgImage!.cropping(to: rect)
            let image = UIImage(cgImage: imageRef!, scale: self.scale, orientation: self.imageOrientation)
            return image
        }
    }

either use method like below

/**
     Extracts image at a given rect from an image
     - parameter rect : rect for which UIImage should be extracted within
     - returns : new UIImage created from rect value supplied
     */
    func imageByCroppingAtRect(_ rect: CGRect) -> UIImage? {

        let imageRef: CGImage? = cgImage?.cropping(to: rect)
        if imageRef == nil {
            return nil
        } else {
            let subImage: UIImage = UIImage(cgImage: imageRef!)
            return subImage
        }
    }


text:
Q: pyodbc Operation Error when I try to access my database it consistently saying server is not found or accessible but docker shows it up and running Using Docker, I'm creating a SQL Server 2019 image & container and I currently cannot execute my Python script which accesses the database and prints out the results within specific table. the SQL Server is running in a docker container. I'm accessing the script within the terminal which is just a python file located inside my local directory.
Here's my code:
import pyodbc
connector = pyodbc.connect('Driver={ODBC Driver 18 for SQL Server};' 'Server=cbbcb967dacb;' 'Database=testdb;' 'UID=sa;' 'PWD=Password' 'Trusted_Connection=yes;')
connector.execute()

cursor = connector.cursor()
cursor.execute('SELECT * FROM inventory')

for i in cursor:
    print(i)

The error I get is

pyodbc.OperationalError: ('08001', '[08001] [Microsoft][ODBC Driver 18 for SQL Server]Named Pipes Provider: Could not open a connection to SQL Server [53].  (53) (SQLDriverConnect); [08001] [Microsoft][ODBC Driver 18 for SQL Server]Login timeout expired (0); [08001] [Microsoft][ODBC Driver 18 for SQL Server]A network-related or instance-specific error has occurred while establishing a connection to SQL Server. Server is not found or not accessible. Check if instance name is correct and if SQL Server is configured to allow remote connections. For more information see SQL Server Books Online.

I downloaded the ODBC driver 18 prior and when I change driver to 'ODBC Driver 17 for SQL Server' the error is:

Data source name not found and no default driver specified

and when I use 'SQL Server', the code returns the error above. I got the database name by running select @@servername and obviously used the password I initially created for the container.
My queries to the database and table are valid as I see the results in terminal: