text:
Q: Apex test run doesn't report back to sfdx I used to run Apex tests using sfdx force:apex:test:run -r human -c command and everything was fine. But after I've created another scratch org this command no longer produces any result, it just hangs. At the same time if I go to Developer Console, I can see, that the test run was actually started and successfully finished. Are there any issues with Salesforce, my dev hub or scratch org?
UPD: These are the three latest records in the log
{
    "name": "sfdx",
    "hostname": "<my host>",
    "pid": 16112,
    "level": 40,
    "msg": "[ '\\u001b[33mWARNING:\\u001b[39m',\n  'In salesforcedx v41 and earlier, the --resultformat parameter caused the apex:test:run command to wait for test results rather than finishing immediately and returning a test run ID. In salesforcedx v42 and later, the --resultformat parameter will no longer cause the command to wait. To wait for test results, include the --wait parameter.' ]",
    "time": "2018-11-13T04:37:25.817Z",
    "v": 0
}{
    "name": "sfdx",
    "hostname": "<my host>",
    "pid": 14356,
    "log": "SourceUtil",
    "level": 40,
    "msg": "Could not delete the outputDir 'C:\\Users\\<my user>\\AppData\\Local\\Temp\\sdx_decomposition_1542085385437' due to: ENOENT: no such file or directory, stat 'C:\\Users\\<my user>\\AppData\\Local\\Temp\\sdx_decomposition_1542085385437.zip'",
    "time": "2018-11-13T05:03:05.458Z",
    "v": 0
}{
    "name": "sfdx",
    "hostname": "<my host>",
    "pid": 14356,
    "log": "SourceUtil",
    "level": 40,
    "msg": "Could not delete the outputDir 'C:\\Users\\<my user>\\AppData\\Local\\Temp\\sdx_mdpkg_1542085385434' due to: ENOTDIR: not a directory, scandir 'C:\\Users\\<my user>\\AppData\\Local\\Temp\\sdx_mdpkg_1542085385434.zip'",
    "time": "2018-11-13T05:03:08.100Z",
    "v": 0
}

A: Could your problem be related to https://success.salesforce.com/answers?id=9063A000000t5onQAA
"What has changed with the sfdx force:apex:test:run command since November 8th 2018
sfdx force:apex:test:run has a --wait argument which defaults to 6 minutes
This has always been interpreted as "if the command doesn't return within this time limit, then TIMEOUT"
Since November 8th/9th, it appears the command waits for the default 6 minutes before running the tests."
I've since discovered the tests actually run on time.
But the sfdx test command waits for the full duration of the --WAIT argument before returning the results.
This has been recognised as a bug by Salesforce, and is currently being worked on.
There is no known workaround.
There is no estimated time for a fix.


text:
Q: Laravel single route point to different controller depending on slugs I'm new to laravel and I have searched a lot for an answer to my problem but either it's not applicable or I'm not getting it.
I have a FileMaker solution for a client that handle customers and events. Each customer to my client have their own event websites that is managed via the solution. A cms simply. Each customer get a site with a url like clientsite.com/event.
Each page in the event has a page-type and I would like to address different controllers depending on the type.
In routes.php i have:
Route::group(['middleware' => ['sal', 'menu']], function () {

    Route::get('/{event}/{page}', function($event, $page) {
        // Query page for page-type and use controller depending on type
    });
});

There are many page types (standard text/image, specialized forms etc) and therefor I would like to address different controllers.
Event names are always unique but pages are not.

A: You could call a controller manually inside the route closure. Though I would suggest doing the validation in a helper file to make the route file clean and readable.
Route::group(['middleware' => ['sal', 'menu']], function () {

    Route::get('/{event}/{page}', function($event, $page) {
        // you could do something like
        $user_type = Auth::user()->user_type;
        if($user_type == "organizer")
        {

            $controller = $app->make('OrganizerController');
            return $controller->callAction('controllerFunc', $parameters = array());
        }
        else
        {
           $controller = $app->make('ClientController');
           return $controller->callAction('controllerFunc', $parameters = array());
        }

    });
});

A: An alternative to the route solution could be to handle the logic in the controller itself:
First, update routes.php to something like:
Route::group(['middleware' => ['sal', 'menu']], function () {
    Route::get('/{event}/{page}', 'RoutesController@index');
});

Then, in the RoutesController.php file (add to app/Http/Controllers), you can do something similar to:
public function index()
{
    $event = Request::segment(1); // get the {event} part of the route
    $page = Request::segment(2); // get the {page} part of the route

    // get event data from database, e.g.
    $event_data = Event::where( 'slug', $event )->first();

    // load correct page
    switch ( $page ) {
        case "people":
            return $this->people();
        break;
        case "anotherPage":
            return $this->another_page();
        break;
    }
}

private function people()
{
    // show view
    return View::make('event.people');
}

This solution keeps your routes file clean, but also lets you handle the different event and page data, and load different views depending on the page being looked at. Your extra logic would be better in a controller rather than the routes file.
It all depends on where you prefer to code your page / view logic. You can use this approach call functions in the same controller, or external ones.

redpajama_set_name: RedPajamaStackExchange


text:
Q: "kubeadm init" fails on setting up Highly Available clusters I try to setup a haproxy'd multi-master node setup for Kubernetes, as described in [1]. My network configurations are:

*

*haproxy = 192.168.1.213

*master0|1|2 = 192.168.1.210|211|212

*worker0|1|2 = 192.168.1.220|221|222 (not interesting at this point)

all hosts are able to connect to each other (DNS is resolved for each node). Each node is running Ubuntu 18.04.3 (LTS). Docker is installed as

*

*docker.io/bionic-updates,bionic-security,now 18.09.7-0ubuntu1~18.04.4 amd64 [installed]

Kubernetes packages currently installed are

*

*kubeadm/kubernetes-xenial,now 1.16.3-00 amd64 [installed]

*kubectl/kubernetes-xenial,now 1.16.3-00 amd64 [installed]

*kubelet/kubernetes-xenial,now 1.16.3-00 amd64 [installed,automatic]

*kubernetes-cni/kubernetes-xenial,now 0.7.5-00 amd64 [installed,automatic]

using an additional repository as described in [2] (i'm aware that i've installed bionic on my VMs, but the "newest" repo available is still xenial).
My haproxy is installed as haproxy/bionic,now 2.0.9-1ppa1~bionic amd64 [installed] from [3] repository.
global
    log /dev/log        local0
    log /dev/log        local1 notice
    chroot /var/lib/haproxy
    stats socket /run/haproxy/admin.sock mode 660 level admin expose-fd listeners
    stats timeout 30s
    user haproxy
    group haproxy
    daemon

defaults
    log global
    mode http
    retries 2
    timeout connect 3000ms
    timeout client  5000ms
    timeout server  5000ms

frontend kubernetes
    bind        *:6443
    option      tcplog
    mode        tcp
    default_backend kubernetes-master-nodes

backend kubernetes-master-nodes
    mode    tcp
    balance roundrobin
    option  tcp-check
    server  master0 192.168.1.210:6443 check fall 3 rise 2
    server  master1 192.168.1.211:6443 check fall 3 rise 2
    server  master2 192.168.1.212:6443 check fall 3 rise 2

While trying to setup my first control plane, running kubeadm init --control-plane-endpoint "haproxy.my.lan:6443" --upload-certs -v=6 as described in [4] results in this error:
Error writing Crisocket information for the control-plane node

full log in [5]. I'm pretty lost, if there's a mistake in my haproxy configuration or if there might be some fault in docker or kubernetes itself.
My /etc/docker/daemon.json looks like this:
{
  "exec-opts": ["native.cgroupdriver=systemd"],
  "log-driver": "json-file",
  "log-opts": {
    "max-size": "100m"
  },
  "storage-driver": "overlay2"
}

*

*[1] https://kubernetes.io/docs/setup/production-environment/tools/kubeadm/high-availability/

*[2] https://kubernetes.io/docs/tasks/tools/install-kubectl/#install-using-native-package-management

*[3] https://launchpad.net/~vbernat/+archive/ubuntu/haproxy-2.0

*[4] https://kubernetes.io/docs/setup/production-environment/tools/kubeadm/high-availability/#stacked-control-plane-and-etcd-nodes

*[5] https://pastebin.com/QD5mbiyN

A: While not being able to find a decent solution and created an issue in the original  "kubeadm" project at github, see here: https://github.com/kubernetes/kubeadm/issues/1930 .
Since the "triage" suggested in the issue was not feasable (Ubuntu is pretty much "set") for me, I ended in setting up another Docker distribution, as described here: https://docs.docker.com/install/linux/docker-ce/ubuntu/ , purging installed distribution before starting the new setup.
While running Docker (Community) v19.03.5 through kubeadm v1.16.3 throws the following warning:
[WARNING SystemVerification]: this Docker version is not on the list of validated versions: 19.03.5. Latest validated version: 18.09

the results are pretty fine, I managed to setup my ha cluster, as described in the original documentation.
So, this can be considered as a workaround, NOT as a solution to my original issue!


text:
Q: How to emulate gps using network location in the android Emulator? I have test using gps location and success. But now i want to test using network location.
How can i do it?

A: If you are using eclipse and the AVD Emulator do the following:
Window -> Show View -> Other
Android -> Emulator Control

This will open a tab in the IDE that will give you all the controls to interface with your running emulator.


text:
Q: Update object to another using Panache JPA I'm working with PanacheRepositories in Quarkus.
Currently I want to realize the function update(X x).
Basically what I want is the function to do is check if an entity y exists having id==x.id exists and update it to x, however I can't figure out if this is possible without having to deep copy every attribute from x into y.
I don't want that, because the object is huge.
Is there any way to do something like
MyEntity y = repository.findById(x.id);
if(y != null){
  y = x;
  repository.persist(y)
}

without detaching the entity?

A: I didn't realize that PanacheRepository is just an overlay of EntityManager, which has the functionality I'm looking for.
So I could just inject the EntityManager and use merge(x) which did exactly what I wanted


text:
Q: every div & designing(full website) repeated multiple time base on data if database have 1 row all div print 1 time if more then more time.why <?php
$conn=mysqli_connect("localhost","root","","users");

    $sql="SELECT * FROM users";
    $result=mysqli_query($conn,$sql);
    while ($row=$result->fetch_assoc())
    {
        $user_id=$row['user_id'];

?>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <title>Admin Panel</title>
    <meta name="description" content="">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <meta name="robots" content="all,follow">

    <link rel="stylesheet" href="vendor/bootstrap/css/bootstrap.min.css">

    <link rel="stylesheet" href="vendor/font-awesome/css/font-awesome.min.css">

    <link rel="stylesheet" href="css/fontastic.css">

    <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Poppins:300,400,700">

    <link rel="stylesheet" href="css/style.default.css" id="theme-stylesheet">

    <link rel="stylesheet" href="css/custom.css">

    <link rel="shortcut icon" href="img/favicon.ico">

            <button class="dismiss"></button>
            <form id="searchForm" action="#" role="search">
              <input type="search" placeholder="What are you looking for..." class="form-control">
            </form>

Admin Panel

AP

Logout

Mark Stephen

Web Designer

          Main

 Show All Record

 Logout

Dashboard

<?php echo $user_id ?>

Appxone © 2017-2018

Design by Appxone

<?php } ?>

My issue
i have multiple value in database the problem is number of records is
equal to number of css,html, all text repeated multiple time related to database row means  every div & designing & text repeated multiple time base on data if database have 1 row all div print 1 time if more then more time.why?
thank in advance plz tell me correct anwser and find my error in my code

A: You're repeating the whole HTML document in while loop, do you mean just repeate
$user_id
 like this?:
<?php
$conn=mysqli_connect("localhost","root","","users");

    $sql="SELECT * FROM users";
    $result=mysqli_query($conn,$sql);

?>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <title>Admin Panel</title>
    <meta name="description" content="">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <meta name="robots" content="all,follow">

    <link rel="stylesheet" href="vendor/bootstrap/css/bootstrap.min.css">

    <link rel="stylesheet" href="vendor/font-awesome/css/font-awesome.min.css">

    <link rel="stylesheet" href="css/fontastic.css">

    <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Poppins:300,400,700">

    <link rel="stylesheet" href="css/style.default.css" id="theme-stylesheet">

    <link rel="stylesheet" href="css/custom.css">

    <link rel="shortcut icon" href="img/favicon.ico">

            <button class="dismiss"></button>
            <form id="searchForm" action="#" role="search">
              <input type="search" placeholder="What are you looking for..." class="form-control">
            </form>

Admin Panel

AP

Logout

Mark Stephen

Web Designer

          Main

 Show All Record

 Logout

Dashboard

<?php
    while ($row=$result->fetch_assoc())
    {
        $user_id=$row['user_id'];
        echo "
$user_id
";
    }
?>

Appxone © 2017-2018

Design by Appxone


text:
Q: Navigation Drawer icons gone Android Studio 2.3.3 I am testing the Navigation Drawerin Android Studio 2.3.3. When I create the default Navigation Drawer Activity provided by Android Studio it comes without any kind of icon in the action bar.
I have also tested in real device, launching the app right after creation, that means, without modifying anything else and the drawer does not slide in when sliding in the screen.
Anybody else faced this problem in AS 2.3.3?
Any solution for that?

activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/drawer_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fitsSystemWindows="true"
    tools:openDrawer="start">

    <include
        layout="@layout/app_bar_main"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

    <android.support.design.widget.NavigationView
        android:id="@+id/nav_view"
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:layout_gravity="start"
        android:fitsSystemWindows="true"
        app:headerLayout="@layout/nav_header_main"
        app:menu="@menu/activity_main_drawer" />

</android.support.v4.widget.DrawerLayout>


text:
Q: Question about the superposition-theorem I had this exam question, where I was asked to solve a circuit with the superposition theorem. I did it by mesh analysis because I didn't read correctly, but to check my procedure I did a different version of the superposition theorem.
The superposition theorem states that you should consider the influence that each element taken separately has on the circuit, and then sum those influences.
What I did was that I didn't consider them completely separately. The thing worked and got the right results.
Important to note here is that no separate case had repeated elements, OK? For example if I had three elements A,B and C; I would consider the influence of A,B then of C. I did not repeat elements in the distinct scenarios. For example I wouldn't have done A,B and A,C and then sum them.
How can I show that my procedure is in line with the superposition theorem?
Thanks!

A: Superposition says that the solution to a linear circuit with multiple sources \$A\$, \$B\$, and \$C\$ is
$$
S_{ABC} = S_A + S_B + S_C
$$
where each \$S_X\$ is the solution with only source \$X\$ active.
You could also write this as
$$
S_{ABC} = (S_A + S_B) + S_C = S_{AB} + S_C
$$
where you've combined sources \$A\$ and \$B\$ before considering \$C\$. That's fine.
What you did was you skipped straight to the last expression: you found \$S_{AB}\$ (without superposition) and used that to help you get the solution. Looks good to me.


text:
Q: Where am I going wrong when creating authentication in Laravel? PHP 7.4
Laravel 8
Route 1 (super.com/auth):
Receives email, password data and makes authentication.
$result = Auth::Attempt(['password' => 'superpwd', 'email' => 'super@mail.ru'], true);
Auth::check() // true

Route 2 (super.com/testAuthCheck):
We check the authentication.
Auth::check(); // false

It turns out that the authentication is not saved in the session.
Please tell me where I'm wrong? May be session or some setting, or modules...
Full code:

use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Hash;

class AuthUser extends Controller
{
    public function register(Request $request)
    {
        $request->validate([
            'name'       => 'required|string',
            'lastname'   => 'required|string',
            'secondname' => 'required|string',
            'tel'        => 'required|numeric',
            'password'   => 'required|string',
        ]);

        $user = User::create([
            'name'       => $request->name,
            'lastname'   => $request->lastname,
            'secondname' => $request->secondname,
            'tel'        => $request->tel,
            'password'   => Hash::make($request->password),
            'email'      => '',
        ]);

        $login = Auth::login($user);

        return response()->json([
            'message' => 'Success!',
            'login' => $login
        ]);
    }
    public function test(Request $request) {
        if(Auth::Attempt(['password' => 111, 'email' => 'a@b.ru'], true)) {
            $request->session()->regenerate();
            $result = Auth::check();
            dump($result); // true
        }
    }

    public function test2(Request $request) {
        $result = Auth::check();
        dump($result); // false
    }

A: Using dump will most likely cause more problems while debugging this.
     public function test(Request $request) {
        if(Auth::Attempt(['password' => 111, 'email' => 'a@b.ru'], true)) {
            $request->session()->regenerate();
            $result = Auth::check();
            //dump($result); ***will terminate the request and the session will not be set correctly ***
            info($result); // check storage/logs/laravel.log

        }
    }


text:
Q: Conditional constraint based on value in another table? With Postgres, I'm not sure how to set this up. I have two tables (pseudocode):
Table A
ID int
Unique bool

Table B
TableA_ID int
UserID int

What I want is if Unique in a row in Table A is true, to set a constraint on all rows in Table B that reference that TableA_ID row, the constraint being that (TableA_ID, UserID) are unique. But only for those rows that reference that particular Table A row.
Edit: This is for a database system. That is, each row in Table A describes a table of data (name, description, what the columns are, etc), and each row in Table B contains the values for a row in a table from Table A, along with some meta data like who created the row. We want to have the ability to designate some tables such that each user can only add one row to them, while other tables we don't care.


text:
Q: "serialport" node module version error message confusing Does the following node error mean I need to upgrade the serialport module, or downgrade nodejs, or something else?   (It used to work until I updated ubuntu from 16.04 to 18.04)
Error: The module '../node_modules/@serialport/bindings/build/Release/bindings.node'
was compiled against a different Node.js version using
NODE_MODULE_VERSION 67. This version of Node.js requires
NODE_MODULE_VERSION 57. Please try re-compiling or re-installing
the module (for instance, using `npm rebuild` or `npm install`).

I have tried:
rm package-lock.json;
rm -rf node_modules;
npm install
npm rebuild
npm install serialport --build-from-source
sudo npm install serialport --unsafe-perm --build-from-source

Is there a simple way to fix this?

A: Completely removed nodejs npm, reinstalled, ran nodejs main.js  and then installed packages as necessary using npm.  Works now.


text:
Q: Crash dumps: ntdll.dll has version 6.2 on Windows 10? We're getting quite many strange crash dumps from our users: there, in OS Version "10.0.18363" is specified, but all system's DLL files has version "6.2.x" (i.e. Windows 8).
What is going on? How can this be?


text:
Q: git log format for mercurial I like the way git displays its log(like in the man pages format). Is there any way I could customize mercurial to display its log(or glog) in a similar format?

A: If you want a formatting that resembles git logs, put this in your .hgrc:
[alias]
vlog = log --template '\033[0;33mcommit: {rev}:{node}\n\033[0mAuthor: {author}\nDate:   {date|rfc822date}\n\n\t{desc|strip|fill68|tabindent}\n\n'

Here's a sample output. (In a terminal, the commit-line is colored).
$ cd code/mercurial
$ hg vlog
commit: 16004:7d12b2d3a83d44271b3aa515fe8d211e47bac2c0
Author: Matt Mackall <mpm@selenic.com>
Date:   Fri, 27 Jan 2012 18:43:31 -0600

        merge with i18n

commit: 16003:0d898ebb424ee85da76bc41584b14ac391549077
Author: Alexander Sauta <demosito@gmail.com>
Date:   Fri, 27 Jan 2012 12:25:02 +0400

        i18n-ru: synchronized with bf502ccc46d7; fuzzies removed

commit: 16002:384f7521c79152d6d197c0659f81e099067cadc3
Author: Nikolaj Sjujskij <sterkrig@myopera.com>
Date:   Thu, 26 Jan 2012 16:56:11 +0400

        i18n-ru: fix typos in `resolve` help

         * help entry is called 'merge-tools', not 'merge-tool';
         * envvar is called HGMERGE, not HGEMERGT.

commit: 16001:fcf66193b18699141e1da1ef4de4795d62a658cb
Author: Matt Mackall <mpm@selenic.com>
Date:   Thu, 26 Jan 2012 20:34:57 -0600

        merge: defer symlink flag merging to filemerge (issue3200)

        Previously, we could change a normal file into a corrupt symlink
        when trying to merge a symlink flag. Now, we leave the flag alone
        and let filemerge deal with it (usually by a prompt).

        We also drop a redundant flag setting after filemerge (now dealt
        with by ms.resolve) that would cause similar corruption.

A: I think Den figured out what you mean, but if you're actually looking to alter the output stylistically you can do that with the --style command.  Examples:
$ hg log --style xml
<?xml version="1.0"?>
<log>
<logentry revision="13480" node="69418d4525d166793bc63789b2bd64fcc3d84401">
<branch>stable</branch>
<tag>tip</tag>
<author email="tamizhgeek@gmail.com">Azhagu Selvan SP</author>
<date>2011-02-24T01:14:15+05:30</date>
<msg xml:space="preserve">convert/svn: abort operation when python bindings are not available
 ...

and
$ hg log --style changelog -l
2011-02-24  Azhagu Selvan SP  <tamizhgeek@gmail.com>

    * hgext/convert/subversion.py:
    convert/svn: abort operation when python bindings are not available

    Subversion python bindings check was not present in svn_sink source
    class which made it fail while using svn as destination repository.
    Added a more maintainble svn bindings check for svn_source and
    svn_sink classes.
    [69418d4525d1] [tip] <stable>
...

A: I'm guessing that by 'man pages format' you mean allowing you to scroll backwards and forwards in the output. You can accomplish the same thing in mercurial using the pager extension. It can be accomplished by adding the following to your .hgrc:
[pager]
pager = LESS='FSRX' less
[extensions]
pager =

the FSRX arguments to less let it show any colored output you might have hg log showing.


text:
Q: Android Browser can not support play list with HTML5 Audio in background mode I want to make Radio Web App Android-browser-based.
The key function for my Web App is continuously playing music-list
(mp3 files) ...
JavaScript Code is simple ...
And it works well in PC Browser, iOS safari, and Android Dolphin
Browser (3rd party browser)...

var audioPlayer = new Audio();

audioPlayer.addEventListener('ended', nextSong, false);

function nextSong() {
  audioPlayer.src = nextMusic_src;
}

But. in Android Default Browser,
when android is in background mode (Home Screen mode & LCD-off Sleep
mode),
Android Browser's onPause()  prevent "ended" event & execution of
nextSong().
So, my web app can play only one music....  and does not work any
more.....
Android Browser's onPause()  source code is like this ...

BrowserActivity.java
public class BrowserActivity extends Activity
{

   private Controller mController;

   // ...

   @Override

   protected void onPause() {

       if (mController != null) {
           mController.onPause();        //   <<==== here
       }
       super.onPause();
   }

}

Controller.java
public class Controller implements WebViewController, UiController {

   protected void onPause() {

       // ...
       mActivityPaused = true;
       // ...
       mUi.onPause();
       mNetworkHandler.onPause();        //   <<==== here

       WebView.disablePlatformNotifications();      //   <<====here
   }

}

NetworkStateHandler.java
public class NetworkStateHandler {

   // ...

   void onPause() {

       // unregister network state listener

       mActivity.unregisterReceiver(mNetworkStateIntentReceiver);  //  <<==== here

   }

}

Is there any browser policy for preventing event in background
mode....?
If not, how can I notice this report to the Google developer for
requesting background music play with web app...?
I consider not WebView based web-app (Hybrid) but only browser-based
web-app...
thank you...
Nohyun Kwak

A: Droid's ended event doesn't fire consistently. It's fixed in ICS, I hear. But Gingerbread and prior have the issue.
Instead of listening for .ended, can you listen for .timeupdate and in that handler, see if the time is the end of the song? That may solve your issue.


text: Q: Как правильно подключать css стили Делаю проект на AngularJS. Есть несколько страниц: index.html, page1.html, page2.html..... Как сделать так, чтобы на всех этих страницах была ссылка на один и тот же файл css? Причём если я захочу поменять название файла, то на всех остальных страницах он тоже измениться.


text:
Q: Mp3 player and JMF I am trying to develop a mp3 player using java.I tried several codes and it ended up in too many errors.So please provide me hints about the code and also help me to configure JMF??

A: JMF natively does not support mp3 as mp3 is not open source.
If you want to play mp3 file you may do this using jlayer, mp3spi and tritonus libraries.
If you need more informations on these library then let me know.
Please see the below code. With the three libraries added to built path, this code worked for me. Hope this will help you
String mp3File = "path to mp3 file";

public void playMp3(String mp3File ) {
    AudioInputStream din = null;
    AudioInputStream in = null;
    try {
        File file = new File(mp3File);
        in = AudioSystem.getAudioInputStream(file);
        AudioFormat baseFormat = in.getFormat();
        AudioFormat decodedFormat = new AudioFormat(
                AudioFormat.Encoding.PCM_SIGNED,
                baseFormat.getSampleRate(), 16, baseFormat.getChannels(),
                baseFormat.getChannels() * 2, baseFormat.getSampleRate(),
                false);
        din = AudioSystem.getAudioInputStream(decodedFormat, in);
        DataLine.Info info = new DataLine.Info(SourceDataLine.class, decodedFormat);
        line = (SourceDataLine) AudioSystem.getLine(info);

        if (line != null) {
            line.open(decodedFormat);
            byte[] data = new byte[4096];
            // Start
            line.start();

            int nBytesRead;
            while ((nBytesRead = din.read(data, 0, data.length)) != -1) {
                line.write(data, 0, nBytesRead);
                if (flag) {
                    break;
                }
            }
            line.drain();
            line.stop();
            line.close();
            din.close();
        }

    } catch (UnsupportedAudioFileException uafe) {
        JOptionPane.showMessageDialog(null, uafe.getMessage());
        logger.error(uafe);
    } catch (LineUnavailableException lue) {
        JOptionPane.showMessageDialog(null, lue.getMessage());
        logger.error(lue);
    } catch (IOException ioe) {
        JOptionPane.showMessageDialog(null, ioe.getMessage());
        logger.error(ioe);
    } finally {
        if (din != null) {
            try {
                din.close();
            } catch (IOException e) {
            }
        }
        try {
            in.close();
        } catch (IOException ex) {
            logger.error(ex);
        }
    }
 }


text:
Q: Order by relational STAT in yii I'm using yii framework. I have a relation
'revCount'=>array(self::STAT, 'Review','rid','condition'=>'status=1')//count review for each restaurant

Now I want to fetch all Restaurants order by review count.
Restaurant::model()->findAll('with'=>'revCount');

What else I need to add so that I get all restaurants ordered by review count?

A: This is how you join other models with a single query:
Restaurant::model()->with('revCount')->findAll();

But what I think you want is not to join the model, but just to sort by it. Similar to this:
Restaurant::model()->with(array(
    'reviews'=>array(
        // we don't want to select reviews
        'select'=>false,
        // but want to get only reviews with status=1
        'joinType'=>'INNER JOIN',
        'condition'=>'reviews.status=1',
    ),
))->findAll();

A: You should be able to do the following..
Restaurant::model()->findAll('with'=>'revCount', 'select' => '(SELECT COUNT(*) FROM review WHERE rid = t.id AND status = 1) AS revCount');


text:
Q: Android ListView, each row display it's own content inside another ListView I have a ListView populated with some text ( phone models in my case, ex: Samsung A, B, C...) and an image ( loaded from URL using android-query ).
When a row is selected, a ViewPager will be created along with 3 Tabs ( Specs, Info, Img ), both fragments Specs and Info are displaying a ListView and the last fragment, Img is displaying a GridView. I'm having no issues with the last fragment, but only with the first 2, as I don't know how to populate the ListView so it will display the content for the selected row.
Is it possible to specify for each row a different string array?
If not, how can I achieve this:

As you can notice in this example, Samsung D, has more informations than the previous one.

This is the main ListView's ClickListener:
listView.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Bundle bundle = new Bundle();
                bundle.putInt("id", position);
                TabStripAdapter newFragment = new TabStripAdapter();
                newFragment.setArguments(bundle);
                FragmentTransaction transaction = getFragmentManager().beginTransaction();
                transaction.replace(R.id.frame_container, newFragment);
                transaction.addToBackStack(null);
                transaction.commit();
            }
        });

Sorry for my english.

A: You should use the on OnItemClickListener for your main ListView and you will have 3 options:

*

*Having an array of objects in the main listview, but only display the model name or the info you want, so when the user select the item just get the object from the position and pass the values (object atributes) to the other activity.

*Having an array of objects in the main listview, but only display the model name or the info you want, so when the user select the item just get the object from the position and pass the object to the other activity.

*Having an two atributes object array (itemId, itemName) at the first activity and when the user select the item, pass the itemId to the next Activity, and from the 3-tabed activity ask (to the web service or database) for the info from the item you have the Id.
It should look something like this:
    MainListView.setOnItemClickListener(new android.widget.AdapterView.OnItemClickListener() {

    @Override
        public void onItemClick(AdapterView<?> parent, View view,int position, long id) {
 //       String selectedProductId = MainListArray.get(position).getId(); //Option 1 & 3
 //       String selectedProductInfo = MainListArray.get(position).getInfo ();
// ...more attributes  //Option 1
 //       CustomObject selectedProduct = MainListArray.get(position); //Option 2.
         Intent i = new Intent(_myContext, newActivity.class);
//         i.putString("productId", selectedProductId); //Option 1 & 3.
//         i.putString("productInfo", selectedProductInfo); //Option 1.
// ...more attributes //Option 2.
 //       i.putParceleable("product", selectedProduct); //Option 2.

         startActivity(i);
        }

});

For passing a complete object look  at this thread, it will show you how to do it.


text:
Q: To prove continuity of $\varphi(p) = \int_X |f|^p\ d\mu$ on $E = \{p: \varphi(p) < \infty\}$ where $0 < p < \infty$
Suppose $f$ is a complex measurable function on $X$, $\mu$ is a positive measure on $X$, and
$$\varphi(p) ~=~ \int_X |f|^p \; d\mu \quad (0 < p < \infty)$$
Let $E :=\{ p : \varphi(p) < \infty\}$. Assume $\|f\|_\infty > 0$. Prove that $\log\varphi$ is convex in the interior of $E$ and that $\varphi$ is continuous on $E$.

I have proved that $\log\varphi$ is convex on $\operatorname{int}E$, using Holder's inequality. We know that log-convexity implies convexity, so $\varphi$ is also convex on $\operatorname{int}E$, and hence continuous on $\operatorname{int}E$. How do we establish the continuity of $\varphi$ on $E$, though? I am missing exactly the points in $E\setminus\operatorname{int}E$.
I know this question has been previously answered here, but I'm unable to understand the proof. Moreover, I am trying to take a different approach to prove continuity. Let $\{p_n\}_{n\in\mathbb N}$ be a sequence in $E$, such that $p_n\to p$ (may or may not be in $E$ - we don't know if $E$ is closed, right?). I wish to show $\varphi(p_n)\to \varphi(p)$, i.e. $$\lim_{n\to\infty} \int_X |f|^{p_n}\ d\mu = \int_X |f|^p \ d\mu$$
This looks like a possible application of Lebesgue's Dominated Convergence Theorem, but I could not find a dominating function yet.
I would appreciate any help, thanks a lot!
I have already seen this answer - it did not help much. The proof was too convoluted, and I needed more details. @OliverDiaz and @robjohn were able to provide convincing detailed arguments, hence this post.

A: Since $E$ is a convex subset of $[0,\infty)$, $E$ is an interval (possibly open, half open, or closed). If $E$ has no interior then either $E$ is empty or $E$ is a singleton $\{p\}$ (for example, for $f(x)=\frac{1}{x(1+|\log x|)^2}\mathbb{1}_{(0,\infty)}(x)$, and $(X,\mu)=(\mathbb{R},\lambda)$, then $E=\{1\}$). In this case there is nothing else to prove.
If $E$ has interior, then $E$ could be of the form $(a, b)$, $(a,b]$, $[a,b)$, $[a,b]$, $(a,\infty)$, or $[a,\infty)$, where $0\leq a<b<\infty$. Hence, if $r$ is an endpoint of the interval $E$, then either $r$ is finite or  $r=\infty$.
Case $r$ is finite: consider the set $A=\{|f| > 1\}$. Then $|f|^p\xrightarrow{E\ni p\rightarrow r}|f|^r$ monotonically on $A$ and on $X\setminus A$. Applying monotone (or dominated convergence) gives
\begin{align}
\int_A|f|^p&\xrightarrow{E\ni p\rightarrow r}\int_A|f|^r\\
\int_{X\setminus A}|f|^p&\xrightarrow{E\ni p\rightarrow r}\int_{X\setminus A}|f|^r
\end{align}
From this, we obtain $\lim_{E\ni p\rightarrow r}\varphi(p)=\|f\|^r_r=\phi(r)$. Notice that if $r\notin E$, then $\varphi(r)=\infty$.
Case $r=\infty$: Although this  case is not necessary to study continuity of $\varphi$ on $E$, a few observations can be made.

*

*(1) $\lim_{p\rightarrow\infty}\|f\|_p=\lim_{p\rightarrow\infty}(\varphi(p))^{1/p} =\|f\|_\infty$;  a proof can be found here.

*(2) One can also see that $\lim_{p\rightarrow\infty}\varphi(p)$ exists in $[0,\infty]$. Consider $A$ as before and let  $C=\{|f|<1\}$, and $p_0\in E$. Then $|f|^p\mathbb{1}_C\leq |f|^{p_0}\mathbb{1}_C$ for all $p>p_0$. Another application of monotone convergence and dominated convergence gives
\begin{align}
\lim_{p\rightarrow\infty}\int_X |f|^p\,d\mu&=\lim_{p\rightarrow\infty}\Big(\int_C|f|^p\,d\mu + \mu(|f|=1) +\int_A|f|^p\,d\mu\Big)\\
&=\mu(|f|=1)+\infty\cdot\mu(\{|f|>1\})\end{align}
If $\mu(|f|>1)>0$, then $\|f\|_\infty>1$ and $\lim\limits_{E\ni p\rightarrow\infty}\varphi(p)=\infty$. If $\mu(|f|>1)=0$, then $\lim\limits_{E\ni p\rightarrow\infty}\varphi(p)=\mu(|f|=1)$.

Notice that unless $\|f\|_\infty<1$ or $\|f\|_\infty>1$, $\varphi(\infty)$ is not well defined.

A: Since $\varphi$ is log-convex, $E$ is an interval.

Least Upper Bound is Included
Suppose that $b$ is the least upper bound of $E$. If $b\not\in E$, there is nothing to prove, so suppose that $b\in E$. Let $b_n\in E$ and $b_n\to b$ monotonically (increasing).
Define
$$
Y=\{x\in X:|f(x)|\le1\}
$$
Since $b_n\le b$,
$$
\int_{X\setminus Y}|f(x)|^{b_n}\,\mathrm{d}\mu\le\int_{X\setminus Y}|f(x)|^b\,\mathrm{d}\mu\lt\infty
$$
and since $b_1\le b_n\le b$,
$$
\int_Y|f(x)|^b\,\mathrm{d}\mu\le\int_Y|f(x)|^{b_n}\,\mathrm{d}\mu\le\int_Y|f(x)|^{b_1}\,\mathrm{d}\mu\lt\infty
$$
Thus, $|f(x)|^b[x\in X\setminus Y]+|f(x)|^{b_1}[x\in Y]$ is a dominating function proving that
$$
\lim_{b_n\to b}\int_X|f(x)|^{b_n}\,\mathrm{d}\mu=\int_X|f(x)|^b\,\mathrm{d}\mu
$$

Greatest Lower Bound is Included
Suppose that $a$ is the greatest lower bound of $E$. If $a\not\in E$, there is nothing to prove, so suppose that $a\in E$. Let $a_n\in E$ and $a_n\to a$ monotonically (decreasing).
Define
$$
Y=\{x\in X:|f(x)|\le1\}
$$
Since $a_n\ge a$,
$$
\int_Y|f(x)|^{a_n}\,\mathrm{d}\mu\le\int_Y|f(x)|^a\,\mathrm{d}\mu\lt\infty
$$
and since $a_1\ge a_n\ge a$,
$$
\int_{X\setminus Y}|f(x)|^a\,\mathrm{d}\mu\le\int_{X\setminus Y}|f(x)|^{a_n}\,\mathrm{d}\mu\le\int_{X\setminus Y}|f(x)|^{a_1}\,\mathrm{d}\mu\lt\infty
$$
Thus, $|f(x)|^{a_1}[x\in X\setminus Y]+|f(x)|^a[x\in Y]$ is a dominating function proving that
$$
\lim_{a_n\to a}\int_X|f(x)|^{a_n}\,\mathrm{d}\mu=\int_X|f(x)|^a\,\mathrm{d}\mu
$$


text:
Q: I'm having a problem when I press the keyboard in Flutter
When I touch the keyboard it has such a height. This also gives an overflowed error

A: Well if you need the Scrolling effect in your screen, It's best to adjust all the elements inside a SingleChildScrollView() widget. But if you think you won't need that. All you want is to get rid of the jumping from bottom, the easiest way you can achieve this is by enabling this
resizeToAvoidBottomInset: true,
in your Scaffold() widget.


text:
Q: How to filter an array (using a regex) in C# Firstly I am brand new to C#, this is my first take on coding outside of HTML and CSS. I currently have a very large array and I want to filter said array by checking each string, if the string has a certain letter in it (in this case if it has any of the following letters (gkqmvwxz) then I want to move on from it and keep looking.
Once I find a string in the array that works I want to keep checking for the longest possible one. (This is from Tom Scott's video about 7 Segment Displays, it felt like a good challenge and he did his in javascript)
My Code looks like this
namespace Longest_Word_in_a_7_segment_display
{
    class Program
    {
        static void Main(string[] args)
        {
            string english = System.IO.File.ReadAllText(@"C:\Users\Max\Desktop\words.txt");
            char[] full = english.ToCharArray();

        }
    }
}

I have defined the string and converted it into an array, I've looked through regex syntax and tried some solutions but they all seem above me. Whats the best way to start learning how to do this so I can fully understand it?

A: I would suggest to start with basics. I am afraid you took big piece of cake to handle it. If you are brand new to C# you are only going to struggle and maybe give up in the future.
If you don't mind to start learning there is Introduction to C# with interactive tutorials or C# Fundamentals: Development for Absolute Beginners. If I were you I'll start there or find some other tutorials on the Internet.

A: Regex works on string not on char[],  I'd recommend you do the following
string english = System.IO.File.ReadAllText(@"C:\Users\Max\Desktop\words.txt");
Regex regex = new Regex(@"\b\w*(g|k|q|m|v|w|x|z)\w*\b");
List<string> filteredWords = regex.Matches(english).Select(x=> x.Value).ToList(); ///Using System.Linq


text:
Q: Variable javascript not working When using buka_halaman('produk','1') then working but when using variable is not working

function rute(){
//window.onhashchange = function(){
  switch(location.hash) {
    case location.hash:
 var abc = location.hash.split('#')[1]; // ex: domain.com/page.html#produk','1
 var def = "'"+abc+"'";
 if (abc!=undefined){
      alert(def);
      buka_halaman(def); //error
   buka_halaman('produk','1') //working
   }
    break;
  }
//}
}

A: Change this:
var def = "'" + abc + "'";

to this:
var def = abc;

Except that you don't need the def variable, you can just use abc directly:
buka_halaman(abc, '1');

Your code was putting single-quote characters into the string.


text:
Q: Decimal conversion I am trying to set decimal values,Below is my input string
String rate="1.000000000";

Converting to double:
Double converted=Double.valueOf(rate);
DecimalFormat format=new DecimalFormat("#.########"); //Setting decimal points to 8

System.out.println("ouput"+format.format(rate)); //Giving output as 1.

I dont understand how to do this,Any hints please.
Regards,
Chaitu

A: Try
DecimalFormat format=new DecimalFormat("#.00000000");

and
System.out.println("ouput"+format.format(converted));

A: # will not be displayed for 0, use 0 instead:
    String rate="1.010000000";
    Double converted=Double.valueOf(rate);
    DecimalFormat format=new DecimalFormat("0.00000000");
    System.out.println("ouput "+format.format(converted));

A: Firstly, you're passing the string rate to the DecimalFormat.format method.  This will fail, you need to pass the converted object in.
When I tested your code with the above changes, I got 1.01 in the output.  To format to 8 decimal places, follow Bala Rs comments.  i.e. DecimalFormat format = new DecimalFormat("#.00000000");


text:
Q: How to wrap an asynchronous function to avoid code duplication? I'm trying to avoid code duplication by wrapping this code in a separate function. Trouble is d3.json is asynchronous so sometimes an empty info object is returned. Is there a way to avoid code duplication here?
function getData(endpoint){

  //long stuff
  var info = {"succeeded": 1,"datum":[], "message":""};

   d3.json(endpoint, function(error, data) {

     //long stuff
     info.datum = data;
     return info;

  });

  return info;

}

A: Once you step into the world of asynchronous calls you can never get back again, so there's no way to do this without making your wrapper function asynchronous also.  Something like this could work:
function getData(endpoint, callback) {
    d3.json(endpoint, function(error, data) {
        var info = {
            succeeded: 1,
            data: data,
            message: ""
        };
        callback(info);
    });
};

Your callback function would accept one parameter that would be your "info" object.
Note that I moved the info object creation inside the d3 callback function closer to where it is used but this is just a style preference.  You can, of course, put it back outside if you wish.


text:
Q: Electrical energy and power Two resistance 2 ohm and 6 ohm are connected in parallel and the combination is then connected to a source of EMF 12V.how much power is consumed in each resistance?

A: Call the two resistors $R_1$ and $R_2$. Since they are connected in parallel, we have that the voltages over both resistors are the same (12V in this case).
The power generated is defined as:
$P = U * I$
By Ohm's law we have:
$I = \frac{U}{R}$
Plugging this result in the first formula:
$ P = \frac{U^2}{R}$
Using this formula you can calculate the power consumption per resistor.


text:
Q: Issue with preloading assets to browser I have a Nodejs App running on background and I have this code in frontend ( here it's simplified for you ) to preload videos , audios , etc ... to blobs like this:
   function preloadOne(url, done) {
      const xhr = new XMLHttpRequest();
      xhrs.push(xhr);
      xhr.open('GET', url, true);
      xhr.responseType = 'blob';
      xhr.onprogress = event => {
        if (!event.lengthComputable) return false;
        let item = this.getItemByUrl(event.target.responseURL);
        item.completion = parseInt((event.loaded / event.total) * 100);
        item.downloaded = event.loaded;
        item.total = event.total;
        this.updateProgressBar(item);
      };
      xhr.onload = event => {
        let type = event.target.response.type;
        let blob = new Blob([event.target.response], {
          type: type
        });
        let url = URL.createObjectURL(blob);
        let responseURL = event.target.responseURL;
        let item = this.getItemByUrl(responseURL);
        item.blobUrl = url;
        item.fileName = responseURL.substring(responseURL.lastIndexOf('/') + 1);
        item.type = type;
        item.size = blob.size;
        done(item);
      };
      xhr.onerror = event => {}
      xhr.send();
    }

Everything is going fine until I reach 32mb transferred then the transfer gets really slow and for the next 10 mb to load I need more time than what I needed to reach 30MBs!!??
Sometimes and not all the times I get this error for loading a video too:

Failed to load resource: net::ERR_HTTP2_PROTOCOL_ERROR

Here you can see the end of the fast part of the preloading where suddenly everything gets slow:

Any suggestions why this is happening and how to fix this is a good point to start and debug this and it's really appreciated ...
For me it seems something get's full after 30 MBs :)
UPDATE: it a more complete version of the code to have a look if you need it:

async function Preloading() {

    preloadedPercent = 0;
    setTimeout(() => startBlink(), 1500);
    (function (global, factory) {
        typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() :
        typeof definer === 'function' && definer.amd ? definer(factory) :
        (global.Preload = factory());
    }(this, (function () {

    'use strict';

    function preloadOne(url, done) {
        const xhr = new XMLHttpRequest();
        xhr.open('GET', url, true);
        xhr.responseType = 'blob';
        xhr.onprogress = event => {
            if(!event.lengthComputable) return false
            let item = this.getItemByUrl(event.target.responseURL);
            item.completion = parseInt((event.loaded / event.total) * 100);
            item.downloaded = event.loaded;
            item.total = event.total;
            this.updateProgressBar(item);
        };
        xhr.onload = event => {
            let type = event.target.response.type;
            let blob = new Blob([event.target.response], { type: type });
            let url = URL.createObjectURL(blob);
            let responseURL = event.target.responseURL;
            let item = this.getItemByUrl(responseURL);
            item.blobUrl = url;
            item.fileName = responseURL.substring(responseURL.lastIndexOf('/') + 1);
            item.type = type;
            item.size = blob.size;
            done(item);
        };

        xhr.onerror = event => {
            console.log('Error Happend in Preloading');
            reload();
        };
        xhr.send();
    }

    function updateProgressBar(item) {
        var sumCompletion = 0;
        var maxCompletion = this.status.length * 100;
        for(var itemStatus of this.status) {
            if(itemStatus.completion) {
                sumCompletion += itemStatus.completion;
            }
        }
        var totalCompletion = parseInt((sumCompletion / maxCompletion) * 100);
        if(!isNaN(totalCompletion)) {
            this.onprogress({
                progress: totalCompletion,
                item: item
            });
        }
    }

    function getItemByUrl(rawUrl) {
        for (var item of this.status) {
            if (item.url == rawUrl) return item
        }
    }

    function fetch(list) {
        return new Promise((resolve, reject) => {
            this.loaded = list.length;
            for (let item of list) {
                this.status.push({ url: item });
                this.preloadOne(item, item => {
                    this.onfetched(item);
                    this.loaded--;
                    if (this.loaded == 0) {
                      this.oncomplete(this.status);
                      resolve(this.status);
                    }
                });
            }
        })
    }

    function Preload() {
        return {
            status: [],
            loaded: false,
            onprogress: () => {},
            oncomplete: () => {},
            onfetched: () => {},
            fetch,
            updateProgressBar,
            preloadOne,
            getItemByUrl
        }
    }

    return Preload;

    })));

    const preload = Preload();
    preload.fetch(preloadingData.preloadURLs).then(items => {});
    preload.oncomplete = items => {
        Media = generateMedia(items);
        Blobs = generateBlobs(items);
        sfx = getSfx();
        preloadProgress(100, true);
        preloadingData = null;
    }
    preload.onprogress = event => { preloadProgress(event.progress); }
    preload.onfetched = item => {}
}

function preloadProgress(value, done) {
    if(value > preloadedPercent || done) {
        preloadedPercent = value;
        checkRestart = 0;
        checkLatency(value);
        progressBar(value, done);
    }
}


text:
Q: Fail while replicating data from PouchDb to CouchDb My Code
thats is a short version of my current code.:
['tableA', 'tableB', 'tableC'].forEach(name => {
    let local = new PouchDB(name, { auto_compaction: true })
    let server = new PouchDB(serverUrl + name)

    var filtro = {
      include_docs: true,
      filter: 'replication/by_dispositivo',
      query_params: { 'dispositivo_id': obj.deviceId }
    }
    local.replicate.from(server, filtro).on('complete', report => {
      var sync = local.sync(server, {
        live: true,
        retry: true,
        ...filtro
      })
    })
})

I'm trying to do a live replication, but for some reason, that doesn't replicate the local data to the server, strangely, PouchDb didn't throw any exception.
Inspecting the Network tab on Dev Tools, I can see te follow request.:
URL: ${serverUrl}/{name}/_revs_diff
Response: {
    "4b0ea507-cd88-4998-baf0-01629b50516b": {
        "missing": [
            "2-2133d30de8d44ebd958cee2b68726ffb"
        ],
        "possible_ancestors": [
            "1-39904a7e55b1cb266c840a2acf34fdc2"
        ]
    }
}

Ok, PouchDb detected that something is missing in the server and must be replicated.
Auditing the Sync
Searching for a hint about what is happening, I modified my code to log the complete and error events.:
['tableA', 'tableB', 'tableC'].forEach(name => {
    let local = new PouchDB(name, { auto_compaction: true })
    let server = new PouchDB(serverUrl + name)

    let filtro = {
      include_docs: true,
      filter: 'replication/by_dispositivo',
      query_params: { 'dispositivo_id': obj.deviceId }
    }
    local.replicate.from(server, filtro).on('complete', report => {
      let sync = local.sync(server, {
        live: true,
        retry: true,
        ...filtro
      })
      sync.on('error', (error) => {
        console.error(error)
        console.error(JSON.stringify(error, null, 2))
      }).on('complete', (result) => {
        console.log(result)
        console.log(JSON.stringify(result, null, 2))
      })
      window.setTimeout(function (evt) {
        state.syncProcess[database].cancel()
      }, 15000)
    })
})

I didn't catch anything in the error event, and the complete event didn't show any errors as you can see bellow.
{
  "push": {
    "ok": true,
    "start_time": "2018-04-06T15:00:42.266Z",
    "docs_read": 0,
    "docs_written": 0,
    "doc_write_failures": 0,
    "errors": [],
    "status": "cancelled",
    "end_time": "2018-04-06T15:00:42.266Z",
    "last_seq": 0
  },
  "pull": {
    "ok": true,
    "start_time": "2018-04-06T15:00:26.422Z",
    "docs_read": 0,
    "docs_written": 0,
    "doc_write_failures": 0,
    "errors": [],
    "last_seq": "17-g1AAAAJDeJyd0EsOgjAQBuAqJj52nkCPILGldCU3UaYzBA3CQl3rTfQmehO9CRZKAiaGiJtpMs18mX8SxtgodpBNdXbSMUKQZDpM4uxwTMxXP2Qwy_N8Fzsh25vGMILIA62QjU8pUrRNCVvGYW4qrCphUgoCfMVd_W2mTQoKaV1JjpWWIUcuu0qbQjp_pBKeUESLH1OlA1PZxTwGudb7EC1dQt5xH6vdrHYvtF6pSZK-4Oov7WG1Z53QUy56UnRK-LJK406-TxIAm8ruDdzts44",
    "status": "cancelled",
    "end_time": "2018-04-06T15:00:41.427Z"
  }
}

Calling one time local to server replication manually
that is my second attempt to catch something usefull. I trying to audit the local.replicate.to method
['tableA', 'tableB', 'tableC'].forEach(name => {
    let local = new PouchDB(name, { auto_compaction: true })
    let server = new PouchDB(serverUrl + name)

    let filtro = {
      include_docs: true,
      filter: 'replication/by_dispositivo',
      query_params: { 'dispositivo_id': obj.deviceId }
    }
    local.replicate.from(server, filtro).on('complete', report => {
      local.replicate.to(server, filtro).on('complete', report => {
        console.log(report)
        console.log(JSON.stringify(report, null, 2))
        let sync = local.sync(server, {
          live: true,
          retry: true,
          ...filtro
        })
      }).on('error', (error) => {
        console.error(error)
        console.error(JSON.stringify(error, null, 2))
      })
    })
})

thats time complete event isn't fired and I catch a error, but that is too generic amd don't give any clues regarding whats is happening.
{
  "result": {
    "ok": false,
    "start_time": "2018-04-06T15:07:19.105Z",
    "docs_read": 1,
    "docs_written": 0,
    "doc_write_failures": 0,
    "errors": [],
    "status": "aborting",
    "end_time": "2018-04-06T15:07:19.768Z",
    "last_seq": 3
  }
}

Putting local data to the server
thats is my last attempt.:

*

*I'll query local and remote databases (in that particular case, I have only one document)

*Copy fields from local doc to remote doc.

*Dispatch the updated remote doc to the remote database

My Junk Code
var deviceId = ''
var listLocal = []
var listServer = []

getDeviceId().then(response => {
    deviceId = response
    return local.find({ selector: { dispositivo_id: deviceId } })
}).then(response => {
    listLocal = response.docs
    return server.find({ selector: { dispositivo_id: deviceId } })
}).then(response => {
    listServer = response.docs

    var tlocal = listLocal[0]
    var tServer = listServer[0]
    Object.keys(tServer).forEach(key => {
      if (key.indexOf("_") !== 0) {
        tServer[key] = undefined
      }
    })
    Object.keys(tlocal).forEach(key => {
      if (key.indexOf("_") !== 0) {
        tServer[key] = tlocal[key]
      }
    })

    return server.put(tServer).then(result => {
      console.log(result)
      console.log(JSON.stringify(result, null, 2))
    }).catch(error => {
      console.error(error)
      console.error(JSON.stringify(error, null, 2))
    })
})

The junk code worked as expected, and i received that response.:
{
  "ok": true,
  "id": "4b0ea507-cd88-4998-baf0-01629b50516b",
  "rev": "2-d9363f28e53fdc145610f5ad3f75a043"
}

Additional Information
My design documents in the CouchDb
_design/replication
{
  "_id": "_design/replication",
  "_rev": "1-42df919aaee8ed3fb309bbda999ba03d",
  "language": "javascript",
  "filters": {
    "by_dispositivo": "function(doc, req) {\r\n  return doc._id === '_design/replication' || (doc.dispositivo_id === req.query.dispositivo_id && !doc._deleted)\r\n}",
    "by_situacao_remote": "function(doc, req) {\r\n  return [2, 3, 4, 5].indexOf(doc.situacao) !== -1 && !doc._deleted\r\n}"
  }
}

_design/authorization
{
  "_id": "_design/authorization",
  "_rev": "9-64c4a22645d783c9089c95d69e9424ad",
  "language": "javascript",
  "validate_doc_update": "..."
}

authorization/validate_doc_update
function(newDoc, oldDoc, userCtx) {
  var isAdmin = userCtx.roles.indexOf('_admin') !== -1 || userCtx.roles.indexOf('admin') !== -1;
  if (!isAdmin) {
    if (newDoc._deleted) {
      if (oldDoc.dispositivo_id !== userCtx.name) {
        throw({forbidden: "..." });
      }
    }
    else {
      if (!newDoc.dispositivo_id || !newDoc.dispositivo_id.trim())
        throw({forbidden: "..." });
      if (newDoc.dispositivo_id !== userCtx.name) {
        throw({forbidden: "..." });
      }

      if (oldDoc && oldDoc.dispositivo_id !== userCtx.name) {
        throw({forbidden: "..." });
      }

      var isRequired = function (prop, msg) {
        var value = newDoc[prop];
        if (!value)
            throw({forbidden: '...' });
      }

      var isDate = function (prop, msg, allow_null) {
        if (!allow_null)
            isRequired(prop, msg)
        var value = newDoc[prop];
        if (value) {
            var date = new Date(value);
            var isDate = date !== "Invalid Date" && !isNaN(date);
            if (!isDate) {
              throw({forbidden: msg });
            }
        }
      }

      var isFloat = function (prop, msg, allow_null) {
        if (!allow_null)
            isRequired(prop, msg)
        var value = newDoc[prop];
        if (value) {
            var numero = new Number(value);
            if (!numero || isNaN(numero) || !isFinite(numero)) {
              throw({forbidden: msg });
            }
        }
      }

      var isInteger = function (prop, msg, allow_null) {
        isFloat(prop, msg, allow_null)
        var value = newDoc[prop];
        if (value) {
            var numero = new Number(value);
            var isInteger = Math.floor(numero) == numero;
            if (!isInteger) {
              throw({forbidden: msg });
            }
        }
      }

      isRequired("talao_id", "...");
      isRequired("equipe_id", "...");

      isInteger("situacao", '...');
      isDate("data_envio", "...");
      isDate("data_recebimento", "...", true);
      isDate("data_decisao", "...", true);

      isRequired("tipo_ocorrencia_codigo", "...");
      isRequired("tipo_ocorrencia_descricao", "...");
      isInteger("talao_codigo", "...");
      isRequired("talao_descricao", "...");
      isRequired("talao_solicitante", "...");
      isRequired("talao_endereco", "...");
    }
  }
  else if (!newDoc._deleted) {
    if (!newDoc.dispositivo_id || !newDoc.dispositivo_id.trim())
      throw({forbidden: "..." });
  }
}

A: While analyzing the stack trace of the exception throw by local.replicate.to, I noticied that reason: promise.all is not a function.
So i googled for a while and found that topic Webpack: Promise is not a constructor. I just need to copy the workaround bellow to my webpack.config and everything worked like a charm.:
resolve: {
  alias: {
    'pouchdb-promise$': "pouchdb-promise/lib/index.js"
  }
}


text:
Q: Trying to execute a set of functions in order I am a Python noob, and I'm trying to make a washing device, programming the interface with Python. For now, the machine should work like that:

*

*Wash

*Tell washing is complete

*Dry

*Tell drying is complete

For this, after times for washing/drying are entered, a button is pressed:
button1 = Button(window.tk, command = lambda:main_process(int(varWashtime.get()), int(varDrytime.get())))

def main_process(wash_seconds,dry_seconds):
        wash(wash_seconds)
        stop_wash()
        dry(dry_seconds)
        stop_dry()
        return

def wash(seconds):
    varWashStarted.set("Washing Started")
    Timer(seconds,idle_fnc).start()
    return

def stop_wash():
    varWashStarted.set("Washing Stopped")
    Timer(3,idle_fnc,()).start()
    return

def dry(seconds):
    varDryStarted.set("Drying Started")
    Timer(seconds,idle_fnc,()).start()
    return

def stop_dry():
    varDryStarted.set("Drying Stopped")
    return

def idle_fnc():
    pass
    return

Here, I used the function idle_fnc to make threading.Timer properly work.
I found out that I can just use Timer to call other functions after each other, but I would prefer to return from a function, then branch to a new one.
My problem is, as I click the button, the whole thing executes without waiting; I instantly see "Washing Stopped" and "Drying Stopped" on the corresponding label, without the delays triggered.
What is the problem?


text:
Q: C# crop, scale, rotate image I use a javascript client plugin for manipulate image inside the browser (JQuery Guillotine). After I will want manipulate the image with the server but I don't know which library can help me for do this job.
When I call the server I send these information:
{ scale: 1.4, angle: 270, x: 10, y: 20, w: 400, h: 300 }

A: I think there are several libraries available to do this, but I have a good experience with implementing this one: http://imageprocessor.org/.

A: I would recommend the AForge.net imaging library. I've used it before and found it easy to implement, reliable and quick. It does everything, but you may find that it's overkill for what you need.
I used it in a kinect project that needed to measure the distance between a person's pupils. After finding the eye with the kinect I used this library to cut out the image of the eye, then apply several filters (and some other imaging magic) to pinpoint the center of the each pupil. This was occurring at about 30fps and this image processor (on a fairly decent machine) kept up with the demand and didn't miss a beat.
Or, seeing as you're just resizing, cropping and rotating, you could just use the System.Drawing libraries already built in to .net
Here are a few examples to get you started: http://dotnet-snippets.com/snippet/crop-and-resize-images/676


text:
Q: document.activeElement.matches(:focus) is false. why is this? I have an li:
<li _ngcontent-c21="" class="accordion li" tabindex="0" aria-expanded="true">

Which I have tabbed to. document.activeElement is in fact this element. However,
document.activeElement.matches(':focus')
false

and to make matters even slightly more bizzare:
document.activeElement.focus()
undefined
document.activeElement.matches(':focus')
false

What is going on here? (this is chrome, btw)

A: If this is happening in the console, the console is in focus, not the element or indeed the page; therefore, elements cannot match :focus as long as the console is in focus. This is not a limitation of Element#matches(), but a side effect of how :focus works — :focus CSS style rules behave the same way.
If you either set a timeout in the console and refocus the page before the timeout expires, or call these functions in a <script> within the page, document.activeElement should match :focus as expected.


text:
Q: Magento Login model email id with retrieve gender value from collection I am new to magento. How to load customer collection to retrieve gender value by passing login email id?
Thanks.
Praksah

A: Afaik, Magento does not have explicit email id's for customers, only email addresses.
To retrieve the gender for a given email address you could use:
$oCustomer = Mage::getModel('customer/customer')
    ->setWebsiteId(1)
    ->loadByEmail('example@example.com');

var_dump($oCustomer->getGender());

The setWebsiteId(1) part is only neccessary when running with website scope.


text:
Q: Сериализация/Десериализация Dictionary Есть некий внешний сервис, отдающий такой объект:
{
    "timestamp": час
    "asks": масив ордерів на продаж
    [
        [ціна, об'єм]
    ],
    "bids": масив ордерів на покупку
    [
        [ціна, об'єм]
    ]
}

Я реализовал его и сериализую с помощью Newtonsoft пакета так:
public class Depth
    {
        [JsonProperty(PropertyName = "timestamp")]
        public int timestamp;

        [JsonProperty(PropertyName = "asks")]
        public Dictionary<string, string> asks;

        [JsonProperty(PropertyName = "bids")]
        public Dictionary<string, string> bids;
    }

и соответственно место где я получаю данный объект из http запроса и десеарилизую
var json = await response.Content.ReadAsStringAsync();
    var d = await Task.Factory.StartNew(() => JsonConvert.DeserializeObject<T>(json));

В итоге ошибка -->
"Cannot deserialize the current JSON array (e.g. [1,2,3]) into type 'System.Collections.Generic.Dictionary`2[System.String,System.String]' because the type requires a JSON object (e.g. {"name":"value"}) to deserialize correctly.
To fix this error either change the JSON to a JSON object (e.g. {"name":"value"}) or change the deserialized type to an array or a type that implements a collection interface (e.g. ICollection, IList) like List<T> that can be deserialized from a JSON array. JsonArrayAttribute can also be added to the type to force it to deserialize from a JSON array."

Возможно для Dictionary имеется какоето другое [сво-во] сериализации или же я неправильно десеарилизую?
Пробовал вмесо Dictionary в классе поля через List<KeyValuePair<string,string>> делать, но тогда значения KeyValuePair равны null.

A: Окей, допустим у нас есть json
string json = @"{
  ""timestamp"": 1530724151,
  ""asks"": [
    [""300943.0"", ""0.000299""],
    [""300850.0"", ""0.004703""],
    [""300500.0"", ""0.056""],
    [""300000.0"", ""0.593274""],
    [""299900.0"", ""0.0342""],
    [""299500.0"", ""0.003196""]
  ],
  ""bids"": [
    [""300943.0"", ""0.000299""],
    [""300850.0"", ""0.004703""],
    [""300500.0"", ""0.056""],
    [""300000.0"", ""0.593274""],
    [""299900.0"", ""0.0342""],
    [""299500.0"", ""0.003196""]
  ]
}";

И мы создали такие классы, которые нам очень нравятся
public class Depth
{
    public int timestamp;
    public MyPair[] asks;
    public MyPair[] bids;
}

public class MyPair
{
    public decimal Cost{get;set;}
    public decimal Volume{get;set;}
}

И теперь мы хотим сконвертировать наш json в наши классы. Но вот незадача - в jsone то поля выглядят как массив массивов, а нам надо массив наших объектов. Что тут можно сделать? А давайте напишем наш конвертер
private class MyAwesomeConverter : JsonConverter
{
    public override bool CanConvert(Type objectType)
    {
        return objectType == typeof(MyPair);
    }

    public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
    {
        JArray array = JArray.Load(reader);
        return new MyPair
        {
            Cost = array[0].Value<decimal>(),
            Volume= array[1].Value<decimal>()
        };
    }

    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
    {
        throw new NotImplementedException();
    }
}

Этот конвертер будет работать только когда надо будет распарсить конкретно наш класс MyPair, для остальных классов будет работать встроенный конвертер. Как теперь все собрать вместе? Вот так:
var depth = JsonConvert.DeserializeObject<Depth>(json, new MyAwesomeConverter());

Все, никаких спец объектов больше создавать не нужно.

A: Все довольно просто:
public class Depth
{
    [JsonProperty("timestamp")]
    public int Timestamp;

    [JsonProperty("asks")]
    public List<Quote> Asks;

    [JsonProperty("bids")]
    public List<Quote> Bids;
}

public class Quote : List<decimal>
{
    public decimal Price => Count > 0 ? this[0] : -1;
    public decimal Volume => Count > 1 ? this[1] : -1;
}


text:
Q: Confused by notation? Would someone be so kind as to explain what is happening with the statement below. I an a bit puzzeled by <MKAnnotation> between id and mp, it not something I have seen before.
id <MKAnnotation> mp = [annotationView annotation];

many thanks
gary

A: id <MKAnnotation> mp

means that mp object is expected to conform to MKAnnotation protocol (and I suppose assignments you make to that objects will be checked at compile time whenever possible).

A: It tells you that the object returned will meet the protocol MKAnnotation
see Apple's objective-C concepts


text:
Q: In Adobe Photoshop drop shadow angle shadow I have problem with drop shadow for specific layer with angle shadow if I changed for one layer it's change for all layersenter image description here!! why??

A: You either have all the layers selected or have "Auto Select" checked. Or one of the layers is nested in another layer forming a group.

A: Make sure only 1 layer is selected. Try making a new layer and applying it.

A: i suggest you to to this :

*

*select which Layer you want to work on

*right click on the Layer

*click on Blending Option

*choose Drop Shadow from menu

A: Sounds like you have global light selected.
If you change the shadow effects on an element with global light selected, ALL other images with global light checked, regardless of what layer they are on, will change also.
If you want to change the shadow of a single object, be sure global light is not selected.


text:
Q: FOSElasticaBundle: prioritizing followers in user search I've got symfony2 project set up with elastica via FOSElasticaBundle.
I've got indexing set up for User document(Mongo) using basic settings.
Now when I do a search for users I'd like that search to be prioritized by specified user's followers (to be returned of the top of search).
The followers are stored in separate document (structure: id, follower_id, folowee_id).
What would be the best approach to do so?

A: Ok, so after research it seems that only way is to first make a find on follow document, then eventually merge results with find on user.
First added indexing on follow entity like:
    follow:
                mappings:
                     follower: ~
                     followee :
                         type : object
                         properties :
                             id : ~

Now I can easily make a search with followee id and followers text string (prefix):
    $baseQuery = new \Elastica\Query\Prefix();
    $baseQuery->setPrefix('follower', $text);

    $filter = new \Elastica\Filter\Term();
    $filter->setTerm('id', $id);
    $subquery = new \Elastica\Query\Filtered($baseQuery, $filter);

    $query = new \Elastica\Query();
    $query->setSize(10);
    $query->setQuery($subquery);

    $results =  $service->find($query);


text:
Q: cannot assign value to object flutter I want to assign values to an object "clientModel" but he always returning null

  ClientModel? clientModel ;
Future<void> getClientData(String email) async {
    emit(FidelityLoadingClientDataState());
        DioHelper.postData(url: GET_CLIENT,
            data: {
              "email":email
            }).then((value) {

              clientModel = ClientModel(status: true, message: "hello from the other side");

              emit(FidelityClientLoadingDataSuccess(clientModel));

        }).catchError((error)async{
          print(error.toString());

          emit(FidelityClientLoadingDataError(error.toString()));

        });
  }

}

even if assign manually value like this to the object :
clientModel = ClientModel(status: true, message: "hello from the other side");

the object return null
class Model :
class ClientModel {
  bool? status ;
  String? message ;
  ClientData? data;

  ClientModel({ this.status, this.message, this.data});

  factory ClientModel.fromJson(Map<String, dynamic> json) {
    return ClientModel(
      status: json['status'] ,
      message: json['message'] ,
      data: ClientData.fromJson(json['data']) ,
    );
  }

}

even i'm calling the method getClientData () in the start of the app but and I'm getting suucess state : 'FidelityClientLoadingDataSuccess' but the value of the object client model it's always null


text:
Q: Get All Anchor Tags Good day!
My regular expression is really bad and I would like to ask for help on my project.
I have contents that I crawled from other sites and I would like to get all anchor tags that have this string in them.
target="_blank"

How will I accomplish this? Any suggestion would be greatly appreciated.
Thanks

A: As mentioned in the comments, regular expressions are not the answer here.
Use DOM and XPath to achieve what you want
$doc = new DOMDocument;
$doc->loadHTMLFile('http://www.example.com/some-file.html');

$xpath = new DOMXPath($doc);
$anchors = $xpath->query('//a[@target="_blank"]');

A:

$dom = new DOMDocument();
$dom->loadHtml($yourCobtent);

$xpath = new DOMXpath($dom);
$yourAnchors = $xpath->query('//a[@target="_blank"]');

A: agree with @quentin, however you can use regexr, (http://gskinner.com/RegExr/), a basic regex for all anchor tags is <a.*href=["'](?<url>[^"]+[.\s]*)["'].*>(?<name>[^<]+[.\s]*)</a>
(http://weblogs.asp.net/palermo4/archive/2004/06/18/regex-pattern-for-anchor-tags-part-2.aspx)


text:
Q: Column selection is set by default in VSCode When selecting text in vscode [os x] it uses column selection, i need to press option while selecting to switch to line selection, how do i reverse this?

A: I just hit this problem myself. For some reason, the following setting had been turned on:
{
    "editor.columnSelection": false
}

There's a key binding called editor.action.toggleColumnSelection that toggles it. Accidentally pressing that could have caused this issue.


text:
Q: Como actualizo mi lista al eliminar un elemento de la lista Estoy intentando hacer un crud en flutter con una base de datos en MYSQL y llevo gran parte de este de la interfaz y funcionalidad hecha lo único que me falta hacer hacer es  que se actaulize la lista cada vez que se ejecute una acción ya sea agregar, editar o eliminar en este caso va ser la acción de eliminar. La unica manera en que se actualiza la lista es si cambio de pantalla  y regreso cada vez despues de realizar una accion para que se actualice.
class UserAddress extends StatefulWidget {
  final int userId;
  UserAddress({Key key, this.userId}) : super(key: key);

  @override
  _UserAddressState createState() => _UserAddressState();
}

class _UserAddressState extends State<UserAddress> {
  Future<List<Address>> userAddress;
  @override
  void initState() {
    super.initState();
    userAddress = fetchAddressData();
  }
  Future<List<Address>> fetchAddressData() async {
    List<Address> address = await fetchAddress(http.Client(),widget.userId);
    return address;
  }
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: SafeArea(
        child: Column(
          children: <Widget>[
            Expanded(
              child: SizedBox(
                  child: addressListView(userAddress)
              ),),],),),);}}

Widget addressListView(userAddress){
  return FutureBuilder<List<Address>>(
      future:userAddress,
      builder: (context, snapshot) {
        if (snapshot.hasError) print(snapshot.error);
        return snapshot.hasData
          ? AddressList(address: snapshot.data,)
          : Center(child: CircularProgressIndicator());
      },
  );
}

class AddressList extends StatefulWidget {
  final List<Address> address;
  final Address addressData;
  AddressList({Key key, this.address, this.addressData,}) : super(key: key);
  @override
  _AddressListState createState() => _AddressListState();
}

class _AddressListState extends State<AddressList> {
  @override
  Widget build(BuildContext context) {
    return ListView.builder(
      itemCount: widget.address.length,
      itemBuilder: (BuildContext context, int index) {
      return Container(
        child: Row(
          children: <Widget>[
             TextData(data: '${widget.address[index].calle}', fontWeight: FontWeight.w400, fontSize: 17,),
            IconButton(icon: Icon(Icons.delete), onPressed: ()=>deleteAddress (widget.address[index].idDireccion)),
          ],
        )
      );},);}}

Future deleteAddress(addressId) async{
  await http.post(
    serverUrl,
    headers: <String, String>{
    'Content-Type': 'application/json; charset=UTF-8',
    },
    body: jsonEncode(<String,String>{
      'idDireccion': addressId.toString(),
      'opcion': 'eliminar'
    }),
  );
}


text:
Q: Sorting a ReactTable based on a Switch being active I need to sort a react table with the rows where a Switch is checked appearing at the top.

Here is the code I have so far.

import React from 'react';
import ReactTable from 'react-table';
import { useDispatch } from 'react-redux';
import { Switch } from '@material-ui/core';

import * as Actions from 'app/routes/actions/store/actions';
import { Pagination, FilterCaseInsensitive } from 'app/library';

export const PromotionControl = (props) => {

    const dispatch = useDispatch();

    const model = props.model;
    const setModel = props.setModel;
    const pageState = props.pageState;
    const promotions = props.promotions;

    function hasPromotion(promotion) {
        if (model.actionPromotions === undefined)
            return false;

        const exists = model.actionPromotions.find(t => t.clientPromotionId === promotion.clientPromotionId);
        return exists !== undefined;
    }

    function handlePromotionSelection(promotion) {
        let selectedPromotions;

        if (hasPromotion(promotion)) {
            selectedPromotions = model.actionPromotions.filter(t =>
                t.clientPromotionId !== promotion.clientPromotionId
            );
        }
        else {
            selectedPromotions = [...model.actionPromotions, {
                clientPromotionId: promotion.clientPromotionId,
                promotionName: promotion.promotionName
            }];
        }
        setModel(values => ({ ...values, actionPromotions: selectedPromotions }));
    }

    return props.promotions.length <= 0 ? (
No promotions configured.
) : (
        <React.Fragment>
            <ReactTable
                data={promotions}
                PaginationComponent={Pagination}
                defaultPageSize={5}
                className="-striped -highlight"
                minRows={0}
                filterable={pageState.filterable}
                sortable
                filtered={pageState.filtered}
                defaultFilterMethod={FilterCaseInsensitive}
                onFilteredChange={(filtered) => dispatch(Actions.filterPromotions(filtered))}
                columns={[
                    {
                        Header: "Client Promotion ID",
                        accessor: 'clientPromotionId',
                        width:200
                    },
                    {
                        Header: "Type",
                        accessor: 'promotionType',
                        maxWidth: 300
                    },
                    {
                        Header: "Name",
                        accessor: "promotionName"
                    },
                    {
                        maxWidth: 70,
                        style: { justifyContent: 'center' },
                        Cell: item => {
                            return (
                                <Switch
                                     checked={hasPromotion(item.original)}
                                     onClick={() => handlePromotionSelection(item.original)}
                                />
                            )
                        }
                    }
                ]}
            />
        </React.Fragment>
    );
};

The column I want to sort the table by is the last column. At the moment the switch is checked based on the result of a check performed by the hasPromotion function. The issue is I don't know how to sort the whole table based on this column with the checked ones appearing at the top of the table.
Any ideas would be greatly appreciated.

A: As in Javascript, we have :
true - false === 1
false - true === -1

You could just base your sort on these values :
yourDataMatrix = yourDataMatrix.sort((a,b) => b.values[indexOfColumnToSort] - a.values[indexOfColumnToSort]);

Since I don't know the structure of your data, this code is not working, but you can use the logic in your code


text:
Q: viewModelProvider owner advice? To me, the information about ViewModelProvider lack some details and as usual I'm turning to StackOverflow to straighten the question marks.
In particular, I have one activity consisting of a couple of fragments, all of which are presenting the same data in different ways. What are the benefits and drawbacks with using the activity as the owner when instantiating the ViewModelProvider, vs using the fragments?
myViewModel = ViewModelProvider(owner).get(MyViewModel::class.java)

A: First, the ViewModel class is lifecycle aware. this means the ViewModel class you defined is going to be managed according to the lifecycle of the activity/fragment.
Same like Observers, it takes lifecycleOwner as a parameter. This means the observer will be alive all the time the fragment/activity is alive. If it entered OnStop, you don't have to stop observing manually, as its lifecyleOwner is the activity/fragment.
Secondly, For the difference between using activity as a lifecycleOwner over fragment, is the ViewModel instance will keep-alive more than defining it inside the fragment. As Activity holds the fragments. One fragment could enter onDetach(), so we guarantee that the instance of this ViewModel inside the fragment is killed. But if we define it within an activity, the life of activity is more longer.
Thirdly, I think since your case is the same data, and just the view changes in fragments, I suggest to use SharedViewModel, check this article for more details.
Hope all things are clear.
Happy coding


text:
Q: XAML parsing/layout rendering time very high I've got the problem, that I create an App, that will run on Windows Phone 8.1 and Windows 10 Mobile. This App is a non-UWP Windows Store App.
The problem I have is, that I have a list of a custom control that one has another List, that is not expanded (=collapsed). That looks like this:

The red rectangles are the ContentPresenter items of the first ItemControl and the green rectangles are the ContentPresenter items of the ItemControl in the first lists items, that is not visible on startup. It will be visible after the click on the expand-button. Both ItemControls have a DataTemplate configured to present what you see in the screenshot. (XAML code below)
The main problem I have is, that if I change the Pivot to the Pivot you see at the screenshot above, there is a freeze of the app for several seconds. It depends on the device how long this freeze is. In the W10M-Emulator on my PC I don't recognize a freeze but on a Lumia 620 with WP8.1 I have a freeze of 8.5 seconds.
In the profiler of Visual Studio it looks like this (I selected the range that is the problem I am talking about):

What I am wondering about is the large orange line with "Layout". If I expand it to the "big players", there is 60-70ms for each not visible item in the profiler.

I am asking myself why this is the case, even if the items are not visible and are in the VirtualizingStackPanel. The Number of Items of the ItemSourcein this example is 3 for the first ItemControl (red boxes) and 17, 59 and 1 for the second ItemControls that are only visible of the first item is expanded.
What I am also wondering about is, that regarding the timeline, all of the Items are processed at the same time because their baseline is for all items the same. But if I scroll down the profiler timeline details, I see another Event called "Parsing" for each item. That one is not processed in parallel for each item but serial. And the parsing of the last item fits to the end of the layout-event. This parsing events look like this:
What is the reason why the parsing takes so long time? I don't think that the controls are very complex etc. and there are no code behind procedures except some string formattings.
Finally here is the XAML code:
My PivotItem on the "MainPage" of the App:
<PivotItem
    Header="Echtzeit"
    Margin="10,-20,10,0"
    >
    <Grid>
        <ScrollViewer
            VerticalScrollBarVisibility="Visible"
            >
            <ItemsControl
                ItemsSource="{Binding RealtimeDepartures, UpdateSourceTrigger=PropertyChanged, Mode=OneWay}"
                HorizontalAlignment="Stretch"
                Margin="0"
                >
                <ItemsControl.ItemsPanel>
                    <ItemsPanelTemplate>
                        <VirtualizingStackPanel />
                    </ItemsPanelTemplate>
                </ItemsControl.ItemsPanel>
                <ItemsControl.ItemTemplate>
                    <DataTemplate>
                        <controls:RealtimeStation
                                StationName="{Binding StationName, UpdateSourceTrigger=PropertyChanged, Mode=OneWay}"
                                Departures="{Binding DepartureList, UpdateSourceTrigger=PropertyChanged, Mode=OneWay}"
                                FontSize="{Binding DataContext.ClientFontSize, ElementName=MainPg, UpdateSourceTrigger=PropertyChanged, Mode=OneWay}"
                                />
                    </DataTemplate>
                </ItemsControl.ItemTemplate>
            </ItemsControl>
        </ScrollViewer>
    </Grid>
</PivotItem>

The RealtimeStation Control XAML:
<UserControl
    ...
    >

    <UserControl.Resources>
        <dec:BoolToVisibilityConverter x:Key="BoolToVisibilityConv"/>
    </UserControl.Resources>

    <Grid>
        <AppBarButton
            HorizontalAlignment="Left"
            VerticalAlignment="Top"
            Grid.Column="0"
            Name="btnExpand"
            Icon="{Binding ExpandButtonIcon, ElementName=main, UpdateSourceTrigger=PropertyChanged, Mode=OneWay}"
            Click="btnExpand_Click"
            IsEnabled="{Binding IsExpandButtonEnabled, ElementName=main, UpdateSourceTrigger=PropertyChanged, Mode=OneWay}"
            IsCompact="True"
            Margin="0,-8,-2,-4"
            />

        <StackPanel
            Orientation="Vertical"
            Margin="48,12,0,0"
            >
            <TextBlock
                Text="{Binding StationName, ElementName=main, UpdateSourceTrigger=PropertyChanged, Mode=OneWay}"
                VerticalAlignment="Center"
                FontSize="24"
                />

            <TextBlock
                Text="Derzeit stehen keine Abfahrten an"
                FontStyle="Italic"
                Visibility="{Binding ShowNoDepartures, ElementName=main, UpdateSourceTrigger=PropertyChanged, Mode=OneWay}"
                FontSize="{Binding FontSize, ElementName=main, UpdateSourceTrigger=PropertyChanged, Mode=OneWay}"
                />

            <TextBlock
                Text="Zugausfälle vorhanden!"
                Foreground="Red"
                FontWeight="Bold"
                Visibility="{Binding ShowTrainCanceled, ElementName=main, UpdateSourceTrigger=PropertyChanged, Mode=OneWay}"
                FontSize="{Binding FontSize, ElementName=main, UpdateSourceTrigger=PropertyChanged, Mode=OneWay}"
                />

            <ItemsControl
                ItemsSource="{Binding DepartureList, UpdateSourceTrigger=PropertyChanged, Mode=OneWay}"
                ScrollViewer.VerticalScrollBarVisibility="Visible"
                ScrollViewer.HorizontalScrollBarVisibility="Disabled"
                Margin="-48,0,0,0"
                Visibility="{Binding IsExpanded, ElementName=main, UpdateSourceTrigger=PropertyChanged, Mode=OneWay, Converter={StaticResource BoolToVisibilityConv}}"
                >
                <ItemsControl.ItemsPanel>
                    <ItemsPanelTemplate>
                        <VirtualizingStackPanel />
                    </ItemsPanelTemplate>
                </ItemsControl.ItemsPanel>
                <ItemsControl.ItemTemplate>
                    <DataTemplate>
                        <ContentPresenter>
                            <controls:RealtimeDeparture
                                DepartureDetails="{Binding}"
                                FontSize="{Binding FontSize, ElementName=main, UpdateSourceTrigger=PropertyChanged, Mode=OneWay}"
                                />
                        </ContentPresenter>
                    </DataTemplate>
                </ItemsControl.ItemTemplate>
            </ItemsControl>
        </StackPanel>
    </Grid>
</UserControl>

And finally the RealtimeDeparture Control:
<UserControl
    ...
    >
    <Grid>
        <control:DisruptionIcon
            Height="24"
            Width="50"
            HorizontalAlignment="Left"
            VerticalAlignment="Top"
            Icon="{Binding TrainIcon, UpdateSourceTrigger=PropertyChanged, Mode=OneWay}"
            Margin="3"
            />

        <StackPanel
            Orientation="Vertical"
            Margin="56,9,0,0"
            >
            <StackPanel
                Orientation="Horizontal"
                Margin="3,0"
                VerticalAlignment="Center"
                >

                <TextBlock
                    Text="{Binding DelayTimeText, ElementName=main, Mode=OneWay, UpdateSourceTrigger=PropertyChanged}"
                    Foreground="{Binding DelayColor, ElementName=main, Mode=OneWay, UpdateSourceTrigger=PropertyChanged}"
                    />
                <TextBlock
                    Text="{Binding DepartureDetailsText, ElementName=main, Mode=OneWay, UpdateSourceTrigger=PropertyChanged}"
                    Margin="3,0"
                    />
            </StackPanel>

            <TextBlock
                Text="{Binding InformationText, UpdateSourceTrigger=PropertyChanged, Mode=OneWay, ElementName=main}"
                Visibility="{Binding IsInformationVisible, UpdateSourceTrigger=PropertyChanged, Mode=OneWay, ElementName=main}"
                Margin="3"
                FontStyle="Italic"
                TextWrapping="Wrap"
                />
            <TextBlock
                Text="Zug fällt aus!"
                Foreground="Red"
                FontWeight="Bold"
                Visibility="{Binding IsCanceledVisible, UpdateSourceTrigger=PropertyChanged, Mode=OneWay, ElementName=main}"
                Margin="3"
                />
        </StackPanel>
    </Grid>
</UserControl>

Does anybody has an idea how to speed up this parsing? What is the reason why it is so slow? Do I have a design issue that is disabling the virtualization-functionality of the VirtualizedStackPanel? I already tried a lot but didn't find the reason why it is so slow.

A: I don't think virtualization is turned on.
Try setting the CanContentScroll property to true on your ScrollViewer:
<ScrollViewer
    CanContentScroll="true"
    VerticalScrollBarVisibility="Visible"
>

The other option can be using e.g. ListBox which supports virtualization on its own (as far as I know it is enough to set the ItemsPanelTemplate to VirtualizingStackPanel)


text:
Q: SQLCMD fails if -c; is specified in parameters on SQL Server 2019 The following sqlcmd fails with no error and no output, just returns silently.
SQLCMD -U dbuser -d dbname -w 255 -h-1 -P mypassword -S dbserver -Q "ALTER TABLE xyz ADD abcd NUMERIC(1)" -c;
While it works fine without the -c; argument
SQLCMD -U dbuser -d dbname -w 255 -h-1 -P mypassword -S dbserver -Q "ALTER TABLE xyz ADD abcd NUMERIC(1)"
This parameter has been there since before 2005, with OSQL, then recently (less than a year ago) we replaced OSQL with SQLCMD.
And now we have discovered that one of our install scripts is not executing and it has come down to this -c; argument.
Also, I am testing on SQL Server 2019. I asked someone to execute the same scripts on a SQL Server 2008 and there the SQLCMD is working with the -c; parameter.
I have even tried specifying : and a few other characters instead of ; to no avail.
How should this parameter be used? And if it is not recommended or not supported to use it any more, then please point to any documentation/bug report/release notes.

A: The sqlcmd Utility doc says:

-c batch_terminator Specifies the batch terminator. By default, commands are terminated and sent to SQL Server by typing the word "GO"
on a line by itself. When you reset the batch terminator, do not use
Transact-SQL reserved keywords or characters that have special meaning
to the operating system, even if they are preceded by a backslash. [emphasis mine]

And if you see the Transact-SQL Syntax Conventions (Transact-SQL) doc, you'll find that:

;        Transact-SQL statement terminator. Although the semicolon isn't
required for most statements in this version of SQL Server, it will be
required in a future version.

That info added to what Stewart Gordon pointed on Why should I use a semicolon in SQL?:

The ANSI/ISO standards for SQL require statements to be separated by
semicolons. As such, the majority of SQL implementations will require
them. I think Microsoft SQL Server 2012 and earlier is one of the few
that deviates from this standard.

From that I'd say the semicolon is now a reserved keyword, although it's not required yet on T-SQL.

How to show the error message

Error Reporting Options
-b Specifies that sqlcmd exits and returns a DOS ERRORLEVEL value when an error occurs. The value that is returned to the DOS ERRORLEVEL
variable is 1 when the SQL Server error message has a severity level
greater than 10; otherwise, the value returned is 0. If the -V option
has been set in addition to -b, sqlcmd will not report an error if the
severity level is lower than the values set using -V. Command
prompt batch files can test the value of ERRORLEVEL and handle the
error appropriately. sqlcmd does not report errors for severity
level 10 (informational messages).
If the sqlcmd script contains an incorrect comment, syntax error, or
is missing a scripting variable, ERRORLEVEL returned is 1.
-m error_level Controls which error messages are sent to stdout. Messages that have a severity level greater than or equal to this level are sent. When this value is set to -1, all messages
including informational messages, are sent. Spaces are not allowed
between the -m and -1. For example, -m-1 is valid, and
-m -1 is not.
This option also sets the sqlcmd scripting variable SQLCMDERRORLEVEL.
This variable has a default of 0.

A: When you look at the help from sqlcmd /?, the -c switch is listed as [-c cmdend], which isn't helpful.
However, if you look at the docs, there is a much more helpful description:

-c batch_terminator -
Specifies the batch terminator. By default, commands are terminated and sent to SQL Server by typing the word "GO" on a line by itself. When you reset the batch terminator, do not use Transact-SQL reserved keywords or characters that have special meaning to the operating system, even if they are preceded by a backslash.

By passing -c; you're telling sqlcmd to send everything between ;s to the server to execute it as separate batches. Since ; is the (optional) statement terminator for SQL (and assuming that every statement does use the statement terminator), you're basically telling sqlcmd to send every statement as a separate batch, similar to having a GO after every statement.
Personally, I find code that uses non-standard batch terminators to be confusing. If you need every statement to be sent as a separate batch, insert GOs between them, and do not use the -c switch. That way, it will work with all the defaults in SSMS, sqlcmd, and other client tools.


text:
Q: Cypher dynamic relationship with conditional APOC procedure? I am learning cypher and trying to find out a way to create dynamic relationship when a condition passes.
Here is an example:
we have single node:
(n2)
and another node which has unknown relationship of TEMP_1 or TEMP_2 with its child:
(n1)------[TEMP_1 or TEMP_2]------>(child)
we want to create relationship between (n2) and (child) if it exists
(n2)------[TEMP_1 or TEMP_2]------>(child)
Here is query:
MATCH (n1: NODE_1)
MATCH (n2: NODE_2)
OPTIONAL MATCH (n1)-[rel:TEMP_1|TEMP_2]->(child)
CALL apoc.do.when(child IS NOT NULL, "CREATE (n2)-[:r]->(ch) RETURN TRUE", "", {n2:n2, r:type(rel), ch:child}) YIELD value

However this creates me relationship of type "r" instead of taking type from rel so it looks like following:
(n2)-[r]->(child)
Is there a way to create dynamic relationship on specific condition?
I have another idea but that would require carry on with query execution even if MATCH returns nothing.
MATCH (n1: NODE_1)
MATCH (n2: NODE_2)
MATCH (n1)-[rel:TEMP_1|TEMP_2]->(child)
CALL apoc.do.when(child IS NOT NULL, "CREATE (n2)-[:r]->(ch) RETURN TRUE", "", {n2:n2, r:type(rel), ch:child}) YIELD value
...[other parts of query e.g. MATCH | CREATE ...]

There is no OPTIONAL MATCH this time and when child IS NULL it returns and does not bother calling APOC procedure. However I would like to carry on with other part of the query e.g. create other relationships. Is there a way to accomplish something like that?

A: The apoc.create.relationship function can create a relationship with a dynamic type.
Also, you need to use the "$" prefix when referencing a parameter.
For example:
OPTIONAL MATCH (n1: NODE_1)-[rel:TEMP_1|TEMP_2]->(child)
CALL apoc.do.when(
  child IS NOT NULL,
  "MATCH (n2: NODE_2) CALL apoc.create.relationship(n2, $r, $ch) YIELD rel RETURN rel",
  "",
  {r:type(rel), ch:child}) YIELD value
...

This snippet only gets n2 as needed, which assumes that you do not need n2 later in the query.


text:
Q: Finding the maximum value of a function found from a differential equation I solved a differential equation and got the function $Q=\frac{t}{2}e^{-\frac{t}{20}}$. I am being asked to then find the point in which the value is at its maximum. One solution approach I can think of is taking the derivative of this function and finding where it is equal to zero, and then plugging those values to see which is the largest.
I am curious if there is a better approach to this problem, while the derivative is rather trivial to find, it seems like a better approach might exist.