text:
Q: Can't find algorithm implementation in opencv I cannot find the implementation of the Voila-Jones-algorithm that is useing Haar features in OpenCV.
I have an example class from that I want to follow the method calls via F12 in VisualStudio. What I want is to jump througt the .cpp files to see the implementations. But what I get is only the declaration in the .hpp files. For example, the calls I want to follow are detectMultiScale(...) and CascsadeClassifier.
With the standard download of OpenCV 3.0 and 3.1, I could run the example class, but, as mentioned, couldn't F12 throug the code.
I tried to build openCV from the sources on github by this tutorial but I get Linker Errors like

main.obj : error LNK2001: Nicht aufgelöstes externes Symbol ""void __cdecl cv::imshow(class cv::String const &,class cv::_InputArray const &)" (?imshow@cv@@YAXABVString@1@ABV_InputArray@1@@Z)"
  and
  1>LINK : fatal error LNK1104: Datei "opencv_aruco310d.obj" kann nicht geöffnet werden.

when I want to run the code.
Building ends without failures, but when I want to add  the additional dependencies to the VS project, there are only .lib files for the debugger, none for the release.
Can anybody help?


text:
Q: Android- Upload photo to the server the UploadProduct.class register a product in my database and upload the photo to my server.
I am trying to upload a file to my server.
 When I execute my app this work perfectly, the product is registered in the database  but in my server , the photo had not been loaded.
When I debug , I put a breakpoint in  httppost.setEntity(mpEntity); , the value of file atribute is /storage/emulated/0/aaaa/20150529_104715.jpg
The path where I save my files is http://aaaa.com/app/imagenes/ and the path of upload.php is http://aaaa.com/app
Here my code:
atributes:
private List<NameValuePair> params = new ArrayList<NameValuePair>(1);
private File file;
private String imageFileName = "";
private String urlImag ="http://aaaa.com/app/imagenes/";
private EditText  etNombreProducto,etDescripcion,etPrecioDia,etPrecioSemana;
private Bitmap bitmap=null;

methods:
public void takePhoto() {

        String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
        imageFileName = timeStamp  + ".jpg";

        //Creamos el Intent para llamar a la Camara
        Intent cameraIntent = new Intent(
                android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
        //Creamos una carpeta en la memeria del terminal
        File imagesFolder = new File(
                Environment.getExternalStorageDirectory(), "aaaa");
        imagesFolder.mkdirs();
        //anadimos el nombre de la imagen
        file= new File(imagesFolder, imageFileName);
        Uri uriSavedImage = Uri.fromFile(file);
        //Le decimos al Intent que queremos grabar la imagen
        cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, uriSavedImage);
        //Lanzamos la aplicacion de la camara con retorno (forResult)
        startActivityForResult(cameraIntent, 1);

    }

    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        //Comprovamos que la foto se a realizado
        if (requestCode == 1 && resultCode == RESULT_OK) {
            //Creamos un bitmap con la imagen recientemente
            //almacenada en la memoria
            bitmap= BitmapFactory.decodeFile(
                    Environment.getExternalStorageDirectory() +
                            "/aaaa/" + imageFileName);
//            //Anadimos el bitmap al imageView para
//            //mostrarlo por pantalla
//            img.setImageBitmap(bMap);
        }
    }

    private boolean uploadFoto(String imag){
        HttpClient httpclient = new DefaultHttpClient();
        httpclient.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
        HttpPost httppost = new HttpPost("http://aaaa.com/app/upload.php");
        MultipartEntity mpEntity = new MultipartEntity( );

        ContentBody contentBody = new FileBody(file,"image/jpeg");
        mpEntity.addPart("foto", contentBody);
        httppost.setEntity(mpEntity);
        try {
            httpclient.execute(httppost);
            httpclient.getConnectionManager().shutdown();
            return true;
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return false;
    }
    private boolean onInsert(){
        String nombreP = etNombreProducto.getText().toString();
        String descripcion = etDescripcion.getText().toString();
        String precioD = etPrecioDia.getText().toString();
        String precioS=etPrecioSemana.getText().toString();
        HttpClient httpclient;

        params.add(new BasicNameValuePair("nombre", nombreP));
        params.add(new BasicNameValuePair("descripcion", descripcion));
        params.add(new BasicNameValuePair("preciodia", precioD));
        params.add(new BasicNameValuePair("preciosemana", precioS));
        params.add(new BasicNameValuePair("imagen", urlImag + imageFileName));
        HttpPost httppost;
        httpclient=new DefaultHttpClient();
        httppost= new HttpPost("http://aaaa.com/app/insertProduct.php");
        // Url del Servidor

        try {
            httppost.setEntity(new UrlEncodedFormEntity(params));
            httpclient.execute(httppost);
            return true;
        } catch (UnsupportedEncodingException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return false;
    }

    private void serverUpdate(){
        if (file.exists())
            new ServerUpdate().execute();
        else
            Toast.makeText(UploadProduct.this, "Debes de hacer una foto",
                    Toast.LENGTH_LONG).show();

    }

    class ServerUpdate extends AsyncTask<String,String,String> {

        ProgressDialog pDialog;
        @Override
        protected String doInBackground(String... arg0) {
            Boolean b=uploadFoto(imageFileName);
            if(onInsert()&& b)
                runOnUiThread(new Runnable(){
                    @Override
                    public void run() {
                        // TODO Auto-generated method stub
                        Toast.makeText(UploadProduct.this, "Exito al subir la imagen",
                                Toast.LENGTH_LONG).show();
                    }
                });
            else
                runOnUiThread(new Runnable(){
                    @Override
                    public void run() {
                        // TODO Auto-generated method stub
                        Toast.makeText(UploadProduct.this, "Sin exito al subir la imagen",
                                Toast.LENGTH_LONG).show();
                    }
                });
            return null;
        }
        protected void onPreExecute() {
            super.onPreExecute();
            pDialog = new ProgressDialog(UploadProduct.this);
            pDialog.setMessage("Actualizando Servidor, espere..." );
            pDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
            pDialog.show();
        }
        protected void onPostExecute(String result) {
            super.onPostExecute(result);
            pDialog.dismiss();
        }

    }

my upload.php
<?php

    $ruta = "app/imagenes/" .basename($_FILES['foto']['name']);
    if(move_uploaded_file($_FILES['foto']['tmp_name'], $ruta)){
            echo "success";
        } else{
            echo "fail";
        }
    ?>

A: In my case , I had to put the absolute path in my php file.
upload.php
<?php
// En versiones de PHP anteriores a 4.1.0, $HTTP_POST_FILES debe utilizarse en lugar
// de $_FILES.

$uploaddir = '/var/www/vhosts/aaaa.com/httpdocs/app/imagenes/';
$uploadfile = $uploaddir . basename($_FILES['foto']['name']);

echo 'bien';
if (move_uploaded_file($_FILES['foto']['tmp_name'], $uploadfile)) {
    echo "El archivo es válido y fue cargado exitosamente.\n";
} else {
    echo "¡Posible ataque de carga de archivos!\n";
    echo $_SERVER['DOCUMENT_ROOT'];
}

echo 'Aquí hay más información de depurado:';

?>

thanks for your help

A:     $profilepic = $_FILES ['foto'] ['name'];
    // let if  jpeg image
    $extension='.jpeg';

    function saveImageInServer($profileimage, $email,$extension ) {
        $dir = '/var/www/users';
        if (is_dir ( $dir ) == false) {
            mkdir ( $dir );
        }
        chmod ( $dir, 0777 );
        $target_Path = $dir . "/" . $email . "." . $extension;
        move_uploaded_file ( $_FILES ['proiflepic'] ['tmp_name'], $target_Path );
        chmod ( $target_Path, 0777 );
    }

redpajama_set_name: RedPajamaStackExchange


text:
Q: Javascript group similarities I have in JavaScript JSON object the following code:
{
apple: 'value',
orange: 'value',
string1Pear: 'value',
string1Banana: 'value',
string2Pear: 'value',
string2Banana: 'value',
pineapple: 'value'
}

I need to group the similar keys for a given object without knowing if there is there is such or what they would look like.
The end result should be something like this:
{
apple: 'value',
orange: 'value',
string: {
   string1: {
      string1Pear: 'value',
      string1Banana: 'value',
   },
   string2: {
      string2Pear: 'value',
      string2Banana: 'value',
   },
}
pineapple: 'value'
}

A: The solution using Object.keys(), String.prototype.match() and Array.prototype.reduce() functions:

var data = { apple: 'value', orange: 'value', string1Pear: 'value', string1Banana: 'value', string2Pear: 'value', string2Banana: 'value', pineapple: 'value'},

    result = Object.keys(data).reduce(function (r, k) {
        var parts = k.match(/(\w+\d+)([A-Z]\w+)/);
        if (!parts) {
            r[k] = data[k];
            return r;
        }
        r[parts[1]] = r[parts[1]] || {};
        r[parts[1]][k] = data[k]
        return r;
    }, {});

console.log(result);

A: If your keys are camel-cased, and you want to always group by whatever string is before the first uppercase letter, this would work:

const fruits = {
      apple: 'value',
      orange: 'value',
      string1Pear: 'value',
      string1Banana: 'value',
      string2Pear: 'value',
      string2Banana: 'value',
      pineapple: 'value'
  }

  // Split by uppercase letters and take the first word.
  function getGroup(key) {
      return key.split(/(?=[A-Z])/)[0];
  }

  // Group keys
  let newObject = {};
  const keys = Object.keys(fruits);

  for (var i = 0; i < keys.length; i++) {
      const key = keys[i];
      const group = getGroup(key);

      if (group === key) {
        newObject[group] = fruits[key];
      }
      else if (newObject.hasOwnProperty(group)) {
        newObject[group][key] = fruits[key];
      }
      else {
         newObject[group] = {};
         newObject[group][key] = fruits[key];
      }
  }

  console.log(newObject);


text:
Q: Can't connect to Firestore over Vodafone in some devices I've encountered some weird behavior using Firestore SDK over a mobile data connection in some devices.
In devices like Xiaomi, Asus and Huawei with a mobile internet connection over Vodafone (I'm from Portugal), the application can't connect to the firestore server. Also, it doesn't provide any error messages, like no network for instance , but sometimes it does show the error "client is offline".
Over wifi there is no problem connecting to the server, and using other portuguese mobile internet providers like NOS or MEO or using other devices with Vodafone, there is no problem connecting to the server.
I've tried in the same device, changing the SIM card from Vodafone, not working, to NOS and it works perfectly.
This project shows that error, for those devices and for that mobile data connection.
When the app starts it tries to get data from the server, and instead of returning and error, it returns empty data.
The logs for this error can be found in logs.txt  file.
There is a log in the logs file that says Firestore: (0.6.6-dev) [OnlineStateTracker]: Could not reach Firestore backend.
Any suggestions is appreciated on how to solve this.
You can see the sample project here https://github.com/tallnato/firebase-mobile-data-bug


text:
Q: Sql server replication - Slow transfer, even with compressed FTP file I have a transactional pull replication running.
The publisher and the distributor are both SQL server 2012.
The subscriber is a SQL express 2012.
I have setup the server to get the initial snapshot from a compressed FTP file. The data transfered is already filtered to the minimum required. Those parts work fine.
Where it seems to have a problem is when the subscriber tries to apply the snapshot. On a high bandwidth network, the snapshot is applied in less then one minute. On a low bandwidth network, the snapshot can take up to 20 minutes to apply.
On the 20 minutes, downloading the FTP snapshot from the low bandwidth subscriber takes 2 minutes.After this, applying the decompressed local files is taking the other 18 minutes.
The ftp snapshots are not supposed to be run locally ?
Why applying local file on the local server takes 18 minutes on a low bandwidth network subscriber and only takes few seconds on high bandwidth network subcriber ?
Thanks !


text:
Q: VPN connected but no access to anything I have a problem with the VPN server on 2008R2. I can successfully connect to the VPN server but i cannot map any drives either by IP or by name. I can ping hosts by ip but not the name. In addition I can access shares and RDP only to the VPN server but not to any others.
What could be the problem? Please Help!

A: Symantec Endpoint Protection was blocking traffic.


text:
Q: Share webpages between multiple websites (Best Way) I have created two websites using C# in Visual studio 2008. Both websites having common maintenance (User and Role) pages. I have also create a common class library (C#) and added reference to both website, which is working properly.
I don't want to replicate/maintain the multiple copies of the same aspx pages.
Is there any better way except user controls, to have single copy of common aspx pages and add reference to both website, just like class library?
Thanks.

A: In your response to Mr.Lister it sounds like you aren't using a master page, and your really should.


text:
Q: What's the best way to load the google maps api into angular2? I have played around with angular2 maps, but in the end I think I want to use the google maps api directly.
What's the best/right way to load this into angular 2? Currently I am loading it via a script tag, inserted into the index.html file, like so.
<!doctype html>
<html>
<head>
  <meta charset="utf-8">
  <title>Ourlatitude</title>
  <base href="/">

  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="icon" type="image/x-icon" href="favicon.ico">
  <link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
  <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Roboto:300,400,500,700,400italic">
</head>
<body>
    <script
    src="https://maps.googleapis.com/maps/api/js?key=my_api_key">
    </script>
  <app-root>Loading...</app-root>
</body>
</html>

Then I create a map in a component inside the ngAfterViewInit() hook of the component that will hold the map.
ngAfterViewInit() {
    this.map = new google.maps.Map(this.mymap.nativeElement, {zoom: 4, center: {lat: -25.363, lng: 131.044} });
}

This seems to work, but adding the script tag does not seem like the right thing to do.  I tried adding the script to the angular-cli.json scripts: [] array, but that does not seem to work (the call to new google.maps.Map() fails with google being undefined).
BTW, I installed the types via npm install --save @types/google-maps and they seem to be recognized.

A: This is how I integrated google-maps:

*

*I created script load service, which loads scripts only when
required -
import { Injectable } from '@angular/core';
@Injectable()
export class ScriptLoadService {

  constructor() { }

  public loadScript(url, id, c): void {
    if (!document.getElementById(id)) {
      const script = document.createElement('script');
      script.type = 'text/javascript';
      script.src = url;
      script.id = id;
      if (c) {
        script.addEventListener('load', function (e) {
          c(null, e);
        }, false);
      }
      document.head.appendChild(script);
    }
  }

}

*Add your googleMapURL in your environment file

googleMapURL:
'https://maps.googleapis.com/maps/api/js?key=XXXXXXXXXXXXXXXXXXXXXXXXXXXXX&libraries=places'

*Now you can use use google maps api in any component by injecting
ScriptLoadService and in ngOnInit or ngAfterViewInit call loadScript
funcion:
@ViewChild('mapElement') mapElm: ElementRef; // to display map
constructor( private scriptLoadService: ScriptLoadService ) {} // inject the service

  ngAfterViewInit() {
    this.scriptLoadService.loadScript(environment.googleMapURL, 'google-map', () => {
      this.center = new google.maps.LatLng(
        this.lat,
        this.lng);

      // Create map
      this.map = new google.maps.Map(this.mapElm.nativeElement, {
        zoom: 18,
        center: this.center,
        disableDefaultUI: true,
        scrollwheel: false,
      });

      // Add Marker to current location detected by browser
      this.marker = new google.maps.Marker({
        position: this.center,
        map: this.map
      });
});
}

Hope this helps :)

A: Try using Getting started, this document let's you start from scratch and build an Angular 2 app with angular2-google-maps. It is more cleaner and more efficient way to load google maps api, as it is integrated using angular2.
To familiarize yourself with angular2 and angular2-google-maps and don't want to set up a full project with NPM, you can use the following Plunker. It has all the dependencies to play with Angular2, Typescript and of course angular2-google-maps: Plunkr link.
<!DOCTYPE html>
<html>
  <head>
    <title>Angular 2 QuickStart</title>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <script src="https://unpkg.com/zone.js@0.6.21/dist/zone.js"></script>
    <script src="https://unpkg.com/reflect-metadata@0.1.3/Reflect.js"></script>
    <script src="https://unpkg.com/systemjs@0.19.31/dist/system.js"></script>
    <script src="https://unpkg.com/typescript@1.8.10/lib/typescript.js"></script>
    <script src="systemjs.config.js"></script>

    <script>
    System.import('app')
      .catch(console.error.bind(console));
  </script>
  </head>

  <!-- 3. Display the application -->
  <body>
    <my-app>Loading...</my-app>

  </body>

</html>

<!--
Copyright 2016 Google Inc. All Rights Reserved.
Use of this source code is governed by an MIT-style license that
can be found in the LICENSE file at http://angular.io/license
-->


text:
Q: HttpGet sends request with the wrong encoding I'm trying to get the text response from the following URL:
http://translate.google.cn/translate_a/single?client=t&sl=zh-CN&tl=en&dt=t&tk=265632.142896&q=%E4%BD%A0%E5%A5%BD

The response is the following:
[[["Hello there","你好",,,1]],,"zh-CN"]

(You can verify this response by entering the address into your browser.)
Here is a simplified version of my code that tries to download this text:
import org.apache.http.client.HttpClient;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.DefaultHttpClient;

public class Test {
    public static String downloadString() {
        String url = "http://translate.google.cn/translate_a/single?client=t&sl=zh-CN&tl=en&dt=t&tk=265632.142896&q=%E4%BD%A0%E5%A5%BD";
        HttpClient client = new DefaultHttpClient();
        HttpGet request = new HttpGet(url);
        ResponseHandler<String> handler = new BasicResponseHandler();
        try {
            return client.execute(request, handler);
        } catch (Exception e) {
            return "GET request failed.";
        }
    }
}

When I call Test.downloadString(), I get the following (incorrect) response:
[[["Huan Chai Sunsolt","浣犲ソ",,,0]],,"zh-CN"]

I'm guessing that there is some sort of encoding problem behind the scenes somewhere in the request process (there are six bytes that should be interpreted as two Chinese characters, but are instead interpreted as three Japanese characters), but I can't seem to pinpoint the exact cause. What am I doing wrong in my code?

A: It's strange, but adding the User-Agent header fixed the problem:
request.addHeader("User-Agent", "Mozilla/5.0 (X11; Linux x86_64; rv:33.0) Gecko/20100101 Firefox/33.0");

A: Android 6.0 release removes support for the Apache HTTP client. If your app is using this client and targets Android 2.3 (API level 9) or higher, use the HttpURLConnection class instead.
here: http://developer.android.com/about/versions/marshmallow/android-6.0-changes.html#behavior-apache-http-client


text:
Q: Rx Java vs Rx C# I am starting to learn Rx for C# with this ebook, but since I also work a lot with Java I am wondering about how Rx for C# and Rx for Java may differ. This way I can learn one and then just focus on the differences between them to finally learn both.
What discrepancies I might expect from Rx for C# and Rx for Java? How they differ from each other? What are their limitations? What one accomplishes that the other can't?


text:
Q: Set Event Log settings via GPO How would I set the "overwrite as needed" setting on Event logs other than Application/Security/System?  Specifically I'd like to apply this to the Powershell and Windows Powershell Logs, in addition to any other future logs that may be added.  This needs to be applied to both server 2003 & 2008.

A: Wow. I looked around on this and can't find any references to set GPO settings for event logs other than for System, Application, Security. That just seems wrong. You will have to script it for your domain or workgroup or workstation with wevtutil.exe (cmd) or limit-eventlog (powershell). Both utilities have remote connection built in.
wevtutil sl <Log Name> /rt:false

limit-eventlog -Log Name  -OverFlowAction OverwriteAsNeeded

A: I don't believe their is a GPO for this.  But most group policies simply modify the registry.
You could create an adm template that modified the settings, or you could simply write a script to adjust the settings.
HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\Eventlog\PowerShell

If you are not sure how to manually configure the settings, simply adjust the settings in the event log GUI, and set all your other systems to be the same.  You may need to restart the system for the changes to go into effect.

A: Right now you'd need to use SDM Software's GPO cmdlets. That's the only way from within PowerShell to modify the settings within a GPO. But there's no way that I know of to make a change to "any logs which might be added" - I don't think you can modify the system defaults (although I could be wrong - it's not something I've done much).

A: Computer Configuration-->Windows Settings-->Security Settings-->Event Log


text:
Q: One app -> multiple languages So I have my app in the App Store. I have the app in my language(Norwegian), and I have the same app in English, but right now there are two different apps in the App Store. The apps are 100% the same, but I have made it as two different apps in the App Store and iTunes Connect because they are different languages. Is it possible that I only have it as one app in iTunes Connect? Hope you understand my question.

A:
Is it possible that I only have it as one app in iTunes Connect?

Yes. Abandon one of the apps (remove it from the store) and localize the other app for Norwegian and English.


text:
Q: How can I get all my contacts phone numbers into an array? How can I get all my contacts phone numbers into an array? I need this, to send the array to my Server/DB to check, if one or more numbers exist in the Database.
I still work with Swift 2, later also with Swift 3.
This code works, but I think, it exist a much more better version.
// With help: http://stackoverflow.com/questions/37039103/how-to-fetch-only-mobile-numbers-in-swift-using-cncontacts
// With help: http://stackoverflow.com/questions/32669612/how-to-fetch-all-contacts-record-in-ios-9-using-contacts-framework/34095632

let store = CNContactStore()

store.requestAccessForEntityType(.Contacts, completionHandler: {
    granted, error in

    guard granted else {
        let alert = UIAlertController(title: "Can't access contact", message: "Please go to Settings -> MyApp to enable contact permission", preferredStyle: .Alert)
        alert.addAction(UIAlertAction(title: "OK", style: .Default, handler: nil))
        self.presentViewController(alert, animated: true, completion: nil)
        return
    }

    let keysToFetch = [CNContactFormatter.descriptorForRequiredKeysForStyle(.FullName), CNContactPhoneNumbersKey]
    let request = CNContactFetchRequest(keysToFetch: keysToFetch)
    var cnContacts = [CNContact]()

    do {
        try store.enumerateContactsWithFetchRequest(request){
            (contact, cursor) -> Void in
            cnContacts.append(contact)
        }
    } catch let error {
        NSLog("Fetch contact error: \(error)")
    }

    var mobilenumbers: [String] = []

    NSLog(">>>> Contact list:")
    for contact in cnContacts {
        let fullName = CNContactFormatter.stringFromContact(contact, style: .FullName) ?? "No Name"
        NSLog("\(fullName): \(contact.phoneNumbers.description)")

        // If phoneNo a Mobilenumber, then put into Array:
        for phoneNo in contact.phoneNumbers {
            if phoneNo.label == CNLabelPhoneNumberMobile {
                let istEineMobileNummer = (phoneNo.value as! CNPhoneNumber).stringValue

                    mobilenumbers.append(istEineMobileNummer)
            }
        }
    }

    print("Print all Mobilenumbers:")
    print(mobilenumbers)
})

A: You can attempt to do this by using the Contacts Framework.
You'll need to ask for the user's permission before accessing this information.


text:
Q: Connection refuse postgresql when use docker with Laravel I've been trying for a few hours to make a connection between laravel and the docker database and try a migrated php artisan
Everything starts correctly but I run into the problem that I can't connect the laravel to the database
Do you have any idea why this is happening?
This is my env
DB_CONNECTION=pgsql
DB_HOST=postgres
DB_PORT=5432
DB_DATABASE=smart
DB_USERNAME=admin
DB_PASSWORD=secret

My docker file
RUN apt-get update && apt-get install -y \
        libpng-dev \
        zlib1g-dev \
        libxml2-dev \
        libzip-dev \
        libonig-dev \
        zip \
        curl \
        unzip \
    && docker-php-ext-configure gd \
    && docker-php-ext-install -j$(nproc) gd \
    && docker-php-ext-install pdo_mysql \
    && docker-php-ext-install mysqli \
    && docker-php-ext-install zip \
    && docker-php-source delete \
    && apt-get install -y postgresql-client

And my docker yml
services:
  app:
    build:
      context: .
      dockerfile: .docker/Dockerfile
    image: 'server'
    ports:
      - 8080:80
    volumes:
      - ./:/var/www/html
database:
    image: postgres
    container_name: database
    restart: unless-stopped
    environment:
        POSTGRES_PASSWORD: secret
        POSTGRES_DB: smart
        POSTGRES_USER: admin
    volumes:
        - ./postgres-data:/var/lib/postgresql/data
    ports:
        - '5432:5432'

The problem is, I can't figure out exactly why this is happening. The laravel server works perfectly, I can access it but when I connect the database everything breaks down
 Illuminate\Database\QueryException

  could not find driver (SQL: select * from information_schema.tables where table_schema = public and table_name = migrations and table_type = 'BASE TABLE')

EDIT::
Apparently I can't connect. to the database because it doesn't start as I would have liked, I can't even access it from the url how do I access the laravel server, opinions?

A: You don't seem to have installed the postgres driver in your docker environment.
Add this to your script.
&& docker-php-ext-install pdo pdo_pgsql


text:
Q: Can we prove that an extension to a structure is consistent if the original structure is? As I understand it, there is no way to prove that $\mathbb{N}$, as modeled by P.A., is consistent - meaning it may be possible to demonstrate eg. $5 = 3$. Therefore it is presumably also impossible to prove that $\mathbb{Z}$ - the extension of $\mathbb{N}$ with additive inverses - is consistent.
But could we at least prove that $\mathbb{Z}$ is consistent if $\mathbb{N}$ is? Could we do the same for $\mathbb{Q}$, $\mathbb{R}$, $\mathbb{C}$?

A: I think you have this backwards: structures are neither consistent or inconsistent, theories are!  Furthermore, given any structure $\mathfrak{A}$ over a (first-order) language, the set $\mathrm{Th} ( \mathfrak{A} )$ of all sentences true in $\mathfrak{A}$ is consistent.
The point of Gödel's (Second) Incompleteness Theorem is that unless PA is inconsistent, there is no way of proving the consistency of PA without transcending PA itself.  To quote George Boolos:

It can be proved that if it can be proved that it can't be proved that two plus two is five, then it can be proved that two plus two is five, and math is a lot of bunk.

Consequently, there is no way to prove that models of PA exist (meaning that there is no way of demonstating that a particular structure $\mathfrak{N}$ satisfies all of the axioms of PA) without transcending PA.
However, it is possible to jump to significantly stronger theories to prove the existence of models of PA.  As an example, ZF proves the existence of the smallest inductive set (a set $I$ such that $\emptyset \in I$ and $x \cup \{ x \} \in I$ for all $x \in I$), call it $N$, and furthermore via a natural translation from the language of PA into the language of set theory, ZF proves that $N$ satisfies all of the axioms of PA.
In such strong enough set theories, we may then unproblematically construct the integers, the rationals, etc.
This may be seen as simply "passing the buck": While a strong enough theory $T$ may prove the consistency of PA, this just means that the consistency of $T$ implies the consistency of PA.  In particular, $T$ itself will be subject to Gödel's Incompleteness Theorem (as long as it is sufficiently simply presented).

A: I think that what you intended to ask is a bit different than what you had asked. So, I'll rephrase your question first. It is the case that the existence of a model of $\mathbb N$ cannot be proved without making some assumption about a universe outside of $\mathbb N$. Put a bit differently, it is impossible to display a model for the natural numbers without making use of some more fundamental notion, which we must take on faith.
Your question is then whether one can exhibit a model for the integerst provided one has a model for the natural numbers, and similarly for the rationals and the reals, and beyond. The answer is yes, it can be done, in many different yet essentially the same way. Moreover, there are various paths one can take, and luckily all the intermediate stops give essentially the same notions.
So, for instance, suppose you have a model $\mathbb  N$ for the naturals satisfying Peano's axioms. You can first introduce the integers by considering the follow formal construction: Let $X=\mathbb N \times \mathbb N$, and define the equivalence relation $(x,y)\equiv(u,v)$ precisely when $x+v=u+y$. Then one can show that the quotient is a model for the integers. Or, you can first introduce the non-negative rationals by considering $Y=\{(x,y)\mid y\ne 0\}$ and the equivalence relation $(x,y)\equiv(u,v)$ precisely when $xv=yu$. Now the quotient will be a model for $\mathbb Q_+$. These are very standard constructions, and can (with a bit of care) be performed interchangeably to produce an essentially unique (that means, any two are isomorphic) model of the rationals. Now, one can complete the rationals in any of several ways to arrive at an essentially unique model of the reals. Then one can construct the complex numbers, and so on.
So, if a model of the naturals exists then it can (within some ambient set theory) be used to construct models of the integers, rationals, reals, and so on.


text:
Q: Runnable JAR file not opening JFrame I am having a mysterious problem with my JAR file not running. My game opens a JFrame object, in which all of the graphics are displayed. Everything works in Eclipse, but when I try to export my finished game as a Runnable JAR file, and then double click it from my desktop, nothing happens. I don't get an error message or anything, and my JFrame doesn't pop up, so there is no game to play.
I made sure non of my classes had any errors or warnings, and still, the JFrame doesn't open. In addition, when I right-click on the supposedly Runnable JAR file that is on my desktop, and go to properties, and then click the tab that says security, there are all check marks under the allow category under SYSTEM.
Here is my main class, if you need it, though I doubt there is a problem with the actual coding, because it works fine in Eclipse, it just doesn't open from my desktop:
package com.wierd0games.Under.main;

import java.awt.Canvas;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.image.BufferStrategy;
import java.awt.image.BufferedImage;
import java.awt.image.DataBufferInt;
import java.util.Random;

import javax.swing.JFrame;

import com.wierd0games.Under.graphics.Draw;
import com.wierd0games.Under.graphics.Sprite;
import com.wierd0games.Under.graphics.SpriteSheet;
import com.wierd0games.Under.input.Keyboard;
import com.wierd0games.Under.mobs.Frog;
import com.wierd0games.Under.mobs.Healthbar;

public class Main extends Canvas implements Runnable {
private static final long serialVersionUID=1L;
public static final int WIDTH=300;
public static final int HEIGHT=WIDTH*9/16;
public static final int SCALE=3;

private JFrame frame;
private boolean running=false;
private Thread thread;
private Draw draw;
private Keyboard keyboard;

private int frames;
private int updates;
private final long TIME_BETWEEN_UPDATES=1000000000/60;

BufferedImage image=new BufferedImage(WIDTH, HEIGHT, BufferedImage.TYPE_INT_RGB);
int[] pixels=((DataBufferInt)image.getRaster().getDataBuffer()).getData();

Frog frog;
private int[] sideCollisions=new int[0];
private int[] verticalCollisions=new int[0];
private final int WATER_LEVEL=1600;

private Generator generator;
private Healthbar healthbar;
private int score=0;
private int time=60;
private int lastScore=0;
private int lastTimeAlive=0;

private int room=0;
private int counter=0;
private Sprite openingScreenToDraw=new Sprite(1, 1, 300, SpriteSheet.backgrounds);
Random random=new Random();

public static void main(String[] args) {
    Main game=new Main();
    game.frame.setResizable(false);
    game.frame.setTitle("Under           |        FPS: ---  Updates: --");
    game.frame.add(game);
    game.frame.pack();
    game.frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    game.frame.setLocationRelativeTo(null);
    game.frame.setVisible(true);
    game.start();
}

private Main() {
    frame=new JFrame();
    Dimension size=new Dimension(WIDTH*SCALE, HEIGHT*SCALE);
    frame.setPreferredSize(size);

    keyboard=new Keyboard();
    addKeyListener(keyboard);
    draw=new Draw(WIDTH, HEIGHT, pixels);

    frog=new Frog(0, 1632, 0.01, .98, .94, .94, WATER_LEVEL, keyboard);
    generator=new Generator(WATER_LEVEL);
    healthbar=new Healthbar(frog.MAX_HUNGER, frog.MAX_BREATH, (int)(frog.MAX_JUMP_CHARGE*100)-40);
}

private void update() {
    if (room==0) {
        if (++counter>300) {
            room=1;
            counter=-60;
            openingScreenToDraw=Sprite.titleScreen;
        }
        else {
            if (counter>120&&counter<280) {
            for (int i=0; i<openingScreenToDraw.pixels.length; i++) {
                if (openingScreenToDraw.pixels[i]!=0) {
                    if (random.nextInt((300-counter-20))==0) {
                        openingScreenToDraw.pixels[i]=0;
                    }
                }
            }
        }
        }
    }

    if (room==1) {
        keyboard.update();
        if (++counter>=0) {
            if (counter>40) {
                counter=0;
                if (openingScreenToDraw==Sprite.titleScreen) {
                    openingScreenToDraw=Sprite.titleScreen2;
                }
                else {
                    openingScreenToDraw=Sprite.titleScreen;
                }
            }

            if (keyboard.keysPressed[10]) {
                room=2;
                counter=0;
            }
        }
    }

    if (room==2) {
        if (++counter>=60) {
            counter=0;
            time--;
        }
        keyboard.update();
        for (int i=0; i<keyboard.keys.length; i++) {
            if (keyboard.keysPressed[i]) {
                System.out.println("Key "+i+" Pressed");
            }
        }
        int[] returned=generator.update((int)frog.x, (int)frog.y);
        int fliesToEat=returned[0];
        int chestsToCollect=returned[1];
        score+=fliesToEat*10+chestsToCollect*100;

        frog.update(sideCollisions, verticalCollisions, fliesToEat);
        healthbar.update(frog.hunger, frog.breath, (int)(frog.jumpCharge*100)-40);
        draw.update(((int)frog.x+(frog.WIDTH+frog.BLANK_LEFT)/2)*-1+WIDTH/2, ((int)frog.y+(frog.HEIGHT+frog.BLANK_TOP)/2)*-1+HEIGHT/2);
        sideCollisions=generator.getSideCollisions();
        verticalCollisions=generator.getVerticalCollisions();

        if (frog.hunger<=0) {
            room=3;
            counter=0;
            lastScore=score;
            lastTimeAlive=60-time;
            score=0;
            time=60;
            frog=new Frog(0, 1632, 0.01, .98, .94, .94, WATER_LEVEL, keyboard);
            generator=new Generator(WATER_LEVEL);
            healthbar=new Healthbar(frog.MAX_HUNGER, frog.MAX_BREATH, (int)(frog.MAX_JUMP_CHARGE*100)-40);
        }
        if (frog.breath<=0) {
            room=4;
            counter=0;
            lastScore=score;
            lastTimeAlive=60-time;
            score=0;
            time=60;
            frog=new Frog(0, 1632, 0.01, .98, .94, .94, WATER_LEVEL, keyboard);
            generator=new Generator(WATER_LEVEL);
            healthbar=new Healthbar(frog.MAX_HUNGER, frog.MAX_BREATH, (int)(frog.MAX_JUMP_CHARGE*100)-40);
        }
        if (time<=0) {
            room=5;
            counter=0;
            lastScore=score;
            lastTimeAlive=60-time;
            score=0;
            time=60;
            frog=new Frog(0, 1632, 0.01, .98, .94, .94, WATER_LEVEL, keyboard);
            generator=new Generator(WATER_LEVEL);
            healthbar=new Healthbar(frog.MAX_HUNGER, frog.MAX_BREATH, (int)(frog.MAX_JUMP_CHARGE*100)-40);
        }
    }

    if (room==3) {
        keyboard.update();
        if (keyboard.keysPressed[10]) {
            room=1;
        }
    }
    if (room==4) {
        keyboard.update();
        if (keyboard.keysPressed[10]) {
            room=1;
        }
    }
    if (room==5) {
        keyboard.update();
        if (keyboard.keysPressed[10]) {
            room=1;
        }
    }
    if (room==6) {
        keyboard.update();
        if (keyboard.keysPressed[10]) {
            room=1;
        }
    }

}

private void render() {
    BufferStrategy bs=getBufferStrategy();
    if (bs==null) {
        createBufferStrategy(3);
        return;
    }

    for (int i=0; i<pixels.length; i++) {//sets the background color to white so that the clouds don't have holes in them
        pixels[i]=-1;
    }

    if (room==0) {
        draw.drawSpriteToScreen(0, 0, openingScreenToDraw);
    }

    if (room==1) {
        draw.drawSpriteToScreen(0, 0, openingScreenToDraw);
    }

    if (room==2) {
        draw.drawSpriteToScreen(0, Math.min(0, -1*(int)frog.y+WATER_LEVEL-HEIGHT/2-2), Sprite.sky);
        draw.drawSpriteToScreen(0, Math.max(0, -1*(int)frog.y+HEIGHT+WATER_LEVEL-HEIGHT/2-2), Sprite.water);

        frog.drawSelf(draw);
        generator.drawBlocks(draw);
        healthbar.drawSelf(draw, score, time);
    }
    if (room==3) {
        draw.drawSpriteToScreen(0, 0, Sprite.youStarved);
        draw.drawNumberToScreen(80, 64, lastScore);
        draw.drawNumberToScreen(117, 79, lastTimeAlive);
    }
    if (room==4) {
        draw.drawSpriteToScreen(0, 0, Sprite.youDrowned);
        draw.drawNumberToScreen(80, 64, lastScore);
        draw.drawNumberToScreen(117, 79, lastTimeAlive);
    }
    if (room==5) {
        draw.drawSpriteToScreen(0, 0, Sprite.outOfTime);
        draw.drawNumberToScreen(80, 64, lastScore);
        draw.drawNumberToScreen(117, 79, lastTimeAlive);
    }
    if (room==6) {
        draw.drawSpriteToScreen(0, 0, Sprite.youWereEaten);
        draw.drawNumberToScreen(80, 64, lastScore);
        draw.drawNumberToScreen(117, 79, lastTimeAlive);
    }

    Graphics g=bs.getDrawGraphics();
    g.drawImage(image, 0, 0, getWidth(), getHeight(), null);
    g.dispose();
    bs.show();
}

private synchronized void start() {
    running=true;
    thread=new Thread(this, "Under");
    thread.start();
}

private synchronized void stop() {
    running=false;
    try {
        thread.join();
    }
    catch (InterruptedException e) {
        e.printStackTrace();
    }
}

public void run() {
    long lastNanoTime=System.nanoTime();
    long lastMilliTime=System.currentTimeMillis();
    updates=0;
    frames=0;
    requestFocus();

    while (running) {
        long currentNanoTime=System.nanoTime();
        while (currentNanoTime-lastNanoTime>=TIME_BETWEEN_UPDATES) {
            lastNanoTime+=TIME_BETWEEN_UPDATES;
            update();
            updates++;
        }
        render();
        frames++;
        while (lastMilliTime+1000<System.currentTimeMillis()) {
            lastMilliTime+=1000;
            frame.setTitle("Under           |        FPS: "+frames+"  Updates: "+updates);
            updates=0;
            frames=0;
        }
    }
    stop();
}

}

Here is a link to where you can download the JAR:
https://sites.google.com/site/wierd0games/ludum-dare-under

A: The exception thrown is:
Exception in thread "main" java.lang.ExceptionInInitializerError
        at com.wierd0games.Under.graphics.Sprite.<clinit>(Sprite.java:13)
        at com.wierd0games.Under.main.Main.<init>(Main.java:53)
        at com.wierd0games.Under.main.Main.main(Main.java:57)
Caused by: java.lang.IllegalArgumentException: input == null!
        at javax.imageio.ImageIO.read(ImageIO.java:1388)
        at com.wierd0games.Under.graphics.SpriteSheet.load(SpriteSheet.java:27)
        at com.wierd0games.Under.graphics.SpriteSheet.<init>(SpriteSheet.java:22)
        at com.wierd0games.Under.graphics.SpriteSheet.<clinit>(SpriteSheet.java:13)
        ... 3 more

you can see the Exception if you run your jar with java -jar Under-LD.jar on the commandline.

A: Did you select your main class inside run config.
Run > Run Configurations > Main Class > select your main class.
next clean and build again. And then open jar file inside dist folder at your project.


text:
Q: ipywidgets Jupyter Notebook: select multiple checkboxes to filter the dataframe and plot it out Any good suggestions on how to build checkboxes to select certain groups of dataframe for visualization in jupyter notebook?
Here's an example:
>> df
    label value date
1   A     4     2021-10-10
2   B     2     2021-10-11
3   B     3     2021-10-11
4   A     5     2021-10-09
5   C     7     2021-10-10
6   A     2     2021-10-09

In this scenario, I intended to create three checkboxes for users to display what they want. If users click A and B, The program will display df[df.isin('label':['A','B'])] and say plotting out a stacked bar chart displaying the number of A and B in terms of date.
(Plotting part totally works, it's just the interactive part I haven't found a way to figure out)
Here's my thoughts:
from ipywidgets import Checkbox, interact

label = ['A', 'B', 'C']
ckb=[Checkbox(description=a) for a in label]

filtered_df=None

def checkbox_fig1(**kwargs):
    global filtered_df

    # Not sure for the following part
    selected=[]
    for k, v in kwargs.items():
        if k:
            selected.append(k)

    filtered_df = df1[df1.isin(selected)]

interact(checkbox_fig1, **{c.description: True for c in ckb})

Overall it's displaying whatever I checked either one label or multiple labels.
I would really appreciate if anyone could offer some suggestions!!!


text:
Q: While dragging multiple items from listview deselecting list items I'm trying to build a WPF application which contains a ListView that allows multiple selections and allows the user to drag and drop selected items into another ListView.  I've been able to get drag and drop to work fine, but I'm having some trouble working with the behaviour of ListView when dragging the mouse on them.
If the user clicks on an item and holds down the mouse button and then begins to drag,
the ListView will change the selection(deselecting list items) as the user drags over other items.  I don't want it to do this- when the user clicks an item and holds the button down, I want the item that they clicked on to always be selected, regardless of where they move the mouse.
Here is my ListView properties I set, Click here for complete code
<ListView Width="auto" Height="280" KeyDown="RightFolderListing_KeyDown" IsSynchronizedWithCurrentItem="True" AllowDrop="True"  PreviewMouseLeftButtonDown="RightList_LeftButtonDown" DragEnter="RightList_DragEnter" Drop="RightList_DropEnter" PreviewMouseMove="RightList_PreviewMouseMove" SelectionMode="Extended"
                        util:GridViewSort.AutoSort="True" Name="RightFolderListing" ItemContainerStyle="{StaticResource RightListViewItemStyle}" ItemsSource="{Binding RightFolderList, ElementName=RPCFTViewer,Mode=TwoWay}" ContextMenuOpening="RightFolderListing_ContextMenuOpening"  >


text:
Q: are there any Image View transition library for android? I need to make transition of imageview which is quite difficult to do by myself. After searching for prebuilt library for hours, I only found some activity transition & simple fade in/out transition.
What I found are material Animation with activities and viewflipper :
https://github.com/lgvalle/Material-Animations
https://androidmyway.wordpress.com/2012/10/30/slide-transition-in-viewflipper/
What I need is vertical bars, dissolve, explode and other advanced transition like in windows movie maker or jquery animation.

If there are any prebuilt android library for this kind of stuff, please let me know. Thanks !

A: *

*Download a set of animation from here:
------>     https://drive.google.com/folderview?id=0B_tCPatPrHgyWmNtWjM2X1ZiV1k&ddrp=1#

*In your android project, if working in Eclipse, open a /res , folder then go to menu:
  file>new>folder>     give name to folder:  "anim".

*Copy all files to this folder. Just drag them from windows explorer. Now we finished the preparations and ready to use the downloaded.

*Activity main screen contains one image.  When click happens, image starts to animate, see the code example below:
/*xml file
 *

*end of file
*/
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.ImageView;

public class MainActivity extends Activity {
ImageView image;

  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    image = (ImageView) findViewById(R.id.imageView);

    image.setOnClickListener(new View.OnClickListener() {

      @Override
      public void onClick(View arg0) {

        image.startAnimation(selectanimation((int)(Math.random()*6))); //randomly select animation 0-5
      }

    });
}
  private Animation selectanimation(int index) {
    switch(index){
    /*
     * create animations, and return them to caller.
     */
    case 0: return new AnimationUtils().loadAnimation(this, R.anim.shake);
    case 1: return new AnimationUtils().loadAnimation(this, R.anim.fade);
    case 2: return new AnimationUtils().loadAnimation(this, R.anim.slide_left);
    case 3: return new AnimationUtils().loadAnimation(this, R.anim.wave_scale);
    case 4: return new AnimationUtils().loadAnimation(this, R.anim.hold);
    case 5: return new AnimationUtils().loadAnimation(this, R.anim.zoom_enter);
    }
    return null;
  }
}

Download full source code Here!

A: You should try to write your own custom animations with android animation class. Here is a library link which you can study and modify as need. It contains animation like explode, fold etc.
https://github.com/2359media/EasyAndroidAnimations
For you question, first animation is little difficult. It will need masking for perfect animation like shown above. If you want some easy hint, you can try using two black images like below. Make sure to cover whole screen with black part. Then move one image below and another to right for creating effect.

Second animation is quite simple, you can try something like in hint below:
<framelayout>
     <imageview src="@drawable/car.jpg">
     <linearlayout
         weightsum="9"
         orientation="horizontal"><!--set it's width height to cover car image-->
        <imageview @+id="imgview1"
           weight="1" src="@drawable/blackbar.jpg">
        <imageview @+id="imgview2"
           weight="1" src="@drawable/blackbar.jpg">
        .
        .
        <imageview @+id="imgview9"
           weight="1" src="drawable/blackbar.jpg">
     </linearlayout>
</framelayout>

In your java code, try following animation for black bars.
 new Timer().schedule(new TimerTask() {
        @Override
        public void run() {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    ScaleAnimation anim = new ScaleAnimation(1.0f, 0.0f, 1.0f, 1.0f, Animation.RELATIVE_TO_SELF,0.0f, Animation.RELATIVE_TO_SELF, 0.5f);
                    anim.setFillAfter(true);
                    anim.setDuration(400);
                    imgBlackBar1.startAnimation(anim);

                }
            });
        }
    }, 150);

now, set delay for bar2 300, bar3 450 and so on as you desire.


text:
Q: How to calculate a darker hex color Using this solution I am trying to calculate the darker range of a color but the output is doesn't look like correct Hex value (missing one value).
> #84079

What am I doing wrong?

function LightenDarkenColor(col, amt) {

    var usePound = false;

    if (col[0] == "#") {
        col = col.slice(1);
        usePound = true;
    }

    var num = parseInt(col,16);

    var r = (num >> 16) + amt;

    if (r > 255) r = 255;
    else if  (r < 0) r = 0;

    var b = ((num >> 8) & 0x00FF) + amt;

    if (b > 255) b = 255;
    else if  (b < 0) b = 0;

    var g = (num & 0x0000FF) + amt;

    if (g > 255) g = 255;
    else if (g < 0) g = 0;

    return (usePound?"#":"") + (g | (b << 8) | (r << 16)).toString(16);

}
var firstColor = LightenDarkenColor("#3068A1", -20);
var NewColor = LightenDarkenColor(firstColor, -20);

console.log(NewColor);

A: Change this:
(usePound?"#":"") + (g | (b << 8) | (r << 16)).toString(16);

to this
(usePound?"#":"") + ('00000'+(b | (g << 8) | (r << 16)).toString(16)).slice(-6);

This will make sure that there are 6 digits and it fixes the green and blue location which were off in the original article.

*

*(r << 16) moves the red to bits 32 to 47

*(g << 8) moves the green to bits 16 to 31

*and b leaves the blue in bits 0-15.

UPDATE
As was pointed out the b and g variables are reading the wrong values as well. So you want to do the following as well:
var g = ((num >> 8) & 0x00FF) + amt;

var b = (num & 0x0000FF) + amt;

Swap where the b and g get their values.
If you don't want to swap those then change my original line to this:
(usePound?"#":"") + ('00000'+(g | (b << 8) | (r << 16)).toString(16)).slice(-6);


text:
Q: EAST text detection -215:Assertion failed (OpenCV Python) When trying to use EAST text detector on some images, with OpenCV in Python on Windows 10, I get the following error:
cv2.error: OpenCV(4.0.0) C:\projects\opencv-python\opencv\modules\dnn\src\dnn.cpp:835: error: (-215:Assertion failed) ld.inputBlobs[0]->total() == total(shapes[index]) in function 'cv::dnn::dnn4_v20180917::BlobManager::allocateBlobsForLayer'

(Strangely, that path does not exist on my file system)
I started from the excellent tutorial by Adrian Rosebrock. Here is a code snippet (it fails on the last line):
# sFileName is the path to the image, previously set
oInputImage = cv.imread(sFileName)
aiShape = oInputImage.shape
(iH, iW) = aiShape[:2]
iRequiredUnit = 32

# check if the image height is enough
iHr = iH % iRequiredUnit
iBottom = 0
iHr = iH % iRequiredUnit
if 0 < iHr:
    # calculate how much padding is necessary
    iBottom = iRequiredUnit - iHr

# check if the image width is enough
iRight = 0
iWr = iW % iRequiredUnit
if 0 < iWr:
    # calculate how much padding is necessary
    iRight = iRequiredUnit - iWr

if iBottom > 0 or iRight > 0:
    # add padding to make the image proportions correct
    oImage = cv.copyMakeBorder(
        src=oInputImage,
        top=iTop,
        bottom=iBottom,
        left=iLeft,
        right=iRight,
        borderType=cv.BORDER_CONSTANT,
        value=[0, 0, 0]
        )
    else:
    # no need to add padding
    oImage = oInputImage.copy()

(iH, iW) = oImage.shape[:2])

ib, ig, ir, _ = cv.mean(oImage)
oBlob = cv.dnn.blobFromImage(
        oImage, 1.0, (iW, iH), (ib, ig, ir),
        swapRB=True, crop=False
)

# load the EAST network
# EAST_path initialized appropriately previously
oNet = cv.dnn.readNet(EAST_path)
oNet.setInput(oBlob)
asLayerNames = [
        "feature_fusion/Conv_7/Sigmoid",
        "feature_fusion/concat_3"]
(afScores, aoGeometry) = oNet.forward(asLayerNames)

I made some modifications, e.g. I recalculate the mean instead of using the hardcoded value shown in the example. I also tried to call blobFromImage without mean (or with the default from the example) and with swapRB=False, but the error keeps occurring.
The problem happens systematically with some files (here's an example), whereas it doesn't with others, on which EAST instead runs smoothly. I cannot identify the characteristics that make an image troublesome, however I am inclined to think that the error is independent of the need to resize the image, since most of the images that can be analyzed without issues must be resized anyway.
I haven't found any documentation specific to the issue and cannot reconstruct the problem easily from the source (which, I guess, is this).
How can I prevent the error?

A: I faced a similar problem with another application. This has something to do with the input size. I used the following workaround that did not fail so far:
    orig_height, orig_width = image.shape[:2]
    while True:
        height, width = image.shape[:2]

        blob = cv2.dnn.blobFromImage(image, scalefactor=1.0, size=(width, height),mean=(104.00698793, 116.66876762, 122.67891434),swapRB=False, crop=False)
        self.net.setInput(blob)
        try:
            prediction = self.net.forward()
            break
        except:
            pass

        if width*height  < 100:
            raise
        image = cv2.resize(image, (int(width*0.9), int(height*0.9)))

    prediction = cv2.resize(prediction[0, 0], (orig_width, orig_height))


text:
Q: Problems with location permission on android [EXPO| REACT NATIVE] I'm trying to update an app that has already been published on the PlayStore but is now being refused because GOOGLE informs that the app does not respect usage policies. I receive the following message:
- The app does not comply with the Location Permissions policy
Email with details send by google
After receiving this response from Google, I have already corrected my code, but the app continues to be refused.
Below are the actions I have already taken to try to resolve the issue:

*

*When I received the lock for the first time, I made the requested corrections in the application code. The app currently requests the following permissions:

permissions on code
Below is the print of the permissions after uploading the .aab to the playstore:
enter image description here

*

*Accessing the play store policy menu, I noticed that the privacy policy setting is linked to build number 29 but I'm already trying to send build 35.

This build 29 uses background localization, but I can't unlink it from the policy configuration tab or add another app version.
app settings in play store
wrong permissions in build 29
I've also reviewed the features that use localization in the code and everything is fine. Below screenshots of the code:
code snippet 1
code snippet 2
code snippet 3
I would like to know if anyone has had similar problems and can give me some guidance on how to solve it?

A: First thing, I noticed that you wrote "ACCCESS_COARSE_LOCATION" (with 3 C). I don't know if this is the error, but better spell it right.
Second thing, be sure that you declared that you DON'T use background location. To do that, go to your Google Play Console, select your app, then go to
App Content (it should be the last section on the left) -> API and sensitive authorizations -> Manage
then set "No" to the question regarding background location.
This is the screen you should see after these steps


text:
Q: Husky e commitlint não funcionam antes do comando git commit Foram instalados os pacotes husky e commitlint a um projeto NodeJS com a intenção de adicionar Hooks aos comandos git commit para manter um mesmo guia de estilo nas mensagens de commit.
Entretanto os Hooks não estão sendo acionados, permitindo que mesmo as mensagens mal formatadas de commit fossem executadas.
OBS:
Todos os passos do guia de instalação já foram seguidos corretamente, e o arquivo package.json já está com o trecho necessário para acionar o hook:
// package.json
{
  "husky": {
    "hooks": {
      "commit-msg": "commitlint -E HUSKY_GIT_PARAMS"
    }
  }
}

Dados do ambiente:

*

*Linux: 16.04.1-Ubuntu

*Git: 2.7

*Node: v12.18.3

*Husky: 4.3.7

*@commitlint/cli: 11.0.0

*@commitlint/config-conventional: 11.0.0

A: No repositório do pacote Husky tem um trecho não muito evidente, onde menciona que a versão minima do Git instalada deve ser 2.13.0

Verify that your version of Git is >=2.13.0.

E para fazer a atualização do Git no Ubuntu, basta executar os seguintes comandos:
sudo add-apt-repository ppa:git-core/ppa -y
sudo apt-get update
sudo apt-get install git -y
git --version

Após fazer a atualização do Git, reinicie o computador e faça os testes novamente.
Espero ter ajudado.


text:
Q: for loop as predicate xquery, xpath I have a list of /bibl entries, each with a /date @when="YEAR" child element. I am trying to output only the first instance of each year.
`<listBibl>
            <bibl>
                <date when="1746"/>
            </bibl>
            <bibl>
                <date when="1746"/>
            </bibl>
            <bibl>
                <date when="1746"/>
            </bibl>
            <bibl>
                <date when="1746"/>
            </bibl>
          <bibl>
                <date when="1747"/>
            </bibl>
            <bibl>
                <date when="1747"/>
            </bibl>
            <bibl>
                <date when="1747"/>
            </bibl>
          <bibl>
                <date when="1754"/>
            </bibl>
            <bibl>
                <date when="1754"/>
            </bibl>
          </listBibl>

I have written an expression that finds this: for $d in /date/@when return (/date[@when=$d])[1]
But this won't work in the programme (teipublisher) I am using to output the attribute value. Does anybody have any suggestions about how I might do this differently.

A: By using BaseX, v.9.6.4
XQuery
xquery version "3.1";

declare context item := document {
<listBibl>
    <bibl>
        <date when="1746"/>
    </bibl>
    <bibl>
        <date when="1746"/>
    </bibl>
    <bibl>
        <date when="1746"/>
    </bibl>
    <bibl>
        <date when="1746"/>
    </bibl>
    <bibl>
        <date when="1747"/>
    </bibl>
    <bibl>
        <date when="1747"/>
    </bibl>
    <bibl>
        <date when="1747"/>
    </bibl>
    <bibl>
        <date when="1754"/>
    </bibl>
    <bibl>
        <date when="1754"/>
    </bibl>
</listBibl>
};

<listBibl>
{
  for $x in ./listBibl/bibl
  let $date := $x/date/@when
  group by $date
  order by $date
  return <bibl>
        <date when="{$date}"/>
    </bibl>
}
</listBibl>

Output XML
<listBibl>
  <bibl>
    <date when="1746"/>
  </bibl>
  <bibl>
    <date when="1747"/>
  </bibl>
  <bibl>
    <date when="1754"/>
  </bibl>
</listBibl>


text:
Q: Ошибка при компиляции c# проекта Скачал себе visual studio для мака, создал проект под с#, решил запустить а оно выдает ошибку:
Invalid 'cwd' value '/Users/s.k./Documents/Programming/c#/projects/test/test'. The system cannot find the path specified.
Буду благодарен за помощь.

Ето пример кода, который я питаюсь запустить. Код автоматически добавлен после создание проекта

То что происходит при попытке компиляции кода

A: Скорее всего проблема из за точки в конце имени учетной записи.
Такая же проблема встречается здесь: учетка с точкой
Проверьте указанный путь cwd.
Все ли каталоги существуют: /Users/s.k./Documents/Programming/c#/projects/test/test
Если нет, попробуйте создать недостающие (до projects) вручную, и создать новый проект. Если не поможет придется переименовать учетку (назвать без точек).


text:
Q: Rendering different repeating data What is the best method to display repeating data with slightly different controls or sub data?  For example displaying an expanded list of questions and answers.  Some questions will have answers, some will not.  Some button controls would show for some items while not for others.
In classic ASP I've used XML/XSL quite effectively for displaying data in this manner.  In .NET I've used functions being called from a label with the HTML writer class to render controls dynamically and nested list views that would bind or not depending on existing data.
I know I could also use XSL with .NET but my question is -  is there a better method of displaying data this way? Inline IIf's and functions being called from the front end doesn't seem very clean.

A: I think the ListView would work in your situation:
http://blogs.msdn.com/mikeormond/archive/2008/01/23/some-asp-net-3-5-listview-control-examples.aspx
http://weblogs.asp.net/scottgu/archive/2007/08/10/the-asp-listview-control-part-1-building-a-product-listing-page-with-clean-css-ui.aspx
You have the ability to group items in different layouts using the ItemTemplates and you can also tap into the event handlers when loading the data.
EDIT:
You may be able to do it this way dynamically, but it's tricky with the ID's:
http://blogs.msdn.com/mikeormond/archive/2008/07/26/dynamically-loading-listview-templates.aspx
Or you could simply create a table composite control and build it up dynamically yourself...


text:
Q: Activity losing focus due to another Activity in the same app vs a separate app / device interrupt I need to log an event only when the application as a whole has lost focus (such as an incoming call or the home key).
What is the best way to tell an Activity has been paused or stopped from an external event rather than another activity within the same app?
Thanks

A: when your activity stops you can check if your app is still on top in the onStop() method:
private boolean isAppOnTop(){
    ActivityManager am = (ActivityManager) getSystemService(Service.ACTIVITY_SERVICE);
    List<ActivityManager.RunningTaskInfo> tasks;
    tasks = am.getRunningTasks(1);
    RunningTaskInfo running = tasks.get(0);
    if(running.topActivity.getPackageName().equals("your.package.name")){
        return true;
    }
    else{
        return false;
    }
}

This method queries all running tasks first. In general the task which has focus is on top of the stack. Check if this task belongs to your package.

A: So along with Dennis' answer which is perfectly valid if you are willing to set the get_tasks permission we explored the following options (mostly based on setting some kind of flag when onstop/onpause is called):

*

*When starting a new activity. In the onStop method if the flag is set to true then the interrupt was caused by a new activity in the app.

*Have a global variable which counts active views. Increments on onStarts and decrements on onStops. If its 0 then we have no visible activities.

*onStart sets an active flag true for the activity. onStop sets the flag to false. (states can also be saved to prefs). When the activity loses focuses we can check all the flags.
Because the app is relatively simple we went for the first option.


text:
Q: How to configure SSLSocket Factory per route using Apache HTTP Components Is there any way to setup a separate SSL Context Factory for each route in Apache HTTP Client. From the documentation i can only see we can configure SSLContextFactory per scheme not per route.
Registry<ConnectionSocketFactory> r = RegistryBuilder.<ConnectionSocketFactory>create()
            .register("http", plainsf)
            .register("https", sslsf)
            .build();

    HttpClientConnectionManager cm = new PoolingHttpClientConnectionManager(r);
    HttpClients.custom()
            .setConnectionManager(cm)
            .build();

All my target endpoints are protected with HTTPS and mandates client certificate authentication. For each of these endpoint i have to select a specific client certificate & present it to the endpoint server. Currently i am seeing the only way is to create a separate HTTPClient instance for each target endpoint route & configure with SSLContext Factory instance.
I am here looking for any pointers to improving this design.
Thanks.

A: I have posted this question in Apache HTTP Client Forums & got the solution on how to handle this.

One can use 'http.socket-factory-registry' context attribute to that
  end but please note this feature is considered undocumented.
http://hc.apache.org/httpcomponents-client-4.5.x/httpclient/xref/org/apache/http/impl/conn/DefaultHttpClientConnectionOperator.html#66
Please also note that one can build a custom ConnectionSocketFactory
  that makes use of custom context attributes when creating SSL sockets.
  That would be the recommended way to solve the issue.


text:
Q: Electron app Error: ENOENT: no such file or directory, open '/.env' I'm a really young developper, sorry if my question is obvious.
I tried everything, but nothing works in my case, or maybe i'm doing it wrong.
I'm actually trying to build a React Typescript Electron App with electron-builder.
When I'm starting my app localy with yarn start, everything is good, but when I'm trying to build, this issue appears.
What I understand is : my .env file isn't in my built app file. How can I tell to my builder to take into account my .env file ?
Someone can help me please ? Thank you :)
Maybe this will be usefull : project files, scripts

A: why you need to use .env file at the first place, it wouldn't be secure cz, all of your data will be created or stored in the system. so if you want to use security credentials in electron application, you should use some cloud-based store that will provide secure access to get credentials otherwise store it in common js or JSON file. the solution is if you're using electron builder you can always use extraResources or asarUnpack.


text:
Q: Swap partition is not working My swap partition is not being used, I set the swappiness to 0 and fixed the UID in the config file to the UID of the swap partition but it's still at 0%.

A: SWAP space is used for RAM paging in cases where you may run out of available memory.  If SWAP is active, but you are not using it, then it is likely that your resources are held in memory which has significantly faster read/write times than the SWAP space on a HDD.
To configre SWAP space, follow this guide


text:
Q: Branch.io deferred deep linking. How to catch key and value params in Unity c#? I need to set up a deferred deep linking to my app, using Unity Branch SDK. I successfully Integrated Branch to unity project and quick link opens my app. But i can't understand how let link open my specific content. How to read key and value parameters in C# code?
In the article "In-app deep link routing" in documentation  I found - Build custom routing inside the routing callback (https://docs.branch.io/pages/deep-linking/routing/#option-1-build-custom-routing-inside-the-routing-callback) and Auto-routing in Android (https://docs.branch.io/pages/deep-linking/routing/#auto-routing-in-android), but examples are only for android and ios. How can I do this on Unity C# (if this is a deferred deep linking)?

A: You can refer to the Unity documentation on reading deep link data here.
For a deeper dive, you can look at the Unity SDK documentation and code here.


text:
Q: SLO with SAML 2.0 (SP initiated SLO or IDP initiated SLO), which one is good to have in service provider We created a application (SP), which have a option to login via SSO(Single Sign On) using third party application (any IdP).  We used SAML 2.0 complaint for SSO(Single Sign On).
Question :

*

*Which one is good to have in my application (SP initiated SLO or IDP initiated SLO)?

*How many application using SP initiated slo and IDP initiated slo?
(1 or 2 application(SP) name for each which are integrated with third party app)

*How about creating both and keeping SLO is optional to IDP?
Can anyone help me

A: There is no requirement to provide SLO. Many large service providers do not (Google Apps and Salesforce, for example).
If you're going to provide for it, it's my opinion that you should support both, but not require it of the SP (make it an option within your SP). All enterprise implementations (PingFederate, OAM, Siteminder, etc.) that I am aware of support both, but do not require either, on both SP and IdP sides.


text:
Q: Customised hot questions for extension I love the hot questions extension I found upon upgrading to iOS 10, I would really like to be able to customise the questions that show up though, really what I would like to be able to see only really falls under swift (iOS), Physics, Mathematics, Music... you get the point. Even just being able to select which sites show up would be great.

A: Doesn't that default the purpose of the HNQ list? It are the hot questions on the network, not a list of hot question for just a few sites.
I could agree it is useful sometimes to have a hot questions per site or tag, but that would be a totally different feature than the one you are requesting now.


text:
Q: Inspecting element on wordpress website shows wrong line number Whenever I inspect an element on my wordpress website it shows the element as being on line 1 of http://localhost/wordpress/wp-content/themes/ignite/style.min.css?ver=1.19 instead of the correct line in "style.css".
Can someone please let me know how to make my website use style.css rather than style.min.css?ver1.9?
Thanks.

A: The script has been minified. Technically it's all on line 1. See if you cannot locate a version of the css that is not minified.
You can also use a minifier tool in reverse, take the unminfied cod and replace the css file with the inflated version. Run it again and then you'll be able to find the problem based on the line.
Minifier tool here:
http://cssminifier.com/


text:
Q: How can I color different parts of my log entries to a RichTextBox in an efficient way? I am making a test program that should present logged data for the user on the screen. What I am trying to do now is to process each message as it comes whereafter I present it on the screen where different parts of the message should be presented in different colors depending on the result. How should I do this if I want to use the MVVM pattern? My idea was to use the RichTextBox but I am not sure on how to catch the actual changes and then only color parts of it.
My first idea was to use a TextBlock. If it binds with Message, where Message returns a string of all the so far logged data I assume it will not just update the changes of the Message string but rather all the logged data. Would this be terribly inefficient when having a lot of log entries?
        <TextBlock
        x:Name="logTxt"
        Grid.Row="0" Grid.Column="0"
        Text="{Binding Path=Message, UpdateSourceTrigger=PropertyChanged}" TextWrapping="Wrap" Background="White"/>

Now if I would like to use the RichTextBox instead, and then only update it with the new data, then could I color the different parts with use of XAML-code or do I have to write it as C# code? Would that be to go against the MVVM pattern? I have searched for a solution but did not really find an explanation that could clarify this for me as I am quite new to C# and MVVM overall.


text:
Q: How to use mvvmcross core library in Windows Service project? I have a developed a WPF project using mvvmcross library and now I want to use the core part in windows service project. Can someone please give a pointer to start with this? Basically I want to implement Setup.cs for the windows service project.

A: MvvmCross does not support Windows Service projects. Nor do we have any intentions of adding support currently. Nor do I understand why you would even use it there, unless it is for the IoC it provides.
You can take a look at how the Console version is implemented. You can probably copy it straight and it will work for Windows Services too.
https://github.com/MvvmCross/MvvmCross/tree/4.0/MvvmCross/Console/Console


text:
Q: Android support library 23.2 - tab styling not working completely as before Some style attributes are no longer applied to my tabs after updating to android support library 23.2. I have a tab view as follows:
<android.support.design.widget.TabLayout
        android:id="@+id/tabs"
        android:layout_width="match_parent"
        android:layout_height="42dp"
        android:layout_marginRight="15dp"
        android:layout_marginLeft="15dp"
        android:layout_marginTop="10dp"
        app:tabMode="fixed"
        app:tabGravity="fill"
        style="@style/WowTabAppearance" />

And the accompaniying styles:
<style name="WowTabAppearance" parent="Widget.Design.TabLayout">
    <item name="tabIndicatorColor">?attr/colorAccent</item>
    <item name="tabIndicatorHeight">2dp</item>
    <item name="tabPaddingStart">12dp</item>
    <item name="tabPaddingEnd">12dp</item>
    <item name="tabBackground">@drawable/wow_tabs_bg</item>
    <item name="tabTextAppearance">@style/WowTabTextAppearance</item>
    <item name="tabSelectedTextColor">@color/dark_primary_color</item>
</style>
<style name="WowTabTextAppearance" parent="TextAppearance.Design.Tab">
    <item name="android:textSize">14dp</item>
    <item name="android:textColor">@color/gray_4_medium_light</item>
    <item name="textAllCaps">false</item>
</style>

textAllCaps now doesn't work - tabs display in uppercase on 23.2. I've tried changing other two attributes, and textColor works, while textSize doesn't.
Is this a bug in 23.2 or has something changed? Where could I see a more detailed report of changes in 23.2?


text:
Q: Applying cantor diagonal argument recursively: How to show the resulting construction is incomplete? Recall that cantor diagonal argument basically asked to list out the table of all countable binary strings, and showing how regardless of what list you start with, there's always a diagonal element that is not enumerated in the list, thus proving the reals have larger cardinality.
\begin{matrix}
00001...\\
10101...\\
11001...\\
11000...\\
11010...\\
\vdots \\
\text{pick}: 00000\\
\end{matrix}
But suppose we iterate this process as follows:

*

*Start with a list of binaries

*Use the diagonal argument to pick out the diagonal element that is not in the list of binaries

*Place the new element at the beginning of the list of binaries

*Repeat until no new diagonal can be picked out.

Since this is expected to iterate indefinitely, can a proof by transfinite induction allow us to deduce whether such procedure can enumerate all countable binary strings. what is the step required to set up this proof?
Alternately, since any algorithm in a computer can only run for finite number of steps, what is the approach used to find a counterexample of this conjecture?

A: You're not gaining anything new by this method. If it terminates, you just end up with a standard list, and you already know how to prove that that can't be complete. If it doesn't terminate, it produces a "two-sided list", infinite in both directions, which you can easily map to a standard list by cutting it at some point and interleaving the two resulting lists. So again you already know how to prove that this can't be complete.


text:
Q: WPF Get the referenced item from a ContextMenu on a ListViewItem I have a ListView with ContextMenu on each ListViewItem that has Click event,
how can I detect in the event handler which Item was clicked in this ContextMenu?
I need the item ID.
 <Style TargetType="{x:Type ListViewItem}">

.
.
.
 <Setter Property="Control.Template">
                <Setter.Value>
                    <ControlTemplate TargetType="tv:TreeListViewItem">
                        <Grid>
                            <Grid.ContextMenu>
                                <ContextMenu>
                                    <MenuItem Header="Open in current tab" Click="MenuItemCurrentTab_Click"/>
                                    <MenuItem Header="Open in new tab" Click="MenuItemNewTab_Click"/>
                                </ContextMenu>
                            </Grid.ContextMenu>

A: See this thread..
Following the same way as the answer from the link you would
<Grid.ContextMenu>
    <ContextMenu>
        <MenuItem Header="Open in current tab"
                  Click="MenuItemCurrentTab_Click"
                  CommandParameter="{Binding RelativeSource={RelativeSource Self}, Path=Parent}"/>

...
private void MenuItemCurrentTab_Click(object sender, RoutedEventArgs e)
{
    MenuItem menuItem = sender as MenuItem;
    if (menuItem != null)
    {
        ContextMenu parentContextMenu = menuItem.CommandParameter as ContextMenu;
        if (parentContextMenu != null)
        {
            ListViewItem listViewItem = parentContextMenu.PlacementTarget as ListViewItem;
        }
    }
}

UPDATE
Add this to get the parent ListViewItem from the Grid
public T GetVisualParent<T>(object childObject) where T : Visual
{
    DependencyObject child = childObject as DependencyObject;
    while ((child != null) && !(child is T))
    {
        child = VisualTreeHelper.GetParent(child);
    }
    return child as T;
}

private void MenuItemCurrentTab_Click(object sender, RoutedEventArgs e)
{
    MenuItem menuItem = sender as MenuItem;
    if (menuItem != null)
    {
        ContextMenu parentContextMenu = menuItem.CommandParameter as ContextMenu;
        if (parentContextMenu != null)
        {
            Grid grid = parentContextMenu.PlacementTarget as Grid;
            ListViewItem listViewItem = GetVisualParent<ListViewItem>(grid);
        }
    }
}

A:     private void MenuItemCurrentTab_Click(object sender, RoutedEventArgs e)
    {
        MenuItem menuItem = (MenuItem)e.Source;
        ContextMenu menu = (ContextMenu)menuItem.Parent;
        ListViewItem item = (ListViewItem)menu.PlacementTarget;
        // do something with item
    }

But it's probably better idea to create single ContextMenu, give it proper name, and use it for all list view items.

A: A recurring problem, with many attempts to solve but all have their drawbacks. The accepted answer here, for instance, supposes that each ListViewItem has its own ContextMenu. This works but, especially with a larger number of list items, has a considerable cost in XAML complexity and can be slow. And really isn't necessary at all. If we only use a single ContextMenu on the ListView itself, some other solutions suggest to use
 <MenuItem CommandParameter="{Binding PlacementTarget.SelectedItem, RelativeSource={RelativeSource AncestorType=ContextMenu}}" />

which seems to solve the problem at first sight (PlacementTarget points to the ListView, its SelectedItem points to the list item, so the menu item handler can use the CommandParameter to get the originating list item), but, unfortunately, fails if the ListView has multiple selection enabled (SelectedItem will point to one of the items selected but not necessarily the one currently clicked) or if we use ListView.PreviewMouseRightButtonDown to disable the selection on right-click (which is, arguably, the only logical thing to do with multiple selections).
There is, however, an approach that has all the benefits:

*

*single ContextMenu on the ListView itself;

*works with all selection schemes, single, multiple, disabled;

*even with multiple selection, it will pass the currently hovered item to the handler.

Consider this ListView:
<ListView ContextMenuOpening="ListView_ContextMenuOpening">
  <ListView.ContextMenu>
    <ContextMenu>
      <MenuItem Header="Menu1" Click="Menu1_Click" CommandParameter="{Binding Parent, RelativeSource={RelativeSource Self}}" />
    </ContextMenu>
  </ListView.ContextMenu>
</ListView>

The CommandParameter is used to pass the parent of the MenuItem, ie. the ContextMenu itself. But the main trick comes in the menu opening handler:
private void ListView_ContextMenuOpening(object sender, ContextMenuEventArgs e) {
  var menu = (e.Source as FrameworkElement).ContextMenu;
  menu.Tag = (FrameworkElement)e.OriginalSource;
}

Inside this handler, we still know the original source of the event, the root FrameworkElement of the list item DataTemplate. Let's store it in the Tag of the menu for later retrieval.
private void Menu1_Click(object sender, RoutedEventArgs e) {
  if (sender is MenuItem menu)
    if (menu.CommandParameter is ContextMenu context)
      if (context.Tag is FrameworkElement item)
        if (item.DataContext is DataType data) {
          //process data
        }
}

In the menu click handler, we can look up the original ContextMenu we stored in the command parameter, from that we can look up the root FrameworkElement of the list item that we stored just before, and finally get the object stored in the list item (of type DataType).

A: ListViewItem item = myListView.SelectedItem as ListViewItem;

Seems to work just fine as the item is selected when you right-click it.


text:
Q: Strategies and techniques for unit testing WinJS UI pages I'm modifying some individual methods within existing and quite complex WinJS UI controls at the moment.
There is a lot of code within these controls which has dependencies on the contents of various HTMLElements and on several other large JavaScript WinJS modules.
There are no existing unit tests for any of the methods - but I'm looking to add unit tests as I add/change functionality.
I've got a basic infrastructure for unit tests set up in VisualStudio using Jasmine and Chutzpah (similar to http://winjsby.blogspot.co.uk/2013/02/windows-8-unit-tests.html)
I'm currently struggling to find a way to effectively write unit tests for these methods which:

*

*have so many static interdependencies (e.g. to lots of things like WinJS.Utilities and msZoomTo)

*rely so heavily on specific complex sets of elements existing in HTML.

*seem to rely on DOM event propagation and handling too

Does anyone have any suggestions or specific examples of good unit tests for large WinJS libraries, of tools to assist with setting up HTML test structures and of tools to provide mocking for static objects?


text:
Q: derivative dot(newton) notation $\frac{d}{dt} \dot{x}^2$ I can't find how to derive $\dot{x}^2$
I know $\frac{d}{dt} \dot{x} = \ddot{x}$
My guess $\frac{d}{dt} \dot{x}^2 = 2\ddot{x}$, but I'm not sure.

A: Use the chain rule.
Remember that $\dot{x} = \frac{dx}{dt}.$ So $\dot{x}^2 = \left(\frac{dx}{dt}\right)^2.$ Now use the chain rule: the derivative is $2\dot{x} \ddot{x}$.


text:
Q: Why my code works in OnCreate but not in OnItemClickListener I´ve made and app that shows a calendar and when i click in a day, i want to show a ListView customize.
My problem is that when i used the code in the OnCreate, it works, but when i used it in OnItemClickListener of the calendar it doesn´t do anything.
Here it´s my code. I appreciate your work and help
    for(int i = 0; i < 5; i++) {
        RowItem item = new RowItem(imagesCharacter[i], imagesAnime[i], characters[i], animes[i]);

        rowItems.add(item);
    }

    CustomListViewAdapter myAdapter = new CustomListViewAdapter(getApplicationContext(),       R.layout.list_item, rowItems);
    listView.setAdapter(myAdapter);
    listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {

        @Override
        public void onItemClick(AdapterView<?> parent,
                View view, int position, long id) {
            // TODO Auto-generated method stub
            Toast toast = Toast.makeText(getApplicationContext(),
                    "Item" + (position + 1) + ": " + rowItems.get(position), Toast.LENGTH_LONG);
            toast.setGravity(Gravity.BOTTOM|Gravity.CENTER_HORIZONTAL, 0, 0);
            toast.show();
        }

    });

If you ask, i do the findViewById of the ListView when i run the app.
SOLUTION:
I found the problem and now it works.
The problem was that the ListView was a child of a LinearLayout and always got or Null when i did the findViewById, or something else that didn´t work.
So i delete de Layout and when i did my findViewById worked.
Thank you for all the answers.

A: Instead of getApplicationContext() (which should be avoided when possible) use YourActivityName.this.

A: Create a reference to the Activity's context by doing:
private Context mContext;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    mContext = this;
}

then pass the context reference to your OnItemClickListener like:
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
       Toast toast = Toast.makeText(mContext, "Item" + (position + 1) + ": " + rowItems.get(position), Toast.LENGTH_LONG);
       // Other codes here.
    }
});


text:
Q: Mapping circular lunes $|z|<1,|z+i|<1$ I want to map the circular lunes $|z|<1,|z+i|<1$ onto the upper half-plane
Since intersection points are $z_1=\sqrt 3/2-i/2$ and $z_2=-\sqrt 3/2-i/2$ we have
$$w_1=\frac {2z-\sqrt 3+i}{2z+\sqrt 3+i} $$
Now $w_1$  maps the lunes to the region between the lines $v=+\sqrt 3 u $ and $v=-\sqrt 3 u $ in left half plane, that is
$$2\pi/3 <arg w < 4\pi/3$$
Now $e^{-i2\pi/3}w_1$ maps to
$$0 <arg w < 2\pi/3$$ and rising to power $3/2$ we arrive to upper half plane.
So my answer is $e^{-i\pi}w_1^{3/2}$, but the answer in end of my book is $e^{i\pi/3}w_1^2$. Could anyone please say me if my answer is wrong or my book is wrong? Thanks!

A: Your answer is correct. Note that the inner angle of the lens at $z_1$ and $z_2$ is ${2\pi\over3}$. This angle remains after the Möbius transformation $z\mapsto w$. Only the exponent ${3\over2}$ can convert this angle to $\pi$, as required for a half plane.


text:
Q: What are ordinary mass-terms (of neutrinos)? When reading the introduction to Sterile neutrino hot, warm, and cold dark matter I came across the following definition of sterile neutrinos:
We can define sterile neutrinos generically as spin-$\frac{1}{2}$, $SU(2)$-singlet particles which interact with the standard $SU(2)$-doublet ("active") neutrinos $\nu_e$, $\nu_\mu$, and $\nu_\tau$, solely via ordinary mass terms.
What is the meaning of ordinary mass terms?
Is it simply the mass terms of SM particles, in this case "active" neutrinos? Meaning that the mass of sterile neutrinos can be written in terms of the mass terms of  $\nu_e$, $\nu_\mu$, and $\nu_\tau$?
Or is there another meaning I am not understanding?

A:
What is the meaning of ordinary mass terms?

The "ordinary mass terms" in the quoted paper (see-saw mechanism) would stand for Dirac mass terms, which couple active left-handed neutrinos $\nu_L$ (the isospin "up" part of the electroweak $SU(2)$ left-handed neutrino-electron doublets) to the sterile right-handed neutrinos $\nu_R$ (as $SU(2)$-singlets):
$$
m (\bar{\nu}_L\nu_R + \bar{\nu}_R\nu_L).
$$
The "non-ordinary mass terms" would mean Majorana mass terms, which couple the sterile right-handed neutrino $\nu_R$ to the charge-conjugate of itself $\nu^c_R$:
$$
M \bar{\nu}_R\nu^c_R.
$$
The "ordinary" Dirac mass $m$ is of the eletroweak symmetry breaking scale, while the "non-ordinary" Majorana mass $M$ is of the much higher see-saw (or grand unification) scale . In the usual scheme of the sea-saw model, the tiny neutrino mass is the resultant effective mass $m_{\nu}$ with scale:
$$
m_{\nu}\sim \frac{m^2}{M}.
$$

A: I am understanding the "ordinary" in "ordinary mass terms" as a way for the author to emphasize the fact that the mass term coupling does not come from a renormalization effect for some other interaction or that it does not arise due to symmetry breaking. And that the coupling itself comes from a type of mixing resembling the PMNS matrix, which mixes the masses of the active and sterile neutrinos.


text:
Q: CMake - add_executable called with incorrect number of arguments I am trying to organize a C++ project which starts to have a lot of files. I would like to create two executables which share some source file using Cmake. I have found an interesting procedure here:
How to add source files in another folder
Below is my version of the thing
file(GLOB Common_sources RELATIVE "Common" "*cpp")
file(GLOB Mps_sources RELATIVE "Mps" "*.cpp")
file(GLOB Mss_sources RELATIVE "Mss" "*.cpp")

add_executable(test_mss ${Common_sources} ${Mss_sources})
add_executable(test_mps ${Common_sources} ${Mps_sources})

But CMake complains
CMake Error at src/CMakeLists.txt:44 (add_executable):
add_executable called with incorrect number of arguments

CMake Error at src/CMakeLists.txt:45 (add_executable):
add_executable called with incorrect number of arguments

It says to look at CMakeOutput.log, but the file is really too long, I can not find useful information.
I checked the CMake documentation, it seems that it can take a second source as an additional argument. https://cmake.org/cmake/help/v3.0/command/add_executable.html
I would like to find the source of this bug. I have the feeling that I am missing something obvious here.

A: The error you get is because source list, passed to add_executable, is actually empty.
Correct way for collect sources in Common/ subdirectory is:
file(GLOB Common_sources "Common/*.cpp")

In command file(GLOB) RELATIVE option doesn't specify search directory. Instead, it just tells CMake to generate relative paths instead of absolute:

If RELATIVE flag is specified, the results will be returned as relative paths to the given path.

Assuming
file(GLOB Common_sources "Common/*.cpp")
# gets: /<path-to-source>/Common/my_source.cpp

then (also note to absolute path in RELATIVE option)
file(GLOB Common_sources RELATIVE "${CMAKE_CURRENT_SOURCE_DIR}/Common" "Common/*.cpp")
# gets: my_source.cpp

and (when files are not under RELATIVE directory)
file(GLOB Common_sources RELATIVE "${CMAKE_CURRENT_SOURCE_DIR}/Mps" "Common/*.cpp")
# gets: ../Common/my_source.cpp

A: You have to quote the variables.
add_executable(test_mss "${Common_sources}" "${Mss_sources}")

Otherwise for an empty variable, CMake replaces the variable by nothing and the number of arguments seems to be wrong.
Similar problem: https://stackoverflow.com/a/39733128/2799037

A: None of the suggested answers worked for me.
This works:
add_executable(<executable_name> <source_file_name>)


text:
Q: Get the text margins of a QLineEdit How can I get the text margins for a QLineEdit?
Note the red lines in the screenshot, that's the margins I'm interested in:

I tried qDebug() << ui->lineEdit->textMargins(); for the edit box from the screenshot, but it printed QMargins(0, 0, 0, 0), even though the edit box does have margins.

A: Check paint event of QLineEdit. As you can see lots of stuff have effect on it.
Besides textMargins there are stuff which can have impact on values which you are looking for.

*

*used style (see line 1942)

*and font properties - see QFontMetrics::ascent and QFontMetrics::descent
The style value is most important and you have to find way to get this value (probably subclass is needed).


text:
Q: MSSQL 2012 Splitting Records Into Multiple Row Currently my record are as below. One complete record are split by pipe | and data are separate by comma.
 123,870503-23-5370,021|456,830503-23-5371,031|789,870103-11-5372,041|654,870501-23-5373,051|321,880503-12-5374,061|987,870803-23-5375,071|109,870508-06-5376,081|174,810503-03-5377,091|509,870103-01-5378,101|687,870501-12-5379,131

How to split the record to become:
C1  C2             C3
123 870503-23-5370 021
456 830503-23-5371 031
789 870103-11-5372 041
......

A: This kind of operation should be done in application layer.
Quick workaround uisng XML to split based on |:
declare @S varchar(1000) = '123,870503-23-5370,021|456,830503-23-5371,031|789,870103-11-5372,041|654,870501-23-5373,051|321,880503-12-5374,061|987,870803-23-5375,071|109,870508-06-5376,081|174,810503-03-5377,091|509,870103-01-5378,101|687,870501-12-5379,131'

Spliting to each column using PARSENAME:
;WITH cte AS
(
select
REPLACE(n.r.value('.', 'varchar(500)'), ',','.') As c
from (select cast('<r>'+replace(@S, '|', '</r><r>')+'</r>' as xml)) as s(XMLCol)
  cross apply s.XMLCol.nodes('r') as n(r)
)
SELECT PARSENAME(c,3) AS col1,
       PARSENAME(c,2) AS col2,
       PARSENAME(c,1) AS col3
FROM cte;

LiveDemo
Output:
╔══════╦════════════════╦══════╗
║ col1 ║      col2      ║ col3 ║
╠══════╬════════════════╬══════╣
║  123 ║ 870503-23-5370 ║  021 ║
║  456 ║ 830503-23-5371 ║  031 ║
║  789 ║ 870103-11-5372 ║  041 ║
║  654 ║ 870501-23-5373 ║  051 ║
║  321 ║ 880503-12-5374 ║  061 ║
║  987 ║ 870803-23-5375 ║  071 ║
║  109 ║ 870508-06-5376 ║  081 ║
║  174 ║ 810503-03-5377 ║  091 ║
║  509 ║ 870103-01-5378 ║  101 ║
║  687 ║ 870501-12-5379 ║  131 ║
╚══════╩════════════════╩══════╝

Warning:
Using XML may cause problems when your string contains some characters like <&'">.
PARSENAME is used to quicky split up to 4 slices. Works only with data that doesn't contain . character.
EDIT:
Inserting is very easy:
;WITH cte AS
(
select
REPLACE(n.r.value('.', 'varchar(500)'), ',','.') As c
from (select cast('<r>'+replace(@S, '|', '</r><r>')+'</r>' as xml)) as s(XMLCol)
  cross apply s.XMLCol.nodes('r') as n(r)
)
INSERT INTO your_table(col1, col2, col3)
SELECT PARSENAME(c,3) AS col1,
       PARSENAME(c,2) AS col2,
       PARSENAME(c,1) AS col3
FROM cte;

A: Another method could be simply export the data to a csv file (you can easily do it through the management studio) and then load that csv file using BULK INSERT by specifying field and record delimiters. Detailed explanation in how to do this can be found here: bulk insert csv


text:
Q: How to get information from table I have an sql table that has 2 columns, one is id_User from a table named applicationUsers and the other one id_Schedule from the table schedule, when i insert information on them i have to do it by the id, but also i have tha table showed on a datagridview, it shows the 2 colums correct, but how can i get for example i have in the main table 1 1, that the name of the user 1 is David and the name of the schedule is special.
How can i show the name from the user 1(David) and the name from the schedule 1(special) in the datagridview?

A: You would need to execute a query that joins all three tables, e.g.
SELECT u.UserName, s.ScheduleName
FROM User u INNER JOIN UserSchedule us
ON u.UserID = us.UserID INNER JOIN Schedule s
ON s.ScheduleID = us.ScheduleID

Populate a DataTable from that query and bind it to a DataGridView and you'll see the user name and schedule name in the two columns.


text:
Q: How are population fractions and sampling fractions derived? I have this function:
corrected_prob<- function(result,population_fraction,sample_fraction){
value<-1/(1+(1/population_fraction-1)/(1/sample_fraction-1)*(1/result-1))
return(value)
}

Which I then use population_fraction and sample_fraction on it:
yprob_corrected <- corrected_prob(result=y_prob, population_fraction =0.04, sample_fraction =0.33)

In statistics, how does one derive population fraction and sample fractions?

A: I'm not sure of your definitions or why you feel 'correction'
is needed.
Population. If a random variable $X \sim \mathsf{Binom}(n = 10, p = .4),$ then $P(X = 5)$ is the long run proportion of occurrences of the result 5 when the binomial experiment described by this model is performed. Specifically, $$P(X = 5) = {10 \choose 5}(.4)^5(.6)^5 = 0.2006581,$$ which can be computed in R as follows:
dbinom(5, 10, .4)
[1] 0.2006581

Samples. If the binomial experiment is repeated many times, say $10\,000,$ the number of occurrences of 5 divided by $10\,000$ is the population proportion of 5s. The Law of Large Numbers
says that this sample proportion becomes closer to the probability 0.2006581 as the number of repetitions increases.
So for $10\,000$ repetitions, we can expect a pretty good match. The program below shows one of many ways to simulate
$10\,000$ repetitions.
set.seed(1028)  # for reproducibility
x = rbinom(10000, 10, .4)
table(x)
x
   0    1    2    3    4    5    6    7    8    9
  60  424 1200 2170 2461 2014 1099  453   99   20

So we say $2014$ occurrences of 5 in $10\,000$ iterations,
for a sample proportion of $0.2014.$ As expected, this is
close to the population proportion, but not an exact match.
I know of no legitimate way to 'correct' 0.2014 to get closer
to 0.2006581. (Starting over with a larger number of iterations might get a sample proportion closer to 0.2006581; but that's a re-enactment not a 'correction'.)
Graphical comparison. The histogram below shows the number of occurrences of the
numbers 0 through 10 from the simulation experiment. The centers
of the red circles show the exact binomial probabilities.
The match is good for 5's, and also for the other possible values.

If this is not what you meant by your question, please try to
be specific why not, and please try to give an example of your own to explain what kind of help you're looking for.