问:
EXCEL VBA - count using dictionary and array
the following code is trying to combine the values in column G and S and then count how many times each value appears.

However when I run this code, the number returns is always the last row number, which I believe it feels all the values are the same. How can I fix this?

This is just the core part of the whole code, so some variables might be defined in the earlier lines.

```<code>Worksheets("Raw Data").Range("BL2:BL" & lastrow).Formula = "=G2&""_""&S2"
Const CB_COL As Long = 64

Dim d2 As Dictionary

Set d2 = New Dictionary

    For i = 2 To lr
        If Not d2.Exists(arr(i, CB_COL)) Then
        d2.Add arr(i, CB_COL), 1
        Else
        d2(arr(i, CB_COL)) = d2(arr(i, CB_COL)) + 1
        End If
    Next

    For i = 2 To lr
        arr(i, CB_COL + 1) = d2(arr(i, CB_COL))
    Next

    With Worksheets("Raw Data")
        .Range(.Cells(1, 1), .Cells(lr, CB_COL + 1)) = arr
    End With
</code>```

答:
Actually I found where the problem was myself...
I should have combined that two columns earlier, before the array was defined... otherwise this column in the array is actually totally blank.</p>

Body:
the following code is trying to combine the values in column G and S and then count how many times each value appears.

However when I run this code, the number returns is always the last row number, which I believe it feels all the values are the same. How can I fix this?

This is just the core part of the whole code, so some variables might be defined in the earlier lines.

Worksheets("Raw Data").Range("BL2:BL" & lastrow).Formula = "=G2&""_""&S2"
Const CB_COL As Long = 64

Dim d2 As Dictionary

Set d2 = New Dictionary

    For i = 2 To lr
        If Not d2.Exists(arr(i, CB_COL)) Then
        d2.Add arr(i, CB_COL), 1
        Else
        d2(arr(i, CB_COL)) = d2(arr(i, CB_COL)) + 1
        End If
    Next

    For i = 2 To lr
        arr(i, CB_COL + 1) = d2(arr(i, CB_COL))
    Next

    With Worksheets("Raw Data")
        .Range(.Cells(1, 1), .Cells(lr, CB_COL + 1)) = arr
    End With


来源: stackexchange

问:
Squid proxy gives 501 on GET request made by python but not curl
So I have a program to download webpages using bare sockets. I have to use bare sockets and can't use anything like requests or urllib etc. I'm on a network behind a Squid proxy, so my python program simply connect's to the proxy server and makes GET requests for the objects which I fetch from a HAR file. I tested the request using curl like

```<code>curl https://apis.google.com/_/scs/abc-static/_/js/k=gapi.gapi.en.wgbKiK972Ko.O/m=gapi_iframes,googleapis_client,plusone/rt=j/sv=1/d=1/ed=1/rs=AItRSTOlX0YCaQmKijyj5lpKQ5AVm7UE6A/cb=gapi.loaded_0 -o out_file
</code>```

and I get the output as the proper entire file. I inspected the header for the response and they are

```<code>HTTP/1.1 200 OK
Vary: Accept-Encoding
Content-Type: text/javascript; charset=UTF-8
Last-Modified: Thu, 11 Dec 2014 20:44:59 GMT
Date: Fri, 12 Dec 2014 03:38:46 GMT
Expires: Sat, 12 Dec 2015 03:38:46 GMT
X-Content-Type-Options: nosniff
Server: sffe
X-XSS-Protection: 1; mode=block
Cache-Control: public, max-age=31536000
Age: 1065247
Alternate-Protocol: 443:quic,p=0.02
Transfer-Encoding: chunked
</code>```

Now I tried to do the same thing using socket programming in python:

```<code>    HOST = 'proxy.address.of.squid.proxy'
    PORT = 3128
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    s.connect((HOST, PORT))
    url = 'https://apis.google.com/_/scs/abc-static/_/js/k=gapi.gapi.en.wgbKiK972Ko.O/m=gapi_iframes,googleapis_client,plusone/rt=j/sv=1/d=1/ed=1/rs=AItRSTOlX0YCaQmKijyj5lpKQ5AVm7UE6A/cb=gapi.loaded_0'
    httpVrsn = 'HTTP/1.1'
    domain = 'apis.google.com'
    objReq = 'GET '+url+' '+httpVrsn+'\r\nHost: '+domain+'\r\n\r\n';
    s.send(objReq);
    data = '';
    try:
        data = s.recv(1024);
        print data
    # other non-relevant stuff
</code>```

the output I get is

```<code>HTTP/1.0 501 Not Implemented
Server: squid/3.1.19
Mime-Version: 1.0
Date: Wed, 24 Dec 2014 10:25:42 GMT
Content-Type: text/html
Content-Length: 3576
X-Squid-Error: ERR_UNSUP_REQ 0
Vary: Accept-Language
Content-Language: en
X-Cache: MISS from localhost
X-Cache-Lookup: NONE from localhost:3128
Via: 1.0 localhost (squid/3.1.19)
Connection: close

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html><head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>ERROR: The requested URL could not be retrieved</title>
<style type="text/css"><!--
 /*
 Stylesheet for Squid Error pages
 Adapted from design by Free CSS Templates
 http://www.freecsstemplates.org
 Released for free under a Creative Commons Attribution 2.5 License
*/

/* Page basics */
* {
  font-family: verdana, sans-serif;
}

html body {
  margin: 0;
  padding: 0;
  background: #efefef;
  font-size: 12px;
  color: #1e1e1e;
}
</code>```

so I checked out this which explained that my Squid proxy 3.1 doesn't support Transfer-Encoding: chunked but it says that's the case for POST requests, I'm not sure if it holds for GET requests as well. I also checked out Unable to test HTTP PUT-based file upload via Squid Proxy. I'm not able to understand how is curl or even my browser able to fetch the content when requested on the same network behind the same proxy but through python I'm not able to fetch the response successfully?

So is there any way to get my python program to work without tweaking with the Squid Proxy, since I don't have control over the proxy.

答:
Curl uses the CONNECT method, which is a tunneling method. The proxy simply connects on the TCP level to the remote side and curl does all the communication including TLS handshake. All TCP/IP packets are just 'shoveled' back and forth by the proxy. But beware, silent intercepting (MITM) by the proxy is possible under certain coditions (e.g. when the admin/company puts his own CA cert into your cert pool).

What your python script does is asking the proxy to communicate with the remote side. Somehow your proxy isn't able to do the TLS connection (not configured or disabled during build, or simply not capable otherwise).

To configure Squid see http://wiki.squid-cache.org/Features/HTTPS

ContentLicense: CC BY-SA 3.0

Body:
So I have a program to download webpages using bare sockets. I have to use bare sockets and can't use anything like requests or urllib etc. I'm on a network behind a Squid proxy, so my python program simply connect's to the proxy server and makes GET requests for the objects which I fetch from a HAR file. I tested the request using curl like

curl https://apis.google.com/_/scs/abc-static/_/js/k=gapi.gapi.en.wgbKiK972Ko.O/m=gapi_iframes,googleapis_client,plusone/rt=j/sv=1/d=1/ed=1/rs=AItRSTOlX0YCaQmKijyj5lpKQ5AVm7UE6A/cb=gapi.loaded_0 -o out_file

and I get the output as the proper entire file. I inspected the header for the response and they are

HTTP/1.1 200 OK
Vary: Accept-Encoding
Content-Type: text/javascript; charset=UTF-8
Last-Modified: Thu, 11 Dec 2014 20:44:59 GMT
Date: Fri, 12 Dec 2014 03:38:46 GMT
Expires: Sat, 12 Dec 2015 03:38:46 GMT
X-Content-Type-Options: nosniff
Server: sffe
X-XSS-Protection: 1; mode=block
Cache-Control: public, max-age=31536000
Age: 1065247
Alternate-Protocol: 443:quic,p=0.02
Transfer-Encoding: chunked

Now I tried to do the same thing using socket programming in python:

    HOST = 'proxy.address.of.squid.proxy'
    PORT = 3128
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    s.connect((HOST, PORT))
    url = 'https://apis.google.com/_/scs/abc-static/_/js/k=gapi.gapi.en.wgbKiK972Ko.O/m=gapi_iframes,googleapis_client,plusone/rt=j/sv=1/d=1/ed=1/rs=AItRSTOlX0YCaQmKijyj5lpKQ5AVm7UE6A/cb=gapi.loaded_0'
    httpVrsn = 'HTTP/1.1'
    domain = 'apis.google.com'
    objReq = 'GET '+url+' '+httpVrsn+'\r\nHost: '+domain+'\r\n\r\n';
    s.send(objReq);
    data = '';
    try:
        data = s.recv(1024);
        print data
    # other non-relevant stuff

the output I get is

HTTP/1.0 501 Not Implemented
Server: squid/3.1.19
Mime-Version: 1.0
Date: Wed, 24 Dec 2014 10:25:42 GMT
Content-Type: text/html
Content-Length: 3576
X-Squid-Error: ERR_UNSUP_REQ 0
Vary: Accept-Language
Content-Language: en
X-Cache: MISS from localhost
X-Cache-Lookup: NONE from localhost:3128
Via: 1.0 localhost (squid/3.1.19)
Connection: close

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">

<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>ERROR: The requested URL could not be retrieved</title>


问:
IIS not redirecting to maped domain
I have set up IP on BigRock for domain redirection and done binding at IIS. Now when I am browsing my Url it is showing me default site of IIS instead of my hosted one.

Please help me to suggest possible cases.

答:
Here's how the IIS binding works

IIS binding has following IP:Port:Hostname

```<code><bindings>
  <binding protocol="http" bindingInformation=":8080:localhost" />
</bindings>
</code>```

Possibe cases

So if you have two websites with bindings e.g
Ipaddress1:80:www.example.com and Ipaddress1:80:www.example2.com ,then if the request reaches on Ipaddress1,then the first website will be served.IPAddress comes how you have configured your DNS entry is

You have two bindings but without the hostnames Ipaddress1:80: and Ipaddress2:80: ,then the request will be served if the IpAddress the request comes matches.So if the request comes on the second IpAddres,it will always be served by IIS no matter what the hostname is.

You can out a wildcard in the Ipaddress , *:80:www.example.com and *:80:www.example2.com .This means that IIS will listen for all the IPaddress.So iis will look at the hostname (HTTP Host header and serves the website which matches the hostheader.This will be sent with the request by the browser

A Host header field must be sent in all HTTP/1.1 request messages. A
  400 (Bad Request) status code will be sent to any HTTP/1.1 request
  message that lacks a Host header field or contains more than one.

getting your default website has possible causes

Your default website does not have a hostname configured and listens on IPAddress * and your actual website's IPAddress or hostname is not properly configured.So IIS serves the default website which has * IPaddress binding or no hostnames.

Hope it helps!

Title: IIS not redirecting to maped domain

Body:
Here's how the IIS binding works

IIS binding has following IP:Port:Hostname

<bindings>
  <binding protocol="http" bindingInformation=":8080:localhost" />
</bindings>

Possibe cases

So if you have two websites with bindings e.g
Ipaddress1:80:www.example.com and Ipaddress1:80:www.example2.com ,then if the request reaches on Ipaddress1,then the first website will be served.IPAddress comes how you have configured your DNS entry is

You have two bindings but without the hostnames Ipaddress1:80: and Ipaddress2:80: ,then the request will be served if the IpAddress the request comes matches.So if the request comes on the second IpAddres,it will always be served by IIS no matter what the hostname is.

You can out a wildcard in the Ipaddress , *:80:www.example.com and *:80:www.example2.com .This means that IIS will listen for all the IPaddress.So iis will look at the hostname (HTTP Host header and serves the website which matches the hostheader.This will be sent with the request by the browser

A Host header field must be sent in all HTTP/1.1 request messages. A
  400 (Bad Request) status code will be sent to any HTTP/1.1 request
  message that lacks a Host header field or contains more than one.

getting your default website has possible causes

Your default website does not have a hostname configured and listens on IPAddress * and your actual website's IPAddress or hostname is not properly configured.So IIS serves the default website which has * IPaddress binding or no hostnames.

Hope it helps!


问:
Monitor UITextField text changes within specified time
Listen to the text box, enter the contents of the case, there is content input within the 2S does not deal with, after the 2S no content input, exit the edit request interface</p>

答:
not writing your code here -- but giveng you a detailed instruction of how to use a NSTimer ;) [note that this is just one way but IMHO it is the easiest/most intuitive]

set yourself as delegate of textfield

wait for didBegin notification and set the timer for cancel Editing to 2s there!

if endEditing is called while timer is active, cancel it

if shouldChangeCharacters is called while timer is active, cancel it

if timer wasn't cancelled and fires. tell the textfield to endEditing


问:
Splash Screen is displaying too fast and then going into the next Java Class
The splash screen is supposed to last 3 seconds but it skipping it almost entirely when the app is run on Genymotion Emulator or Android Studios Emulator both emulators are running perfectly with other applications. I don't understand?

SplashScreen.java

package com.transcendencetech.juliospizzaprototype;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.view.Window;

/**
 * Created by Stormy Forrester on 20/03/2016.
 */
public class SplashScreen extends AppCompatActivity {

  /** Called when the activity is first created. */
  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    this.requestWindowFeature(Window.FEATURE_NO_TITLE);
    setContentView(R.layout.splash_screen);

    int secondsDelayed = 4;
    new Handler().postDelayed(new Runnable() {
      public void run() {
        startActivity(new Intent(SplashScreen.this,
          SignInActivity.class));
        finish();
      }
    }, secondsDelayed * 3);
  }
}```

**splash_screen,xml **

答:
Change your variable form

```<code> int secondsDelayed = 4;
</code>```

to

```<code> int secondsDelayed = 4000;
</code>```

Body:
The splash screen is supposed to last 3 seconds but it skipping it almost entirely when the app is run on Genymotion Emulator or Android Studios Emulator both emulators are running perfectly with other applications. I don't understand?

SplashScreen.java

package com.transcendencetech.juliospizzaprototype;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.view.Window;

/**
 * Created by Stormy Forrester on 20/03/2016.
 */
public class SplashScreen extends AppCompatActivity {

  /** Called when the activity is first created. */
  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    this.requestWindowFeature(Window.FEATURE_NO_TITLE);
    setContentView(R.layout.splash_screen);

    int secondsDelayed = 4;
    new Handler().postDelayed(new Runnable() {
      public void run() {
        startActivity(new Intent(SplashScreen.this,
          SignInActivity.class));
        finish();
      }
    }, secondsDelayed * 3);
  }
}

**splash_screen,xml **

Body:
Change your variable form

 int secondsDelayed = 4;

to

 int secondsDelayed = 4000;


问:
Multiple choice list with custom view?
I've seen example com.example.android.apis.view.List11 from ApiDemos. In that example, each row takes the view android.R.simple_list_item_multiple_choice. Each such view has a TextView and a CheckBox.

Now I want each view to have 2 TextViews and 1 CheckBox, somewhat similar to the List3 example. I tried creating a custom layout file row.xml like this:

```<code><?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >
    <CheckBox
        android:id="@+id/checkbox"
        android:layout_alignParentRight="true"
        android:layout_width="wrap_content"
        android:layout_height="fill_parent" />
    <TextView
        android:id="@+id/text_name"
        android:textSize="13px"
        android:textStyle="bold"
        android:layout_toLeftOf="@id/checkbox"
        android:layout_alignParentLeft="true"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content" />
    <TextView
        android:id="@+id/text_phone"
        android:textSize="9px"
        android:layout_toLeftOf="@id/checkbox"
        android:layout_below="@id/text_name"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content" />
</RelativeLayout>
</code>```

Then in Activity's onCreate(), I do like this:

```<code>public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    // Query the contacts
    mCursor = getContentResolver().query(Phones.CONTENT_URI, null, null, null, null);
    startManagingCursor(mCursor);

    ListAdapter adapter = new SimpleCursorAdapter(this,
            R.layout.row,
            mCursor,
            new String[] { Phones.NAME, Phones.NUMBER},
            new int[] { R.id.text_name, R.id.text_phone });
    setListAdapter(adapter);
    getListView().setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
}
</code>```

The result kind of looks like what I want, but it looks like the list doesn't know which item of it is selected. Also, I need to click exactly on the CheckBox. In the List11 example, I only need to click on the item row.

So what do I need to do to make a multiple choice list with my custom view for each row? Many thanks.

答: Got the solution ... You can get the clicks on the views (like checkboxes in custom layouts of row) by adding listener to each of them in the adapter itself while you return the converted view in getView(). You may possibly have to pass a reference of list object if you intent to get any list specific info. like row id.</p>

Title: Multiple choice list with custom view?

Body:
I've seen example com.example.android.apis.view.List11 from ApiDemos. In that example, each row takes the view android.R.simple_list_item_multiple_choice. Each such view has a TextView and a CheckBox.

Now I want each view to have 2 TextViews and 1 CheckBox, somewhat similar to the List3 example. I tried creating a custom layout file row.xml like this:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >
    <CheckBox
        android:id="@+id/checkbox"
        android:layout_alignParentRight="true"
        android:layout_width="wrap_content"
        android:layout_height="fill_parent" />
    <TextView
        android:id="@+id/text_name"
        android:textSize="13px"
        android:textStyle="bold"
        android:layout_toLeftOf="@id/checkbox"
        android:layout_alignParentLeft="true"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content" />
    <TextView
        android:id="@+id/text_phone"
        android:textSize="9px"
        android:layout_toLeftOf="@id/checkbox"
        android:layout_below="@id/text_name"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content" />
</RelativeLayout>

Then in Activity's onCreate(), I do like this:

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    // Query the contacts
    mCursor = getContentResolver().query(Phones.CONTENT_URI, null, null, null, null);
    startManagingCursor(mCursor);

    ListAdapter adapter = new SimpleCursorAdapter(this,
            R.layout.row,
            mCursor,
            new String[] { Phones.NAME, Phones.NUMBER},
            new int[] { R.id.text_name, R.id.text_phone });
    setListAdapter(adapter);
    getListView().setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
}

The result kind of looks like what I want, but it looks like the list doesn't know which item of it is selected. Also, I need to click exactly on the CheckBox. In the List11 example, I only need to click on the item row.

So what do I need to do to make a multiple choice list with my custom view for each row? Many thanks.

ContentLicense: CC BY-SA 2.5


问:
How to select from whereIn clause using Laravel Eloquent ORM or Query Builder?
I'd like to get value by the following MySQL using Eloquent ORM.

MySQL Query -

```<code>SELECT * FROM `users` WHERE `is_super_admin` = 1 OR `is_partner` = 1
OR `is_admin` = 1 OR `id` IN
(select `user_id` from `site_userrole_mapper` where `is_site_owner` = 1)
</code>```

Laravel Query (It's not working) -

```<code>Users::Where('is_super_admin', '=', 1)
        ->orWhere('is_partner', '=', 1)
        ->orWhere('is_admin', '=', 1)
        ->orWhereIn('id', [
            DB::table('site_userrole_mapper')
            ->select('user_id')
            ->where('is_site_owner', '=', 1)
            ->get()
            //Here get() returns an object and we're not able compare it with id
        ])
        ->get();
</code>```

I just want to convert above MySQL query in Eloquent ORM. Thanks for your help.

答:
Try this one,

change this query and pluck user_id

```<code>whereIn('id',[
DB::table('site_userrole_mapper')
        ->select('user_id')
        ->where('is_site_owner', '=', 1)
        ->get()
   ])
</code>```

to

```<code>whereIn('id',
DB::table('site_userrole_mapper')
        ->where('is_site_owner', '=', 1)
        ->pluck('user_id')
      )
</code>```

Body:
I'd like to get value by the following MySQL using Eloquent ORM.

MySQL Query -

SELECT * FROM `users` WHERE `is_super_admin` = 1 OR `is_partner` = 1
OR `is_admin` = 1 OR `id` IN
(select `user_id` from `site_userrole_mapper` where `is_site_owner` = 1)

Laravel Query (It's not working) -

Users::Where('is_super_admin', '=', 1)
        ->orWhere('is_partner', '=', 1)
        ->orWhere('is_admin', '=', 1)
        ->orWhereIn('id', [
            DB::table('site_userrole_mapper')
            ->select('user_id')
            ->where('is_site_owner', '=', 1)
            ->get()
            //Here get() returns an object and we're not able compare it with id
        ])
        ->get();

I just want to convert above MySQL query in Eloquent ORM. Thanks for your help.

Body:
Try this one,

change this query and pluck user_id

whereIn('id',[
DB::table('site_userrole_mapper')
        ->select('user_id')
        ->where('is_site_owner', '=', 1)
        ->get()
   ])

to

whereIn('id',
DB::table('site_userrole_mapper')
        ->where('is_site_owner', '=', 1)
        ->pluck('user_id')
      )


问:
Npm cannot be installed successfully while installing nodejs
I'm new in using nodejs. I installed Node.js using this command

```<code>sudo apt-get install -y nodejs
</code>```

Normally, when Node.js is installed, npm will be automatically installed.
But when checking the npm version i get this result

How can i fix it?

答:
Remove the legacy NodeJS by calling sudo apt-get remove --purge nodejs -y because it seems to be outdated

Follow the instruction on the NodeJS page here

NodeJS from the Linux repositories are mostly outdated. The newest version is v8.x

Body:
I'm new in using nodejs. I installed Node.js using this command

sudo apt-get install -y nodejs

Normally, when Node.js is installed, npm will be automatically installed.
But when checking the npm version i get this result

How can i fix it?


答:
it seems (for some) that there is a bug in the latest Ubuntu software version of Nodejs that causes the segmentation fault that you are haveing

The best way to install it is by getting node from the source and compiling it.

```<code>#!/bin/sh
# Update System
echo "System Update"
apt-get -y update
echo "Update completed"
# Installing the applications needed to build Nodejs
apt-get -y install libssl-dev git-core pkg-config build-essential curl gcc g++ checkinstall
# Download & Unpack Node.js - v7.3.0
echo "Download Node.js - v7.3.0"
mkdir /tmp/node-install
cd /tmp/node-install
wget https://nodejs.org/dist/latest/node-v7.3.0.tar.gz
tar -zxf node-v7.3.0.tar.gz
echo "Node.js download & unpack completed"
# Install Node.js
echo "Compiling and installing Node.js"
cd node-v7.3.0
./configure && make && checkinstall --install=yes --pkgname=nodejs --pkgversion "7.3.0" --default
echo "Node.js install completed! Deleting The /tmp files"
rm -rf /tmp/node-install
echo "If you have made it this far in the script with no errors popping up all is well have a good day"
</code>```

Make sure and use sudo chmod a+x /path/to/file/install_nodejs_latest.sh to make sure it will start. Then use sudo sh /path/to/file/install_nodejs_latest.sh to start it. (It must me ran with sudo for all the commands to fire correctly)

The script removes the old nodejs, npm and all node modules.

It will update npm at the end of the script.

Every once and awhile it is recommended to do sudo npm install -g npm (If you want the latest) because npm upgrades faster then node js does

after the script is complete run npm -v and node -v If the versions pop up then run sudo npm install -g phonegap,sudo npm install -g cordova,sudo npm install -g less also if you want to update any of the modules in the future all you have to do is install it again and that will override the preveous one. expressjs is for an app by app bases so it's not recomended to install it globally

i've got the answer from the below source:
link

Title: Npm cannot be installed successfully while installing nodejs

Body:
it seems (for some) that there is a bug in the latest Ubuntu software version of Nodejs that causes the segmentation fault that you are haveing

The best way to install it is by getting node from the source and compiling it.

#!/bin/sh
# Update System
echo "System Update"
apt-get -y update
echo "Update completed"
# Installing the applications needed to build Nodejs
apt-get -y install libssl-dev git-core pkg-config build-essential curl gcc g++ checkinstall
# Download & Unpack Node.js - v7.3.0
echo "Download Node.js - v7.3.0"
mkdir /tmp/node-install
cd /tmp/node-install
wget https://nodejs.org/dist/latest/node-v7.3.0.tar.gz
tar -zxf node-v7.3.0.tar.gz
echo "Node.js download & unpack completed"
# Install Node.js
echo "Compiling and installing Node.js"
cd node-v7.3.0
./configure && make && checkinstall --install=yes --pkgname=nodejs --pkgversion "7.3.0" --default
echo "Node.js install completed! Deleting The /tmp files"
rm -rf /tmp/node-install
echo "If you have made it this far in the script with no errors popping up all is well have a good day"

Make sure and use sudo chmod a+x /path/to/file/install_nodejs_latest.sh to make sure it will start. Then use sudo sh /path/to/file/install_nodejs_latest.sh to start it. (It must me ran with sudo for all the commands to fire correctly)

The script removes the old nodejs, npm and all node modules.

It will update npm at the end of the script.

Every once and awhile it is recommended to do sudo npm install -g npm (If you want the latest) because npm upgrades faster then node js does

after the script is complete run npm -v and node -v If the versions pop up then run sudo npm install -g phonegap,sudo npm install -g cordova,sudo npm install -g less also if you want to update any of the modules in the future all you have to do is install it again and that will override the preveous one. expressjs is for an app by app bases so it's not recomended to install it globally

i've got the answer from the below source:
link


问:
Sum of revision number of all xml file into json file
I just want to read revision number of all XML file and put the addition of that revision into a new variable and then write into JSON file.

I am using XSLT for this.
I am using document function to get all required XML files.

Then I am fetching the value of all revision:

```<code><SAMPLE CODE>
<XSLT>
'<xsl:stylesheet version="2.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:tns="http://tnsnamespace"
<xsl:output method="text" indent="yes" />

<xsl:template match="/">
<xsl:copy>
  <xsl:apply-templates select="document('C:\AW_Worksapce\File1.xml')/*"/>
  <xsl:apply-templates select="document('C:\AW_Worksapce\File2.xml')/*"/>
  <xsl:apply-templates select="document('C:\AW_Worksapce\File3.xml')/*"/>
</xsl:copy>

</xsl:template>

<xsl:template match="app">
{
  <xsl:variable name="rev" select="@revision" />
    // Here some where I need to add all rev value into a
</code>```

variable totalrev
        // Which I can use further

e.g.  File1.xml ahhve revision = 3 File1.xml ahhve revision = 2
  File1.xml ahhve revision = 5

So output would be totalrev = 10

But I am not sure how to add them.

```<code>Now,

build.xml file
<fileset dir="Windows/" casesensitive="yes" id="filename.list">
        <include name="file1.xml"/>
        <include name="file2.xml"/>
        <include name="file3.xml"/>
</fileset>
<pathconvert property="filename.list.csv" refid="filename.list" pathsep=","
/>

    <xslt basedir="Windows/" destdir="/meta-inf" extension=".mf"
style="test1.xslt" >
        <mapper type="glob" from="*.xml" to="test1.mf"/>
        <param name="build_date" expression="${build.date}"/>
        <param name="dir" expression="${windows.dir}"/>
        <param name="file_list" expression="${new.filename.list.csv}"/>
    </xslt>

I want extract all three files from fileset and use like below:

XSLT File:
<xsl:variable name="docs" select="document('file1.xml') |
document('file2.xml') | document('file3.xml')"/>

Can anyone help me here?
</code>```

答:
You could use a global variable with all documents, in XSLT 1.0 and later you can use

```<code><xsl:variable name="docs" select="document('C:\AW_Worksapce\File1.xml') | document('C:\AW_Worksapce\File2.xml') | document('C:\AW_Worksapce\File3.xml')"/>
</code>```

in XSLT 2.0 and later you can also use

```<code><xsl:variable name="docs" select="document('C:\AW_Worksapce\File1.xml'), document('C:\AW_Worksapce\File2.xml'), document('C:\AW_Worksapce\File3.xml')"/>
</code>```

in all versions you can then simply compute sum($docs//app/@revision).

Body:
I just want to read revision number of all XML file and put the addition of that revision into a new variable and then write into JSON file.

I am using XSLT for this.
I am using document function to get all required XML files.

Then I am fetching the value of all revision:

<SAMPLE CODE>
<XSLT>
'<xsl:stylesheet version="2.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:tns="http://tnsnamespace"
<xsl:output method="text" indent="yes" />

<xsl:template match="/">
<xsl:copy>
  <xsl:apply-templates select="document('C:\AW_Worksapce\File1.xml')/*"/>
  <xsl:apply-templates select="document('C:\AW_Worksapce\File2.xml')/*"/>
  <xsl:apply-templates select="document('C:\AW_Worksapce\File3.xml')/*"/>
</xsl:copy>

</xsl:template>

<xsl:template match="app">
{
  <xsl:variable name="rev" select="@revision" />
    // Here some where I need to add all rev value into a

variable totalrev
        // Which I can use further

e.g.  File1.xml ahhve revision = 3 File1.xml ahhve revision = 2
  File1.xml ahhve revision = 5

So output would be totalrev = 10

But I am not sure how to add them.

Now,

build.xml file
<fileset dir="Windows/" casesensitive="yes" id="filename.list">
        <include name="file1.xml"/>
        <include name="file2.xml"/>
        <include name="file3.xml"/>
</fileset>
<pathconvert property="filename.list.csv" refid="filename.list" pathsep=","
/>

    <xslt basedir="Windows/" destdir="/meta-inf" extension=".mf"
style="test1.xslt" >
        <mapper type="glob" from="*.xml" to="test1.mf"/>
        <param name="build_date" expression="${build.date}"/>
        <param name="dir" expression="${windows.dir}"/>
        <param name="file_list" expression="${new.filename.list.csv}"/>
    </xslt>

I want extract all three files from fileset and use like below:

XSLT File:
<xsl:variable name="docs" select="document('file1.xml') |
document('file2.xml') | document('file3.xml')"/>

Can anyone help me here?

Body:
You could use a global variable with all documents, in XSLT 1.0 and later you can use

<xsl:variable name="docs" select="document('C:\AW_Worksapce\File1.xml') | document('C:\AW_Worksapce\File2.xml') | document('C:\AW_Worksapce\File3.xml')"/>

in XSLT 2.0 and later you can also use

<xsl:variable name="docs" select="document('C:\AW_Worksapce\File1.xml'), document('C:\AW_Worksapce\File2.xml'), document('C:\AW_Worksapce\File3.xml')"/>

in all versions you can then simply compute sum($docs//app/@revision).


问:
azure app registration remove permissions
I have registered an App in AAD. Then in required permissions I added alot of permissions for AAD and Office Graph. Then I removed all permissions but noticed my app kept working. Required Permissions is empty, but permissions still have all the permissions:
Permissions

How can I remove all permissions from an App in AAD?

答:
After removing the permission, we need to grant permission to make the changing work. Here is a figure for your reference:

And we can confirm the permission is changed successfully by decoding the token from this site. You can see the roles or scope claim in the decoded token.


问:
Drupal 6 - change Author of a node
Is there an easy way to change the author of a node to another user? I can't seem to find it. I found a workaround, which was to setup an "action" to change the author of a node to a specific user, and then temporarily setup a "trigger" so that whenever i update a node, it should run that action. It works, but is ugly. I suppose I could also attack the db directly, but these both seem like rather inelegant solutions.

I appreciate this shouldn't be that common an requirement. This is what happened: I setup the site, including place-holder content, which the publisher users then populated with real content. This was clearly not the right way to go about it, but it's the situation I find myself in...

答:
Can't you simply edit the node, expand the Authoring Information section near the bottom of the page, and change the Author name.

It should be noted that in order to change these the administer nodes permission must be set for that account.  If this is undesired (and in production environments, it is), you can use the Rules module or use the nodeapi hooks to change the desired fields.

Title: Drupal 6 - change Author of a node


问:
TransactionTooLargeException only on Nougat
I've go an app that works well on devices with Android versions lower than Nougat.

When I launch the app on a device with Nougat and I press home button, the app crashes and in logcat I have:

```<code>!!! FAILED BINDER TRANSACTION !!!  (parcel size = 1819712)
Unhandled exception
java.lang.RuntimeException: android.os.TransactionTooLargeException: data parcel size 1819712 bytes
    at android.app.ActivityThread$StopInfo.run(ActivityThread.java:3781)
    at android.os.Handler.handleCallback(Handler.java:751)
    at android.os.Handler.dispatchMessage(Handler.java:95)
    at android.os.Looper.loop(Looper.java:154)
    at android.app.ActivityThread.main(ActivityThread.java:6119)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)
 Caused by: android.os.TransactionTooLargeException: data parcel size 1819712 bytes
    at android.os.BinderProxy.transactNative(Native Method)
    at android.os.BinderProxy.transact(Binder.java:615)
    at android.app.ActivityManagerProxy.activityStopped(ActivityManagerNative.java:3636)
    at android.app.ActivityThread$StopInfo.run(ActivityThread.java:3773)
    at android.os.Handler.handleCallback(Handler.java:751)
    at android.os.Handler.dispatchMessage(Handler.java:95)
    at android.os.Looper.loop(Looper.java:154)
    at android.app.ActivityThread.main(ActivityThread.java:6119)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)
</code>```

Is there a simple solution? This problem appears only on Nougat.

答:
I have the same problem. This has been complained by many developers on the google forum. Their answer is WAI (work as intended) because they don't recommend to save too much data in the state.
So the advice is to only add very basic arguments to an Intent.
If you want to send data among activities or fragments,

Store the data in a (temporary) file and pass around the file URI.
This option is probably your only option if you want to transfer
large amounts of data to a completely different app. Store the data
in the Application instance;

Create a singleton container holding the
data you pass around.

If you are using FragmentStatePageAdapter, add the following code to avoid it saving state data.

```<code>@Override
public Parcelable saveState() {
        Bundle bundle = (Bundle) super.saveState();
        bundle.putParcelableArray("states", null); // Never maintain any states from the base class to avoid TransactionTooLargeException
        return bundle;
}
</code>```

Reference:

https://issuetracker.google.com/issues/37103380

https://www.neotechsoftware.com/blog/android-intent-size-limit

ContentLicense: CC BY-SA 4.0

Body:
I've go an app that works well on devices with Android versions lower than Nougat.

When I launch the app on a device with Nougat and I press home button, the app crashes and in logcat I have:

!!! FAILED BINDER TRANSACTION !!!  (parcel size = 1819712)
Unhandled exception
java.lang.RuntimeException: android.os.TransactionTooLargeException: data parcel size 1819712 bytes
    at android.app.ActivityThread$StopInfo.run(ActivityThread.java:3781)
    at android.os.Handler.handleCallback(Handler.java:751)
    at android.os.Handler.dispatchMessage(Handler.java:95)
    at android.os.Looper.loop(Looper.java:154)
    at android.app.ActivityThread.main(ActivityThread.java:6119)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)
 Caused by: android.os.TransactionTooLargeException: data parcel size 1819712 bytes
    at android.os.BinderProxy.transactNative(Native Method)
    at android.os.BinderProxy.transact(Binder.java:615)
    at android.app.ActivityManagerProxy.activityStopped(ActivityManagerNative.java:3636)
    at android.app.ActivityThread$StopInfo.run(ActivityThread.java:3773)
    at android.os.Handler.handleCallback(Handler.java:751)
    at android.os.Handler.dispatchMessage(Handler.java:95)
    at android.os.Looper.loop(Looper.java:154)
    at android.app.ActivityThread.main(ActivityThread.java:6119)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)

Is there a simple solution? This problem appears only on Nougat.

Body:
I have the same problem. This has been complained by many developers on the google forum. Their answer is WAI (work as intended) because they don't recommend to save too much data in the state.
So the advice is to only add very basic arguments to an Intent.
If you want to send data among activities or fragments,

Store the data in a (temporary) file and pass around the file URI.
This option is probably your only option if you want to transfer
large amounts of data to a completely different app. Store the data
in the Application instance;

Create a singleton container holding the
data you pass around.

If you are using FragmentStatePageAdapter, add the following code to avoid it saving state data.

@Override
public Parcelable saveState() {
        Bundle bundle = (Bundle) super.saveState();
        bundle.putParcelableArray("states", null); // Never maintain any states from the base class to avoid TransactionTooLargeException
        return bundle;
}

Reference:

https://issuetracker.google.com/issues/37103380

https://www.neotechsoftware.com/blog/android-intent-size-limit


问:
npm install -g ionic not installing in windows 8.1
I'm new to ionic framework and getting error when im trying to install ionic.

I have installed apache-ant, nodejs, cordova but when i was trying to install ionic then it throws error as follows.

OS windows 8.1 64 bit.

Please guide me to install this ionic.

```<code>\node-sass\build\binding.sln" (default target) (1) ->
(_src_\libsass target) ->
  ..\..\src\libsass\include\sass/base.h(18): fatal error C1083: Cannot open inc
lude file: 'stdbool.h': No such file or directory [C:\Users\guru.ramachandran\A
ppData\Roaming\npm\node_modules\ionic\node_modules\node-sass\build\binding.sln]
  ..\..\src\libsass\include\sass/base.h(18): fatal error C1083: Cannot open inc
lude file: 'stdbool.h': No such file or directory [C:\Users\guru.ramachandran\A
ppData\Roaming\npm\node_modules\ionic\node_modules\node-sass\build\binding.sln]
  c:\users\guru.ramachandran\appdata\roaming\npm\node_modules\ionic\node_module
s\node-sass\src\libsass\src\units.hpp(10): error C2668: 'acos' : ambiguous call
 to overloaded function [C:\Users\guru.ramachandran\AppData\Roaming\npm\node_mo
dules\ionic\node_modules\node-sass\build\binding.sln]
  c:\users\guru.ramachandran\appdata\roaming\npm\node_modules\ionic\node_module
s\node-sass\src\libsass\src\ast.hpp(12): fatal error C1083: Cannot open include
 file: 'unordered_map': No such file or directory [C:\Users\guru.ramachandran\A
ppData\Roaming\npm\node_modules\ionic\node_modules\node-sass\build\binding.sln]
  c:\users\guru.ramachandran\appdata\roaming\npm\node_modules\ionic\node_module
s\node-sass\src\libsass\src\ast.hpp(12): fatal error C1083: Cannot open include
 file: 'unordered_map': No such file or directory [C:\Users\guru.ramachandran\A
ppData\Roaming\npm\node_modules\ionic\node_modules\node-sass\build\binding.sln]
  ..\..\src\libsass\include\sass/values.h(5): fatal error C1083: Cannot open in
clude file: 'stdbool.h': No such file or directory [C:\Users\guru.ramachandran\
AppData\Roaming\npm\node_modules\ionic\node_modules\node-sass\build\binding.sln
</code>```

答:
The issue is about node-gyp module, which requires VS2013-VS2015 to build components at this time, in their README file, they say

Option 1

Install all the required tools and configurations using Microsoft's
  windows-build-tools using

npm install --global --production windows-build-tools

from an elevated PowerShell or CMD.exe (run as
  Administrator).

Option 2

Install tools and configuration manually:

Visual C++ Build Environment:

Option 1: Install Visual C++ Build Tools using the Default Install
  option.

Option 2: Install Visual Studio 2015 (or modify an existing
  installation) and select Common Tools for Visual C++ during setup.
  This also works with the free Community and Express for Desktop
  editions.

[Windows Vista / 7 only] requires .NET Framework 4.5.1 Install
  Python 2.7 (v3.x.x is not supported), and run npm config set python
  python2.7 (or see below for further instructions on specifying the
  proper Python version and path.)

Launch cmd, npm config set msvs_version 2015

Source: https://github.com/nodejs/node-gyp

Body:
I'm new to ionic framework and getting error when im trying to install ionic.

I have installed apache-ant, nodejs, cordova but when i was trying to install ionic then it throws error as follows.

OS windows 8.1 64 bit.

Please guide me to install this ionic.

\node-sass\build\binding.sln" (default target) (1) ->
(_src_\libsass target) ->
  ..\..\src\libsass\include\sass/base.h(18): fatal error C1083: Cannot open inc
lude file: 'stdbool.h': No such file or directory [C:\Users\guru.ramachandran\A
ppData\Roaming\npm\node_modules\ionic\node_modules\node-sass\build\binding.sln]
  ..\..\src\libsass\include\sass/base.h(18): fatal error C1083: Cannot open inc
lude file: 'stdbool.h': No such file or directory [C:\Users\guru.ramachandran\A
ppData\Roaming\npm\node_modules\ionic\node_modules\node-sass\build\binding.sln]
  c:\users\guru.ramachandran\appdata\roaming\npm\node_modules\ionic\node_module
s\node-sass\src\libsass\src\units.hpp(10): error C2668: 'acos' : ambiguous call
 to overloaded function [C:\Users\guru.ramachandran\AppData\Roaming\npm\node_mo
dules\ionic\node_modules\node-sass\build\binding.sln]
  c:\users\guru.ramachandran\appdata\roaming\npm\node_modules\ionic\node_module
s\node-sass\src\libsass\src\ast.hpp(12): fatal error C1083: Cannot open include
 file: 'unordered_map': No such file or directory [C:\Users\guru.ramachandran\A
ppData\Roaming\npm\node_modules\ionic\node_modules\node-sass\build\binding.sln]
  c:\users\guru.ramachandran\appdata\roaming\npm\node_modules\ionic\node_module
s\node-sass\src\libsass\src\ast.hpp(12): fatal error C1083: Cannot open include
 file: 'unordered_map': No such file or directory [C:\Users\guru.ramachandran\A
ppData\Roaming\npm\node_modules\ionic\node_modules\node-sass\build\binding.sln]
  ..\..\src\libsass\include\sass/values.h(5): fatal error C1083: Cannot open in
clude file: 'stdbool.h': No such file or directory [C:\Users\guru.ramachandran\
AppData\Roaming\npm\node_modules\ionic\node_modules\node-sass\build\binding.sln


问:
RoR autoload sub directories
I have created a "services" dir in app/ where I have created some classes (services). Now it's looks like this :

```<code>-app
   -services
      -class1
      -class2
      -class3
      -class4
</code>```

For now, I have added app/services in config/spring.rb

```<code>%w(
  .ruby-version
  .rbenv-vars
  tmp/restart.txt
  tmp/caching-dev.txt
  app/services
  app/errors
).each { |path| Spring.watch(path) }
</code>```

So my classes in services are loaded.

But now, I want to do this :

```<code>-app
   -services
      -dir1
         -class1
         -class2
      -dir2
         -class3
      -class4
</code>```

I got error :

uninitialized constant TransactionService::AuthorizeRequest

How autoload a dir and subdir ?

答:
Rails tries to guess namespaces by dirnames & filenames. So, to have a  TransactionService::AuthorizeRequest class name, you should have the exact following structure:

```<code>app
- services
-- transaction_service
--- authorize_request.rb
</code>```

Your class sould looks like :

```<code>module TransactionService
  class AuthorizeRequest
  end
end
</code>```

Title: RoR autoload sub directories

Body:
I have created a "services" dir in app/ where I have created some classes (services). Now it's looks like this :

-app
   -services
      -class1
      -class2
      -class3
      -class4

For now, I have added app/services in config/spring.rb

%w(
  .ruby-version
  .rbenv-vars
  tmp/restart.txt
  tmp/caching-dev.txt
  app/services
  app/errors
).each { |path| Spring.watch(path) }

So my classes in services are loaded.

But now, I want to do this :

-app
   -services
      -dir1
         -class1
         -class2
      -dir2
         -class3
      -class4

I got error :

uninitialized constant TransactionService::AuthorizeRequest

How autoload a dir and subdir ?

Body:
Rails tries to guess namespaces by dirnames & filenames. So, to have a  TransactionService::AuthorizeRequest class name, you should have the exact following structure:

app
- services
-- transaction_service
--- authorize_request.rb

Your class sould looks like :

module TransactionService
  class AuthorizeRequest
  end
end


问:
Add items to listbox using pushbutton and drop down menu in MATLAB
I am creating a GUI using GUIDE in MATLAB2015. I have a drop down menu which the user selects a message to view, after that they click the Add push button to add the message name to a list box and display the data it contains in a table.

My problem is, if I want to add more than one message, instead of adding that message, it overwrites the previous one. Below is my current code.

```<code>addData = getappdata(handles.msgSel_menu, 'Data');
boxMsg = get(handles.msgSel_menu,'String');
boxMsgVal = get(handles.msgSel_menu,'Value');
set(handles.activeDataBox,'String',boxMsg{boxMsgVal});
set(handles.data_table, 'Data', addData);
</code>```

Apologies if this has been done multiple times before, but as I'm relatively new to MATLAB I could do with a little explanation of any code that fixes my issue.

答:
You have to get the initial string cell from your listbox then you add the desired element to the cell. From the resulting cell variable, you update the listbox using the set command.

Here is a simple example.

```<code>addData = getappdata(handles.msgSel_menu, 'Data');
current_data = get(handles.activeDataBox, 'String'); % get the current string
new_data = current_data; % set new_data to the initial string ...
new_data{ length(current_data) + 1 } = addData ; % ... then you add the desired element by incrementing the cell
set(handles.activeDataBox, 'String', new_data); % update your listbox
</code>```

EDIT : The code has been updated.

Body:
I am creating a GUI using GUIDE in MATLAB2015. I have a drop down menu which the user selects a message to view, after that they click the Add push button to add the message name to a list box and display the data it contains in a table.

My problem is, if I want to add more than one message, instead of adding that message, it overwrites the previous one. Below is my current code.

addData = getappdata(handles.msgSel_menu, 'Data');
boxMsg = get(handles.msgSel_menu,'String');
boxMsgVal = get(handles.msgSel_menu,'Value');
set(handles.activeDataBox,'String',boxMsg{boxMsgVal});
set(handles.data_table, 'Data', addData);

Apologies if this has been done multiple times before, but as I'm relatively new to MATLAB I could do with a little explanation of any code that fixes my issue.

Body:
You have to get the initial string cell from your listbox then you add the desired element to the cell. From the resulting cell variable, you update the listbox using the set command.

Here is a simple example.

addData = getappdata(handles.msgSel_menu, 'Data');
current_data = get(handles.activeDataBox, 'String'); % get the current string
new_data = current_data; % set new_data to the initial string ...
new_data{ length(current_data) + 1 } = addData ; % ... then you add the desired element by incrementing the cell
set(handles.activeDataBox, 'String', new_data); % update your listbox

EDIT : The code has been updated.


问:
Automatic class decoration (or validation) upon derivation

I have a base class from which I derive multiple subclasses.

Each subclass defines class constants, and I wish to enforce certain limitations on them.
For example:

```<code>class Base(object):
    # define these in your sub-class, and make sure (NOM % DENOM == 0)
    NOMINATOR = None
    DENOMINATOR = None

class Subclass_good(Base):
    NOMINATOR = 6
    DENOMINATOR = 3

class Subclass_bad(Base):
    NOMINATOR = 7
    DENOMINATOR = 5
</code>```

I want to be able to enforce the rule (NOM % DENOM == 0).

I currently do this with a class decorator:

```<code>def nom_denom_validator(cls):
    assert(cls.NOMINATOR % cls.DENOMINATOR == 0)
    return cls

# and decorate each subclass, e.g.:
@nom_denom_validator
class Subclass_another(Base):
    NOMINATOR = 9
    DENOMINATOR = 12
</code>```

But I don't like the fact that I need to decorate each subclass (I have plenty). I'm interested whether this can be done by some manipulation on the Base class directly.

Any advice?

答:
You can do the checking in the base classes constructor

```<code>class Base(object):
    # define these in your sub-class, and make sure (NOM % DENOM == 0)
    NOMINATOR = None
    DENOMINATOR = None
    def __init__(self):
        assert(self.NOMINATOR % self.DENOMINATOR == 0)
</code>```

When you create an instance of Subclass_bad(), you'll get AssertionError.

Body:
I have a base class from which I derive multiple subclasses.

Each subclass defines class constants, and I wish to enforce certain limitations on them.
For example:

class Base(object):
    # define these in your sub-class, and make sure (NOM % DENOM == 0)
    NOMINATOR = None
    DENOMINATOR = None

class Subclass_good(Base):
    NOMINATOR = 6
    DENOMINATOR = 3

class Subclass_bad(Base):
    NOMINATOR = 7
    DENOMINATOR = 5

I want to be able to enforce the rule (NOM % DENOM == 0).

I currently do this with a class decorator:

def nom_denom_validator(cls):
    assert(cls.NOMINATOR % cls.DENOMINATOR == 0)
    return cls

# and decorate each subclass, e.g.:
@nom_denom_validator
class Subclass_another(Base):
    NOMINATOR = 9
    DENOMINATOR = 12

But I don't like the fact that I need to decorate each subclass (I have plenty). I'm interested whether this can be done by some manipulation on the Base class directly.

Any advice?

Body:
You can do the checking in the base classes constructor

class Base(object):
    # define these in your sub-class, and make sure (NOM % DENOM == 0)
    NOMINATOR = None
    DENOMINATOR = None
    def __init__(self):
        assert(self.NOMINATOR % self.DENOMINATOR == 0)

When you create an instance of Subclass_bad(), you'll get AssertionError.


答:
You should multiply your seconds (eg 4) with 1000.

Because you have to give it in milliseconds.

Try changing your code to

```<code> @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    this.requestWindowFeature(Window.FEATURE_NO_TITLE);
    setContentView(R.layout.splash_screen);

    int secondsDelayed = 4;
    new Handler().postDelayed(new Runnable() {
      public void run() {
        startActivity(new Intent(SplashScreen.this,
          SignInActivity.class));
        finish();
      }
    }, secondsDelayed * 1000);
  }
}
</code>```

Title: Splash Screen is displaying too fast and then going into the next Java Class

Body:
The splash screen is supposed to last 3 seconds but it skipping it almost entirely when the app is run on Genymotion Emulator or Android Studios Emulator both emulators are running perfectly with other applications. I don't understand?

SplashScreen.java

package com.transcendencetech.juliospizzaprototype;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.view.Window;

/**
 * Created by Stormy Forrester on 20/03/2016.
 */
public class SplashScreen extends AppCompatActivity {

  /** Called when the activity is first created. */
  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    this.requestWindowFeature(Window.FEATURE_NO_TITLE);
    setContentView(R.layout.splash_screen);

    int secondsDelayed = 4;
    new Handler().postDelayed(new Runnable() {
      public void run() {
        startActivity(new Intent(SplashScreen.this,
          SignInActivity.class));
        finish();
      }
    }, secondsDelayed * 3);
  }
}

**splash_screen,xml **

Body:
You should multiply your seconds (eg 4) with 1000.

Because you have to give it in milliseconds.

Try changing your code to

 @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    this.requestWindowFeature(Window.FEATURE_NO_TITLE);
    setContentView(R.layout.splash_screen);

    int secondsDelayed = 4;
    new Handler().postDelayed(new Runnable() {
      public void run() {
        startActivity(new Intent(SplashScreen.this,
          SignInActivity.class));
        finish();
      }
    }, secondsDelayed * 1000);
  }
}


问:
React via Webpack - Production flag increases file size
I'm pretty new to using React and Webpack so I'm likely doing something wrong, but when I build with the -p production flag my file size is considerably bigger (3.26MB vs 2.23MB) than when I build without.

package.json:

```<code>{
  "name": "myProject",
  "version": "0.0.1",
  "description": "",
  "main": "webpack.config.js",
  "dependencies": {
    "babel-loader": "^6.2.0",
    "babel-plugin-add-module-exports": "^0.1.2",
    "babel-plugin-react-html-attrs": "^2.0.0",
    "babel-plugin-transform-class-properties": "^6.3.13",
    "babel-plugin-transform-decorators-legacy": "^1.3.4",
    "babel-preset-es2015": "^6.3.13",
    "babel-preset-react": "^6.3.13",
    "babel-preset-stage-0": "^6.3.13",
    "flux": "^2.1.1",
    "history": "^1.17.0",
    "react": "^0.14.6",
    "react-dom": "^0.14.6",
    "react-router": "^1.0.3",
    "webpack": "^1.12.9",
    "webpack-dev-server": "^1.14.1"
  },
  "devDependencies": {},
  "scripts": {
    "dev": "webpack-dev-server --content-base src --inline --hot",
    "build": "webpack",
    "build-p": "webpack -p"
  },
  "author": ""
}
</code>```

webpack.config.js:

```<code>var debug = process.env.NODE_ENV !== "production";
var webpack = require('webpack');
var path = require('path');

module.exports = {
  context: path.join(__dirname, "src"),
  devtool: debug ? "inline-sourcemap" : null,
  entry: "./js/app.js",
  module: {
    loaders: [
      {
        test: /\.jsx?$/,
        exclude: /(node_modules|bower_components)/,
        loader: 'babel-loader',
        query: {
          presets: ['react', 'es2015', 'stage-0'],
          plugins: ['react-html-attrs', 'transform-class-properties', 'transform-decorators-legacy'],
        }
      }
    ]
  },
  output: {
    path: __dirname + "/src/",
    filename: "app.min.js"
  },
  plugins: debug ? [] : [
    new webpack.optimize.DedupePlugin(),
    new webpack.optimize.OccurenceOrderPlugin(),
    new webpack.optimize.UglifyJsPlugin({ mangle: false, sourcemap: false }),
  ],
};
</code>```

答:
I had the same problem and it got solved by removing the 'debug' property from webpack.conf.js. In stead I call webpack with the -d flag when I'm developing (and not when building the production bundle), as that adds the debug property automatically.

I see that debug is a conditional in your config, but at least it solved the problem for me.

Body:
I'm pretty new to using React and Webpack so I'm likely doing something wrong, but when I build with the -p production flag my file size is considerably bigger (3.26MB vs 2.23MB) than when I build without.

package.json:

{
  "name": "myProject",
  "version": "0.0.1",
  "description": "",
  "main": "webpack.config.js",
  "dependencies": {
    "babel-loader": "^6.2.0",
    "babel-plugin-add-module-exports": "^0.1.2",
    "babel-plugin-react-html-attrs": "^2.0.0",
    "babel-plugin-transform-class-properties": "^6.3.13",
    "babel-plugin-transform-decorators-legacy": "^1.3.4",
    "babel-preset-es2015": "^6.3.13",
    "babel-preset-react": "^6.3.13",
    "babel-preset-stage-0": "^6.3.13",
    "flux": "^2.1.1",
    "history": "^1.17.0",
    "react": "^0.14.6",
    "react-dom": "^0.14.6",
    "react-router": "^1.0.3",
    "webpack": "^1.12.9",
    "webpack-dev-server": "^1.14.1"
  },
  "devDependencies": {},
  "scripts": {
    "dev": "webpack-dev-server --content-base src --inline --hot",
    "build": "webpack",
    "build-p": "webpack -p"
  },
  "author": ""
}

webpack.config.js:

var debug = process.env.NODE_ENV !== "production";
var webpack = require('webpack');
var path = require('path');

module.exports = {
  context: path.join(__dirname, "src"),
  devtool: debug ? "inline-sourcemap" : null,
  entry: "./js/app.js",
  module: {
    loaders: [
      {
        test: /\.jsx?$/,
        exclude: /(node_modules|bower_components)/,
        loader: 'babel-loader',
        query: {
          presets: ['react', 'es2015', 'stage-0'],
          plugins: ['react-html-attrs', 'transform-class-properties', 'transform-decorators-legacy'],
        }
      }
    ]
  },
  output: {
    path: __dirname + "/src/",
    filename: "app.min.js"
  },
  plugins: debug ? [] : [
    new webpack.optimize.DedupePlugin(),
    new webpack.optimize.OccurenceOrderPlugin(),
    new webpack.optimize.UglifyJsPlugin({ mangle: false, sourcemap: false }),
  ],
};


问:
How can I increase the cursor speed in terminal?
How can I increase the cursor speed in terminal?
I have Mac OS X by the way.
It would also be interesting to know it for Linux.

I don't know what I should search for in Google (or what you like).

答:
If by "cursor speed", you mean the repeat rate when holding down a key -  then have a look here:
http://hints.macworld.com/article.php?story=20090823193018149

To summarize, open up a Terminal window and type the following command:

```<code>defaults write NSGlobalDomain KeyRepeat -int 0
</code>```

More detail from the article:

Everybody knows that you can get a pretty fast keyboard repeat rate by changing a slider on the Keyboard tab of the Keyboard & Mouse System Preferences panel. But you can make it even faster! In Terminal, run this command:

defaults write NSGlobalDomain KeyRepeat -int 0

Then log out and log in again. The fastest setting obtainable via System Preferences is 2 (lower numbers are faster), so you may also want to try a value of 1 if 0 seems too fast. You can always visit the Keyboard & Mouse System Preferences panel to undo your changes.

You may find that a few applications don't handle extremely fast keyboard input very well, but most will do just fine with it.

Note: It requires a system restart

Body:
If by "cursor speed", you mean the repeat rate when holding down a key -  then have a look here:
http://hints.macworld.com/article.php?story=20090823193018149

To summarize, open up a Terminal window and type the following command:

defaults write NSGlobalDomain KeyRepeat -int 0

More detail from the article:

Everybody knows that you can get a pretty fast keyboard repeat rate by changing a slider on the Keyboard tab of the Keyboard & Mouse System Preferences panel. But you can make it even faster! In Terminal, run this command:

defaults write NSGlobalDomain KeyRepeat -int 0

Then log out and log in again. The fastest setting obtainable via System Preferences is 2 (lower numbers are faster), so you may also want to try a value of 1 if 0 seems too fast. You can always visit the Keyboard & Mouse System Preferences panel to undo your changes.

You may find that a few applications don't handle extremely fast keyboard input very well, but most will do just fine with it.

Note: It requires a system restart


问:
dotnet-core ef sql connection
I want to set sql connection to config.json and use it from AuditContext class.
But when I run example drop-database from PMC, I get an error.

System.ArgumentException: Format of the initialization string does not conform to specification starting at index 21.
     at System.Data.Common.DbConnectionOptions.GetKeyValuePair(String connectionString, Int32 currentPosition, StringBuilder buffer, String& keyname, String& keyvalue)
     at System.Data.Common.DbConnectionOptions.ParseInternal(Dictionary2 parsetable, String connectionString, Boolean buildChain, Dictionary2 synonyms)
     at System.Data.Common.DbConnectionOptions..ctor(String connectionString, Dictionary2 synonyms)
     at System.Data.SqlClient.SqlConnectionString..ctor(String connectionString)
     at System.Data.SqlClient.SqlConnectionFactory.CreateConnectionOptions(String connectionString, DbConnectionOptions previous)
     at System.Data.ProviderBase.DbConnectionFactory.GetConnectionPoolGroup(DbConnectionPoolKey key, DbConnectionPoolGroupOptions poolOptions, DbConnectionOptions& userConnectionOptions)
     at System.Data.SqlClient.SqlConnection.ConnectionString_Set(DbConnectionPoolKey key)
     at System.Data.SqlClient.SqlConnection.set_ConnectionString(String value)
     at Microsoft.EntityFrameworkCore.Storage.Internal.SqlServerConnection.CreateDbConnection()
     at Microsoft.EntityFrameworkCore.Internal.LazyRef1.get_Value()
     at Microsoft.EntityFrameworkCore.Design.Internal.DbContextOperations.GetContextInfo(String contextType)
     at Microsoft.EntityFrameworkCore.Design.OperationExecutor.GetContextInfoImpl(String contextType)
     at Microsoft.EntityFrameworkCore.Design.OperationExecutor.OperationBase.<>c__DisplayClass3_0`1.b__0()
     at Microsoft.EntityFrameworkCore.Design.OperationExecutor.OperationBase.Execute(Action action)

Here is my Startup.cs class

```<code>using System.Threading.Tasks;
using Audit.Models.Entity;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Identity.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json.Serialization;

namespace Audit
{
public class Startup
{
    private IHostingEnvironment _env;
    private IConfigurationRoot _config;

    public Startup(IHostingEnvironment env)
    {
        _env = env;

        var builder = new ConfigurationBuilder()
            .SetBasePath(_env.ContentRootPath)
            .AddJsonFile("config.json")
            .AddEnvironmentVariables();

        _config = builder.Build();
    }
    // This method gets called by the runtime. Use this method to add services to the container.
    // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
    public void ConfigureServices(IServiceCollection services)
    {
        services.AddSingleton(_config);

        services.AddDbContext<AuditContext>();

        services.AddIdentity<ApplicationUser, IdentityRole>(config =>
        {
            config.User.RequireUniqueEmail = false;
            config.Cookies.ApplicationCookie.LoginPath = "/auth/login";
            config.Cookies.ApplicationCookie.Events = new CookieAuthenticationEvents()
            {
                OnRedirectToLogin = async ctx =>
                {
                    if (ctx.Request.Path.StartsWithSegments("/api") && ctx.Response.StatusCode == 200)
                    {
                        ctx.Response.StatusCode = 401;
                    }
                    else
                    {
                        ctx.Response.Redirect(ctx.RedirectUri);
                    }
                    await Task.Yield();

                }
            };
        }).AddEntityFrameworkStores<AuditContext>();

        services.AddLogging();

        services.AddMvc()
            .AddJsonOptions(config =>
                {
                    config.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
                });

    }

    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
    public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
    {

        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
            loggerFactory.AddDebug(LogLevel.Information);
        }
        else
        {
            loggerFactory.AddDebug(LogLevel.Error);
        }

        app.UseStaticFiles();

        app.UseIdentity();

        app.UseMvc(config =>
        {
            config.MapRoute(
              name: "Default",
              template: "{controller}/{action}/{id?}",
              defaults: new { controller = "App", action = "Index" }
              );
        });
    }
  }
  }
</code>```

Here is config.json

```<code>{
  "ConnectionStrings": {
    "AuditDbContextConnection": "Server=xxx.xxx.xxx.xxx;Database:databasename;User Id:user;Password:password;"
  }
}
</code>```

Here is AuditContext.cs

```<code>using Microsoft.AspNetCore.Identity.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;

namespace Audit.Models.Entity
{
    public class AuditContext : IdentityDbContext<ApplicationUser>
    {
        private IConfigurationRoot _config;

        public AuditContext(IConfigurationRoot config, DbContextOptions options) : base(options)
        {
            _config = config;
        }

        public DbSet<Aql> Aql { get; set; }
        public DbSet<AqlVer> AqlVer { get; set; }
        public DbSet<Cartiglio> Cartiglio { get; set; }
        public DbSet<CartonBox> CartonBox { get; set; }
        public DbSet<CartonBoxLog> CartonBoxLog { get; set; }
        public DbSet<Entry> Entry { get; set; }
        public DbSet<Fashion> Fashion { get; set; }
        public DbSet<Level> Level { get; set; }
        public DbSet<MasterCode> MasterCode { get; set; }
        public DbSet<Settings> Settings { get; set; }
        public DbSet<SubCode> SubCode { get; set; }
        public DbSet<TotalProduction> TotalProduction { get; set; }

        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        {

            base.OnConfiguring(optionsBuilder);
            optionsBuilder.UseSqlServer(_config["ConnectionStrings:AuditDbContextConnection"]);
        }

    }

}
</code>```

What I did wrong and where ?
Thanks.

答:
So, as discussed in the comments the problem was that the connection string contained ':' instead of '='.

So instead of:

```<code>{
  "ConnectionStrings": {
    "AuditDbContextConnection": "Server=xxx.xxx.xxx.xxx;Database:databasename;User Id:user;Password:password;"
  }
}
</code>```

This would make it:

```<code>{
  "ConnectionStrings": {
    "AuditDbContextConnection": "Server=xxx.xxx.xxx.xxx;Database=databasename;User Id=user;Password=password;"
  }
}
</code>```

Title: dotnet-core ef sql connection

Body:
I want to set sql connection to config.json and use it from AuditContext class.
But when I run example drop-database from PMC, I get an error.

System.ArgumentException: Format of the initialization string does not conform to specification starting at index 21.
     at System.Data.Common.DbConnectionOptions.GetKeyValuePair(String connectionString, Int32 currentPosition, StringBuilder buffer, String& keyname, String& keyvalue)
     at System.Data.Common.DbConnectionOptions.ParseInternal(Dictionary2 parsetable, String connectionString, Boolean buildChain, Dictionary2 synonyms)
     at System.Data.Common.DbConnectionOptions..ctor(String connectionString, Dictionary2 synonyms)
     at System.Data.SqlClient.SqlConnectionString..ctor(String connectionString)
     at System.Data.SqlClient.SqlConnectionFactory.CreateConnectionOptions(String connectionString, DbConnectionOptions previous)
     at System.Data.ProviderBase.DbConnectionFactory.GetConnectionPoolGroup(DbConnectionPoolKey key, DbConnectionPoolGroupOptions poolOptions, DbConnectionOptions& userConnectionOptions)
     at System.Data.SqlClient.SqlConnection.ConnectionString_Set(DbConnectionPoolKey key)
     at System.Data.SqlClient.SqlConnection.set_ConnectionString(String value)
     at Microsoft.EntityFrameworkCore.Storage.Internal.SqlServerConnection.CreateDbConnection()
     at Microsoft.EntityFrameworkCore.Internal.LazyRef1.get_Value()
     at Microsoft.EntityFrameworkCore.Design.Internal.DbContextOperations.GetContextInfo(String contextType)
     at Microsoft.EntityFrameworkCore.Design.OperationExecutor.GetContextInfoImpl(String contextType)
     at Microsoft.EntityFrameworkCore.Design.OperationExecutor.OperationBase.<>c__DisplayClass3_0`1.b__0()
     at Microsoft.EntityFrameworkCore.Design.OperationExecutor.OperationBase.Execute(Action action)

Here is my Startup.cs class

using System.Threading.Tasks;
using Audit.Models.Entity;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Identity.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json.Serialization;

namespace Audit
{
public class Startup
{
    private IHostingEnvironment _env;
    private IConfigurationRoot _config;

    public Startup(IHostingEnvironment env)
    {
        _env = env;

        var builder = new ConfigurationBuilder()
            .SetBasePath(_env.ContentRootPath)
            .AddJsonFile("config.json")
            .AddEnvironmentVariables();

        _config = builder.Build();
    }
    // This method gets called by the runtime. Use this method to add services to the container.
    // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
    public void ConfigureServices(IServiceCollection services)
    {
        services.AddSingleton(_config);

        services.AddDbContext<AuditContext>();

        services.AddIdentity<ApplicationUser, IdentityRole>(config =>
        {
            config.User.RequireUniqueEmail = false;
            config.Cookies.ApplicationCookie.LoginPath = "/auth/login";
            config.Cookies.ApplicationCookie.Events = new CookieAuthenticationEvents()
            {
                OnRedirectToLogin = async ctx =>
                {
                    if (ctx.Request.Path.StartsWithSegments("/api") && ctx.Response.StatusCode == 200)
                    {
                        ctx.Response.StatusCode = 401;
                    }
                    else
                    {
                        ctx.Response.Redirect(ctx.RedirectUri);
                    }
                    await Task.Yield();

                }
            };
        }).AddEntityFrameworkStores<AuditContext>();

        services.AddLogging();

        services.AddMvc()
            .AddJsonOptions(config =>
                {
                    config.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
                });

    }

    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
    public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
    {

        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
            loggerFactory.AddDebug(LogLevel.Information);
        }
        else
        {
            loggerFactory.AddDebug(LogLevel.Error);
        }

        app.UseStaticFiles();

        app.UseIdentity();

        app.UseMvc(config =>
        {
            config.MapRoute(
              name: "Default",
              template: "{controller}/{action}/{id?}",
              defaults: new { controller = "App", action = "Index" }
              );
        });
    }
  }
  }

Here is config.json

{
  "ConnectionStrings": {
    "AuditDbContextConnection": "Server=xxx.xxx.xxx.xxx;Database:databasename;User Id:user;Password:password;"
  }
}

Here is AuditContext.cs

using Microsoft.AspNetCore.Identity.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;

namespace Audit.Models.Entity
{
    public class AuditContext : IdentityDbContext<ApplicationUser>
    {
        private IConfigurationRoot _config;

        public AuditContext(IConfigurationRoot config, DbContextOptions options) : base(options)
        {
            _config = config;
        }

        public DbSet<Aql> Aql { get; set; }
        public DbSet<AqlVer> AqlVer { get; set; }
        public DbSet<Cartiglio> Cartiglio { get; set; }
        public DbSet<CartonBox> CartonBox { get; set; }
        public DbSet<CartonBoxLog> CartonBoxLog { get; set; }
        public DbSet<Entry> Entry { get; set; }
        public DbSet<Fashion> Fashion { get; set; }
        public DbSet<Level> Level { get; set; }
        public DbSet<MasterCode> MasterCode { get; set; }
        public DbSet<Settings> Settings { get; set; }
        public DbSet<SubCode> SubCode { get; set; }
        public DbSet<TotalProduction> TotalProduction { get; set; }

        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        {

            base.OnConfiguring(optionsBuilder);
            optionsBuilder.UseSqlServer(_config["ConnectionStrings:AuditDbContextConnection"]);
        }

    }

}

What I did wrong and where ?
Thanks.

Body:
So, as discussed in the comments the problem was that the connection string contained ':' instead of '='.

So instead of:

{
  "ConnectionStrings": {
    "AuditDbContextConnection": "Server=xxx.xxx.xxx.xxx;Database:databasename;User Id:user;Password:password;"
  }
}

This would make it:

{
  "ConnectionStrings": {
    "AuditDbContextConnection": "Server=xxx.xxx.xxx.xxx;Database=databasename;User Id=user;Password=password;"
  }
}


问:
Setting the last value of each matrix in a cell array in Matlab
I have a cell array where each cell contains a matrix of identical size. How do I efficiently set the last entry of each matrix in the array? I was trying to make use of cellfun but it doesn't look like assignment is possible.

Minimal working example (the most efficient implementation I could come up with):

```<code>C = cell(5, 6, 7);
[C{:}] = deal(ones(10, 1));
for i = 1:5
    for j = 1:6
        for k = 1:7
            C{i,j,k}(end) = 0;
        end
    end
end
</code>```

答:
Here's a way to do it without loops. This allows

the cells to contain a matrix (not necessarily a vector as in your example); and

the desired values to be different for each cell (not necessarily the same as in your example).

Code:

```<code>C = repmat({zeros(2,3)}, 4, 5, 6); % example cell array with matrices
values = 1:numel(C); % example vector with numel(C) values. Or it can be a scalar
t = cat(3, C{:}); % temporarily concatenate all matrices into 3D array
t(end,end,:) = values; % set last value of each matrix
C = reshape(num2cell(t, [1 2]), size(C)); % convert back
</code>```

Result:

```<code>>> whos C
  Name      Size             Bytes  Class    Attributes

  C         4x5x6            19200  cell

>> C{1,1,1}
ans =
     0     0     0
     0     0     1
>> C{2,1,1}
ans =
     0     0     0
     0     0     2
>> C{4,5,6}
ans =
     0     0     0
     0     0   120
</code>```

Body:
I have a cell array where each cell contains a matrix of identical size. How do I efficiently set the last entry of each matrix in the array? I was trying to make use of cellfun but it doesn't look like assignment is possible.

Minimal working example (the most efficient implementation I could come up with):

C = cell(5, 6, 7);
[C{:}] = deal(ones(10, 1));
for i = 1:5
    for j = 1:6
        for k = 1:7
            C{i,j,k}(end) = 0;
        end
    end
end

Body:
Here's a way to do it without loops. This allows

the cells to contain a matrix (not necessarily a vector as in your example); and

the desired values to be different for each cell (not necessarily the same as in your example).

Code:

C = repmat({zeros(2,3)}, 4, 5, 6); % example cell array with matrices
values = 1:numel(C); % example vector with numel(C) values. Or it can be a scalar
t = cat(3, C{:}); % temporarily concatenate all matrices into 3D array
t(end,end,:) = values; % set last value of each matrix
C = reshape(num2cell(t, [1 2]), size(C)); % convert back

Result:

>> whos C
  Name      Size             Bytes  Class    Attributes

  C         4x5x6            19200  cell

>> C{1,1,1}
ans =
     0     0     0
     0     0     1
>> C{2,1,1}
ans =
     0     0     0
     0     0     2
>> C{4,5,6}
ans =
     0     0     0
     0     0   120


问:
Order by created_at not working with Eloquent models
I have a little issue when trying to order records by created_at column when using Eloquent Models. The ordering works by date but not by time. Example if I have 3 records with created_at values:

2017-07-04 07:16:33

2017-07-04 05:35:01

2017-07-04 05:27:48

I have the same output when using orderby('created_at', 'desc') or 'asc'. Ordering however works if i have for example

2017-07-04 05:27:48

2017-07-03 06:35:50

Ordering works also when I use raw queries. The issue is present only when I use Eloquent Model.

Has anyone any idea why is this happening? Thanks in advance

答: Ohh it was my bad! I solved the issue, it wasn't a problem on server side when getting the data, but on client side because I used 'dataTables'</p>


问:
Issue while backpropagating through sparse_tensor_dense_matmul in tensorflow
I have a simple network defined as follows:

```<code>h1 = tf.sparse_tensor_dense_matmul(x, W1)
h2 = tf.matmul(h1, W2)
y = tf.matmul(h2, W3)
loss = tf.nn.l2_loss(y - y_)
train = tf.train.AdamOptimizer(learning_rate=lr).minimize(loss)
</code>```

where x is a sparseTensor, rest are dense.

Dimensions (shapes) of W1 = [1000,200], W2 = [200,400] and W3 = [400, 500].

When I run the following:

```<code>sess.run([train], feed_dict={x:X, y_:Y})
</code>```

where X is sparseTensor of shape [N, 1000] and Y is a tensor of shape [N, 500]

I get an error saying:

OOM when allocating tensor with shape[3684773,200].

This is happening while the the the gradient for W is being computed. 3684773 also happens to be the number of non-zero elements in X.

Note:

When I compute gradients using tf.gradients, they work completely
fine.

When I run the same network using dense X and dense multiply( tf.matmul ), it works completely fine.

答:
Maybe I'm a bit late to help you, but the problem you face is that you do not have enough memory to allocate the tensor for the gradient. Assuming you're working with 32 bit floats, this tensor would need ~2.8 GB of memory, which is quite a lot for graphics cards. The only solution that I see is to pin everything to CPU memory using

```<code>with tf.device("/cpu:0"):
    # your code
</code>```

But then you should expect a large performance penalty.

Body:
I have a simple network defined as follows:

h1 = tf.sparse_tensor_dense_matmul(x, W1)
h2 = tf.matmul(h1, W2)
y = tf.matmul(h2, W3)
loss = tf.nn.l2_loss(y - y_)
train = tf.train.AdamOptimizer(learning_rate=lr).minimize(loss)

where x is a sparseTensor, rest are dense.

Dimensions (shapes) of W1 = [1000,200], W2 = [200,400] and W3 = [400, 500].

When I run the following:

sess.run([train], feed_dict={x:X, y_:Y})

where X is sparseTensor of shape [N, 1000] and Y is a tensor of shape [N, 500]

I get an error saying:

OOM when allocating tensor with shape[3684773,200].

This is happening while the the the gradient for W is being computed. 3684773 also happens to be the number of non-zero elements in X.

Note:

When I compute gradients using tf.gradients, they work completely
fine.

When I run the same network using dense X and dense multiply( tf.matmul ), it works completely fine.

Body:
Maybe I'm a bit late to help you, but the problem you face is that you do not have enough memory to allocate the tensor for the gradient. Assuming you're working with 32 bit floats, this tensor would need ~2.8 GB of memory, which is quite a lot for graphics cards. The only solution that I see is to pin everything to CPU memory using

with tf.device("/cpu:0"):
    # your code

But then you should expect a large performance penalty.


问:
Bootstrap 4: get the last card in card column
I'm using Bootstrap 4 to build a masonry card deck.
Now I have 3 columns with 3 cards in it.
Is it possible to adress the last card of every column?

I could adress the last card of the deck with the following code:

```<code>card-columns div.card:last-of-type
</code>```

But is this also possible for every column?

This is the code of the card deck:

Card title that wraps to a new line

This is a longer card with supporting text below as a natural lead-in to additional content. This content is a little bit longer.

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Integer posuere erat a ante.

          Someone famous in Source Title

Card title

This card has supporting text below as a natural lead-in to additional content.

Last updated 3 mins ago

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Integer posuere erat.

          Someone famous in Source Title

Card title

This card has supporting text below as a natural lead-in to additional content.

Last updated 3 mins ago

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Integer posuere erat a ante.

          Someone famous in Source Title

Card title

This is a wider card with supporting text below as a natural lead-in to additional content. This card has even longer content than the first to show that equal height action.

Last updated 3 mins ago

```

答:
This would be a dynamic solution to the problem, with the given HTML structure.

.card-columns div.card p:last-child {
  background: #ff0000;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="card-columns">
  <div class="card">
    <p>The first paragraph of div 1.</p>
    <p>The second paragraph of div 1.</p>
    <p>The third paragraph of div 1.</p>
    <p>The fourth paragraph of div 1.</p>
  </div>
  <div class="card">
    <p>The first paragraph of div 2.</p>
    <p>The second paragraph of div 2.</p>
    <p>The third paragraph of div 2.</p>
    <p>The fourth paragraph of div 2.</p>
  </div>
</div></code>```

Body:
I'm using Bootstrap 4 to build a masonry card deck.
Now I have 3 columns with 3 cards in it.
Is it possible to adress the last card of every column?

I could adress the last card of the deck with the following code:

card-columns div.card:last-of-type

But is this also possible for every column?

This is the code of the card deck:

Card title that wraps to a new line

This is a longer card with supporting text below as a natural lead-in to additional content. This content is a little bit longer.

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Integer posuere erat a ante.

          Someone famous in Source Title

Card title

This card has supporting text below as a natural lead-in to additional content.

Last updated 3 mins ago

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Integer posuere erat.

          Someone famous in Source Title

Card title

This card has supporting text below as a natural lead-in to additional content.

Last updated 3 mins ago

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Integer posuere erat a ante.

          Someone famous in Source Title

Card title

This is a wider card with supporting text below as a natural lead-in to additional content. This card has even longer content than the first to show that equal height action.

Last updated 3 mins ago

Body:
This would be a dynamic solution to the problem, with the given HTML structure.

.card-columns div.card p:last-child {
  background: #ff0000;
}

<div class="card-columns">
  <div class="card">
    <p>The first paragraph of div 1.</p>
    <p>The second paragraph of div 1.</p>
    <p>The third paragraph of div 1.</p>
    <p>The fourth paragraph of div 1.</p>
  </div>
  <div class="card">
    <p>The first paragraph of div 2.</p>
    <p>The second paragraph of div 2.</p>
    <p>The third paragraph of div 2.</p>
    <p>The fourth paragraph of div 2.</p>
  </div>
</div>


问:
XML within an Android string resource?
I was wondering if I could place XML within /res/values/strings.xml? I ask this because I am checking for the XML data file for my application, if it does not exist yet then it creates it from the default contents that will be contained as a string resource.

Eclipse tries to change the less than and greater than tags to their corresponding HTML entities when using the GUI to edit the strings. Is eclipse on the right track? Because I should think that it will be written out into my file as HTML entities too. Could I use getText() rather than getString() to convert the entities back into tags?

答:
Yes you can, just use CDATA

<string name="stringName1"><![CDATA[bla]]></string>

Title: XML within an Android string resource?

Body:
Yes you can, just use CDATA

<string name="stringName1"><![CDATA[<html>bla</html>]]></string>


问:
How to See Required Library File Names in Ruby
How can I see the required library file name? e.g. path/to/file.rb or path/to/file.so

```<code>$ rails c
Loading development environment (Rails 4.2.7.1)
[1] pry(main)> require "readline"
=> false
</code>```

I would like to make sure the exact file path that is actually required, but don't know how to confirm the file path.

答:
Ruby has a pre-defined variable $" or $LOADED_FEATURES which contains the required modules

```<code>$LOADED_FEATURES
#=> ["enumerator.so", "thread.rb", "rational.so", ...]
</code>```

You could use grep to find "readline":

```<code>$LOADED_FEATURES.grep /readline/
#=> ["/Users/sos/.rbenv/versions/2.4.0/lib/ruby/2.4.0/x86_64-darwin15/readline.bundle"]
</code>```

Body:
How can I see the required library file name? e.g. path/to/file.rb or path/to/file.so

$ rails c
Loading development environment (Rails 4.2.7.1)
[1] pry(main)> require "readline"
=> false

I would like to make sure the exact file path that is actually required, but don't know how to confirm the file path.

Body:
Ruby has a pre-defined variable $" or $LOADED_FEATURES which contains the required modules

$LOADED_FEATURES
#=> ["enumerator.so", "thread.rb", "rational.so", ...]

You could use grep to find "readline":

$LOADED_FEATURES.grep /readline/
#=> ["/Users/sos/.rbenv/versions/2.4.0/lib/ruby/2.4.0/x86_64-darwin15/readline.bundle"]


问:
"unknown type name import" error in iOS
I Had tried to include swift ViewController File in to Objective-C project
but i unable to do it, it shows error like unknown type name import how to solve this please any one help for this issue.

Here I Send my Code and ScreenShot.

```<code>import UIKit
@objc class SigViewController2: UIViewController {

@IBOutlet weak var cameraBtn: UIButton!

@IBOutlet weak var imageBtn: UIButton!

@IBOutlet weak var settingsBtn: UIButton!

@IBOutlet weak var mediaBtn: UIButton!

override func viewDidLoad() {
    super.viewDidLoad()

    // Do any additional setup after loading the view, typically from a nib.
}
override func viewWillAppear(animated: Bool) {
    super.viewWillAppear(true)
    navigationController?.navigationBarHidden = false

    self.navigationItem.title = "Main";
}
override func supportedInterfaceOrientations() -> UIInterfaceOrientationMask {

    // Only allow Portrait
    return UIInterfaceOrientationMask.Portrait
}

override func preferredInterfaceOrientationForPresentation() -> UIInterfaceOrientation {

    // Only allow Portrait
    return UIInterfaceOrientation.Portrait
}
</code>```

答:
For Developers still looking for answer.

Importing Swift file inside Objective-c can cause this error, if it doesn't import properly.

Let's look at the the error first.

Let's try above KJTreeObjC.Swift file inside below Objective-C ViewController.

Solution:

You've to import it with the help of bridging header.

When you Created/Copied Swift file inside Objective-C project. It would've created a bridging header automatically.

Check Objective-C Generated Interface Header Name at Targets -> Build Settings.

That's the header name we will Import now.

You can check afterwards, error would've been gone instantly.

Title: "unknown type name import" error in iOS

Body:
I Had tried to include swift ViewController File in to Objective-C project
but i unable to do it, it shows error like unknown type name import how to solve this please any one help for this issue.

Here I Send my Code and ScreenShot.

import UIKit
@objc class SigViewController2: UIViewController {

@IBOutlet weak var cameraBtn: UIButton!

@IBOutlet weak var imageBtn: UIButton!

@IBOutlet weak var settingsBtn: UIButton!

@IBOutlet weak var mediaBtn: UIButton!

override func viewDidLoad() {
    super.viewDidLoad()

    // Do any additional setup after loading the view, typically from a nib.
}
override func viewWillAppear(animated: Bool) {
    super.viewWillAppear(true)
    navigationController?.navigationBarHidden = false

    self.navigationItem.title = "Main";
}
override func supportedInterfaceOrientations() -> UIInterfaceOrientationMask {

    // Only allow Portrait
    return UIInterfaceOrientationMask.Portrait
}

override func preferredInterfaceOrientationForPresentation() -> UIInterfaceOrientation {

    // Only allow Portrait
    return UIInterfaceOrientation.Portrait
}


问:
How to reload a Page from another class with Ionic3
I have 2 Folders. /HomePage and /SettingsPage.

/HomePage contains:

home.html

home.ts

The /SettingsPage contains:

settings.html

settings.ts

I want to "clean"/reload my HompePage (home.html) from settings.ts

I reload/refresh my settings.html with this:

```<code>this.navCtrl.setRoot(this.navCtrl.getActive().component);
</code>```

答:
You could use Events for that:</p>

```<code>import { Events } from 'ionic-angular';

// SettingsPage (publish an event when you need to reload the HomePage)
constructor(public events: Events) {}

shouldReload() {
  events.publish('shouldReloadData');
}

// HomePage (listen for the event to reload the page)
constructor(public events: Events) {
  events.subscribe('shouldReloadData', () => {
    // Reload the page here
  });
}
</code>```

Body:
I have 2 Folders. /HomePage and /SettingsPage.

/HomePage contains:

home.html

home.ts

The /SettingsPage contains:

settings.html

settings.ts

I want to "clean"/reload my HompePage (home.html) from settings.ts

I reload/refresh my settings.html with this:

this.navCtrl.setRoot(this.navCtrl.getActive().component);

Body:
You could use Events for that:

import { Events } from 'ionic-angular';

// SettingsPage (publish an event when you need to reload the HomePage)
constructor(public events: Events) {}

shouldReload() {
  events.publish('shouldReloadData');
}

// HomePage (listen for the event to reload the page)
constructor(public events: Events) {
  events.subscribe('shouldReloadData', () => {
    // Reload the page here
  });
}


问:
What is the cost/overhead of defining a type?
Is there any runtime cost or overhead for having defined too many types in C++? For example, is there any difference at all between these two piece of code:

```<code>int main()
{
    int x, y;
    double fx, fy;

    return 0;
}
</code>```

And:

```<code>template<typename T>
struct Point
{
    T x, y;
};

int main()
{
    Point<int> p;
    Point<double> fp;

    return 0;
}
</code>```

Imagine a code which has many templated types, so that at compile time it generates even more concrete types: is it going to have any impact at runtime? My main concern is about static memory consumption.

答:
On a typical implementation, types without a vtable are virtually free - they cease to exist completely at compile time, where member access is transformed into moves from/to memory with the relevant offsets.

Types with a vtable (so, stuff with virtual methods) do have a O(number_of_types) cost in static memory consumption, namely each type will have to have a separate vtable/RTTI data, plus the data needed by dynamic_cast to navigate complex class hierarchies; in a typical implementation, you may estimate this cost in something like 1 pointer per virtual method + 1 pointer to RTTI information + the size of the mangled class name + a handful of pointers connecting the data structures for dynamic_cast. (This besides the cost of the vtable pointer in each instance of such types)

Body:
Is there any runtime cost or overhead for having defined too many types in C++? For example, is there any difference at all between these two piece of code:

int main()
{
    int x, y;
    double fx, fy;

    return 0;
}

And:

template<typename T>
struct Point
{
    T x, y;
};

int main()
{
    Point<int> p;
    Point<double> fp;

    return 0;
}

Imagine a code which has many templated types, so that at compile time it generates even more concrete types: is it going to have any impact at runtime? My main concern is about static memory consumption.


问:
how to make AWS api gateway accept http instead of https
I have a Lambda function proxied by API Gateway. However, API Gateway only expose https and not http. I searched everywhere but looks like API Gateway is not possible to accept http.

So my question is how to translate http client calls to https and send to api gateway? I am asking because my client can only make http calls and they won't change.

答:
You can put a Cloudfront distribution in front of API Gateway with to following setup:

Origin Protocol Policy: HTTPS Only

Viewer Protocol Policy: HTTP and HTTPS

Forward Headers: None

Object Caching: Use Origin Cache Headers


问:
How do you switch between python 2 and 3, and vice versa?
I am reading How To Learn Python The Hard Way, which uses 2. Recently discovered Invent With Python, which uses 3.

Can I download python 3, and use it when I read Invent With Python, then switch back to python 2 when I want to read How To Learn Python The Hard Way. If so, how would I choose which version I use?

答:
In windows 10 it is a lot easier then what have been given by users above.

Install both the version in separate folders, and then go to environment variable and add the path for both the versions.

Now any time you want to run particular version, just change its order (path) and move it to top of other version, and then restart the cmd and type python this time, you will see that only that particular version of python will run.

For example in my case, I have two version of python one in anaconda(v3.0.6) and another is python 2.7

anytime I want to run the 2.7 i move its path above the anaconda version, as you can see in the screenshot above, and move it below when i want to run anaconda version.