问:
How do I make a heatmap in Cartopy
I am mapping latitude, longitude, and then a separate value on cartopy.

How do I make the points colored like a heatmap based the list called klist? I cant find any snippets of code where it will work with cartopy

That list has range of values that I want colored based on the how big the value is.

```<code># Define a Cartopy 'ordinary' lat-lon coordinate reference system.
crs_latlon = ccrs.PlateCarree()

def make_plot(projection_name, projection_crs):

    ax = plt.axes(projection=projection_crs)

# Set display limits to include a set region of latitude * longitude.
# (Note: Cartopy-specific).
    ax.set_extent((-65.0, -62, 44, 45.5), crs=crs_latlon)

# Add coastlines and meridians/parallels (Cartopy-specific).
    ax.coastlines(linewidth=0.2, color='black')
    ax.gridlines(crs=crs_latlon, linestyle='-')

# Mark some particular places with a small circle and a name label...
# Define some test points with latitude and longitude coordinates.
    #city_data = [('Halifax, NS', 44.67, -63.61)]

    plt.plot(lon,lat,marker='x', markersize=1.0, markeredgewidth=2.5,
             markerfacecolor='black',
             transform=crs_latlon)
# Add a title, and display.
    iplt.show("Mission #1: Attenuation Coeffiecient")

def main():
# Demonstrate with two different display projections.
    make_plot('Equidistant Cylindrical', ccrs.PlateCarree())

if __name__ == '__main__':
    main()
</code>```

答:
From what I can see, you would produce a heat map the same way you would produce a heat map in plain matplotlib. Just use pcolormesh (or pcolor or whatever) and with a properly defined meshgrid. Here, I modified @berna1111's answer to produce a color map instead of drawing circles on the map.

To avoid drawing outside the coastlines, you could use a masked array or use transparency, although the former would probably be best.

In the following example, I supply a heat_data that is a numpy array that contains the data that will be colour coded. I assume that this data is defined over the whole map range for convenience. Your data may differ.
Because I don't have the actual data, I create lat and lon arrays from the extent and the size of heat_data. In the main(), I generate some noise to fill heat_data and create the plot.

import cartopy.crs as ccrs
import matplotlib.pyplot as plt
import numpy as np

def make_plot(projection_name, projection_crs, extent, heat_data):
    """
    ?
    """
    fig = plt.figure()
    rect = 0.1, 0.1, 0.8, 0.8
    ax = fig.add_axes(rect, projection=projection_crs)

    # Set display limits to include a set region of latitude * longitude.
    # (Note: Cartopy-specific).
    ax.set_extent(extent, crs=projection_crs)

    # Add coastlines and meridians/parallels (Cartopy-specific).
    ax.coastlines(linewidth=0.2, color='black')
    ax.gridlines(crs=projection_crs, linestyle='-')

    lat = np.linspace(extent[0],extent[1],heat_data.shape[0])
    lon = np.linspace(extent[2],extent[3],heat_data.shape[1])
    Lat,Lon = np.meshgrid(lat,lon)
    ax.pcolormesh(Lat,Lon,np.transpose(heat_data))
    plt.savefig("Test_fig.pdf", bbox_inches='tight')

def main():
    #extent = (-65.0, -62, 44, 45.5)
    extent = (-90, -40, 30, 60)
    # Define some test points with latitude and longitude coordinates.
    #city_data = [('Halifax, NS', 44.67, -63.61, 'black'),
    #             ('Neighbour', 45, -63, 'blue'),
    #             ('Other_Place', 44.1, -64, 'red')]
    heat_data = np.random.normal(0.0,0.2,size=(100,150))

    # Demonstrate with two different display projections.
    # Define a Cartopy 'ordinary' lat-lon coordinate reference system.
    crs_latlon = ccrs.PlateCarree()
    make_plot('Equidistant Cylindrical', crs_latlon, extent, heat_data)
    #crs_ae = ccrs.LambertCylindrical()
    #make_plot('Lambert Cylindrical', crs_ae, extent, heat_data)

if __name__ == '__main__':
    main()
```

Title: How do I make a heatmap in Cartopy

Body:
I am mapping latitude, longitude, and then a separate value on cartopy.

How do I make the points colored like a heatmap based the list called klist? I cant find any snippets of code where it will work with cartopy

That list has range of values that I want colored based on the how big the value is.

# Define a Cartopy 'ordinary' lat-lon coordinate reference system.
crs_latlon = ccrs.PlateCarree()

def make_plot(projection_name, projection_crs):

    ax = plt.axes(projection=projection_crs)

# Set display limits to include a set region of latitude * longitude.
# (Note: Cartopy-specific).
    ax.set_extent((-65.0, -62, 44, 45.5), crs=crs_latlon)

# Add coastlines and meridians/parallels (Cartopy-specific).
    ax.coastlines(linewidth=0.2, color='black')
    ax.gridlines(crs=crs_latlon, linestyle='-')

# Mark some particular places with a small circle and a name label...
# Define some test points with latitude and longitude coordinates.
    #city_data = [('Halifax, NS', 44.67, -63.61)]

    plt.plot(lon,lat,marker='x', markersize=1.0, markeredgewidth=2.5,
             markerfacecolor='black',
             transform=crs_latlon)
# Add a title, and display.
    iplt.show("Mission #1: Attenuation Coeffiecient")

def main():
# Demonstrate with two different display projections.
    make_plot('Equidistant Cylindrical', ccrs.PlateCarree())

if __name__ == '__main__':
    main()


来源: stackexchange

问:
Appcelerator Studio: Cannot create a new project
I'm experiencing problems with Appcelerator Studio.
If I try to make a new project inside the workspace, I receive the following error:
"Error while reading/writing the .project file"

I tried to write outside the workspace. It doesn't create a Hello World project! Instead I have an empty project with only 3 files: CHANGELOG, LICENSE, manifest. Unable to add new models, views or controllers: the New command does nothing.

Any suggestions? Thanks in advance!

答:
You should try to reinstall Appcelerator Studio and make sure that you installed all the required tools.

Also try to update Appcelerator CLI tool.

ContentLicense: CC BY-SA 3.0


问:
jQuery if button is not pressed
I want to check wether a button is pressed in jQuery. If the button is pressed the page has to scroll down. If the button it not pressed the page shows an animation and once this is finished it has to scroll down.

Now I have this:

```<code>$('#btmmdl').click(function(){
    $(this).data('clicked', true);
});

if($('#btmmdl').data('clicked')){
    // Scroll down
} else {
    // Show animation and scroll down after 9 seconds
}
</code>```

Am I doing something wrong?

答:
Your problem is that click event is executed when is. You don't know when will user click on button. Therefore you have to add your if statement inside callback function and perform your task.

```<code>$('#btmmdl').click(function() {
    $(this).attr('data-clicked', !$(this).attr('data-clicked')); //Toggle status
    if ($(this).attr('data-clicked')) {
        // Scroll down
    } else {
        // Show animation and scroll down after 9 seconds
    }
});
</code>```

Each click will toggle mode. First click will do scroll, second will show animation, third again scroll, etc.

Title: jQuery if button is not pressed

Body:
I want to check wether a button is pressed in jQuery. If the button is pressed the page has to scroll down. If the button it not pressed the page shows an animation and once this is finished it has to scroll down.

Now I have this:

$('#btmmdl').click(function(){
    $(this).data('clicked', true);
});

if($('#btmmdl').data('clicked')){
    // Scroll down
} else {
    // Show animation and scroll down after 9 seconds
}

Am I doing something wrong?

Body:
Your problem is that click event is executed when is. You don't know when will user click on button. Therefore you have to add your if statement inside callback function and perform your task.

$('#btmmdl').click(function() {
    $(this).attr('data-clicked', !$(this).attr('data-clicked')); //Toggle status
    if ($(this).attr('data-clicked')) {
        // Scroll down
    } else {
        // Show animation and scroll down after 9 seconds
    }
});

Each click will toggle mode. First click will do scroll, second will show animation, third again scroll, etc.


问:
Panorama control truncating long titles
I'm trying to create a simple Windows Phone 7 app in which one of the pages uses a Panorama control. My control has five PanoramaItem children. Using the code below, the title is truncated on the fourth screen in the middle of the word "anyone." How can I make the Panorama control display the full title?

```<code><controls:Panorama Title="This is the longest title anyone has ever seen" >
</code>```

答: It may be related to the number of panes you have.</p>

ContentLicense: CC BY-SA 2.5

Title: Panorama control truncating long titles

Body:
I'm trying to create a simple Windows Phone 7 app in which one of the pages uses a Panorama control. My control has five PanoramaItem children. Using the code below, the title is truncated on the fourth screen in the middle of the word "anyone." How can I make the Panorama control display the full title?

<controls:Panorama Title="This is the longest title anyone has ever seen" >


问:
Ionic Package unable install
I have downloaded latest node version 4 and tried to install ionic.

But it was loading for long time in command prompt.

```<code>npm install ionic -g
</code>```

Then I have downloaded 0.10.38 and it started downloading.

Whether ionic supported only in the 0.10 version.

While Installing with higher version getting below error

```<code>npm ERR! Windows_NT 6.1.7600
npm ERR! argv "C:\\Program Files\\nodejs\\node.exe" "C:\\Program Files\\nodejs
node_modules\\npm\\bin\\npm-cli.js" "install" "ionic" "-g"
npm ERR! node v5.0.0
npm ERR! npm  v3.3.6

npm ERR! Callback called more than once.
npm ERR!
npm ERR! If you need help, you may report this error at:
npm ERR!     <https://github.com/npm/npm/issues>
C:\Users\<users>\AppData\Roaming\npm
└── (empty)

npm ERR! Windows_NT 6.1.7600
npm ERR! argv "C:\\Program Files\\nodejs\\node.exe" "C:\\Program Files\\nodejs
node_modules\\npm\\bin\\npm-cli.js" "install" "ionic" "-g"
npm ERR! node v5.0.0
npm ERR! npm  v3.3.6

npm ERR! Callback called more than once.
npm ERR!
npm ERR! If you need help, you may report this error at:
npm ERR!     <https://github.com/npm/npm/issues>
C:\Users\<users>\AppData\Roaming\npm
└── (empty)

npm ERR! Windows_NT 6.1.7600
npm ERR! argv "C:\\Program Files\\nodejs\\node.exe" "C:\\Program Files\\nodejs
node_modules\\npm\\bin\\npm-cli.js" "install" "ionic" "-g"
npm ERR! node v5.0.0
npm ERR! npm  v3.3.6

npm ERR! Callback called more than once.
npm ERR!
npm ERR! If you need help, you may report this error at:
npm ERR!     <https://github.com/npm/npm/issues>

npm ERR! Please include the following file with any support request:
npm ERR!     C:\Windows\system32\npm-debug.log
npm ERR! code 1
</code>```

答:
Hi I have a some problem like this one check this I hope this help you.

https://github.com/ionic-team/ionic-cli/issues/2477

Run this:

```<code>npm install --save-dev @ionic/app-scripts
</code>```

Title: Ionic Package unable install

Body:
I have downloaded latest node version 4 and tried to install ionic.

But it was loading for long time in command prompt.

npm install ionic -g

Then I have downloaded 0.10.38 and it started downloading.

Whether ionic supported only in the 0.10 version.

While Installing with higher version getting below error

npm ERR! Windows_NT 6.1.7600
npm ERR! argv "C:\\Program Files\\nodejs\\node.exe" "C:\\Program Files\\nodejs
node_modules\\npm\\bin\\npm-cli.js" "install" "ionic" "-g"
npm ERR! node v5.0.0
npm ERR! npm  v3.3.6

npm ERR! Callback called more than once.
npm ERR!
npm ERR! If you need help, you may report this error at:
npm ERR!     <https://github.com/npm/npm/issues>
C:\Users\<users>\AppData\Roaming\npm
└── (empty)

npm ERR! Windows_NT 6.1.7600
npm ERR! argv "C:\\Program Files\\nodejs\\node.exe" "C:\\Program Files\\nodejs
node_modules\\npm\\bin\\npm-cli.js" "install" "ionic" "-g"
npm ERR! node v5.0.0
npm ERR! npm  v3.3.6

npm ERR! Callback called more than once.
npm ERR!
npm ERR! If you need help, you may report this error at:
npm ERR!     <https://github.com/npm/npm/issues>
C:\Users\<users>\AppData\Roaming\npm
└── (empty)

npm ERR! Windows_NT 6.1.7600
npm ERR! argv "C:\\Program Files\\nodejs\\node.exe" "C:\\Program Files\\nodejs
node_modules\\npm\\bin\\npm-cli.js" "install" "ionic" "-g"
npm ERR! node v5.0.0
npm ERR! npm  v3.3.6

npm ERR! Callback called more than once.
npm ERR!
npm ERR! If you need help, you may report this error at:
npm ERR!     <https://github.com/npm/npm/issues>

npm ERR! Please include the following file with any support request:
npm ERR!     C:\Windows\system32\npm-debug.log
npm ERR! code 1

Body:
Hi I have a some problem like this one check this I hope this help you.

https://github.com/ionic-team/ionic-cli/issues/2477

Run this:

npm install --save-dev @ionic/app-scripts


问:
SQL query, field name paseed by reference vb.net
I'm having problems trying to make this work, I have this query on an application that Im writing in vb.net 2012:

```<code>Dim strSql As String = " SELECT * FROM Table_Master WHERE  field & "'= ('" & txtCadena.Text & "')"
</code>```

What I need is to have the option to choose the field that I'm querying writing the field name on a textbox.

答:
I finally made it doing this.</p>

```<code>Dim Query As String
Dimm DT As DataTable = New DataTable

Query = "select Actual, Description, Unit_of_measurement from Table_ARTIClES WHERE NUMPART = '" & txtPartNum.Text & "'"

Dim Table As SqlDataAdapter = New SqlDataAdapter(Query, conn)
Table.Fill(DT)

lblInventory.Text = DT.Rows(0)("Actual").ToString
</code>```

Body:
I'm having problems trying to make this work, I have this query on an application that Im writing in vb.net 2012:

Dim strSql As String = " SELECT * FROM Table_Master WHERE  field & "'= ('" & txtCadena.Text & "')"

What I need is to have the option to choose the field that I'm querying writing the field name on a textbox.

Body:
I finally made it doing this.

Dim Query As String
Dimm DT As DataTable = New DataTable

Query = "select Actual, Description, Unit_of_measurement from Table_ARTIClES WHERE NUMPART = '" & txtPartNum.Text & "'"

Dim Table As SqlDataAdapter = New SqlDataAdapter(Query, conn)
Table.Fill(DT)

lblInventory.Text = DT.Rows(0)("Actual").ToString


问:
Isolation Forest
I'm currently working on identifying outliers in my data set using the IsolationForest method in Python, but don't completely understand the example on sklearn:

http://scikit-learn.org/stable/auto_examples/ensemble/plot_isolation_forest.html#sphx-glr-auto-examples-ensemble-plot-isolation-forest-py

Specifically, what is the graph actually showing us? The observations have already been defined as normal/outliers -- so I'm assuming the shade of the contour plot indicates whether that observation is indeed an outlier (e.g., observations with higher anomaly scores lie in darker shaded areas?).

Lastly, how is the following section of code actually being used (specifically the y_pred functions)?

```<code># fit the model
clf = IsolationForest(max_samples=100, random_state=rng)
clf.fit(X_train)
y_pred_train = clf.predict(X_train)
y_pred_test = clf.predict(X_test)
y_pred_outliers = clf.predict(X_outliers)
</code>```

I'm guessing it was just provided for completeness in the event someone wants to print the output?

Thanks in advance for the help!

答:
For each observation, it tells whether or not (+1 or -1**) it should be considered as an outlier according to the fitted model.**

Simple Example Using Iris data

```<code>from sklearn.model_selection import train_test_split
from sklearn.datasets import load_iris
import numpy as np
import matplotlib.pyplot as plt
from sklearn.ensemble import IsolationForest

rng = np.random.RandomState(42)
data = load_iris()

X=data.data
y=data.target
X_outliers = rng.uniform(low=-4, high=4, size=(X.shape[0], X.shape[1]))

X_train, X_test, y_train, y_test = train_test_split( X, y, test_size=0.3, random_state=0)

clf = IsolationForest(random_state=0)
clf.fit(X_train)

y_pred_train = clf.predict(X_train)
y_pred_test = clf.predict(X_test)
y_pred_outliers = clf.predict(X_outliers)

print(y_pred_test)
print(y_pred_outliers)
</code>```

Result:

```<code>[-1 -1 -1 -1  1 -1  1  1  1  1  1  1  1  1  1  1  1  1  1 -1  1  1  1 -1
  1 -1 -1  1 -1  1  1  1  1  1  1  1 -1  1  1  1  1  1  1 -1  1]

[-1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1
 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1
 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1
 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1
 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1
 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1
 -1 -1 -1 -1 -1 -1]
</code>```

Interpretation:

The print(y_pred_test) returns 1 and -1. This means that some samples of X_test are not outliers and some are (source).

On the other hand, print(y_pred_outliers) return only -1. This means that all the samples (150 in total for iris data) of X_outliers are outliers.

Using your code

After your code just print the y_pred_outliers:

```<code># fit the model
clf = IsolationForest(max_samples=100, random_state=rng)
clf.fit(X_train)
y_pred_train = clf.predict(X_train)
y_pred_test = clf.predict(X_test)
y_pred_outliers = clf.predict(X_outliers)

print(y_pred_outliers)
</code>```

Title: Isolation Forest

Body:
I'm currently working on identifying outliers in my data set using the IsolationForest method in Python, but don't completely understand the example on sklearn:

http://scikit-learn.org/stable/auto_examples/ensemble/plot_isolation_forest.html#sphx-glr-auto-examples-ensemble-plot-isolation-forest-py

Specifically, what is the graph actually showing us? The observations have already been defined as normal/outliers -- so I'm assuming the shade of the contour plot indicates whether that observation is indeed an outlier (e.g., observations with higher anomaly scores lie in darker shaded areas?).

Lastly, how is the following section of code actually being used (specifically the y_pred functions)?

# fit the model
clf = IsolationForest(max_samples=100, random_state=rng)
clf.fit(X_train)
y_pred_train = clf.predict(X_train)
y_pred_test = clf.predict(X_test)
y_pred_outliers = clf.predict(X_outliers)

I'm guessing it was just provided for completeness in the event someone wants to print the output?

Thanks in advance for the help!

Body:
For each observation, it tells whether or not (+1 or -1**) it should be considered as an outlier according to the fitted model.**

Simple Example Using Iris data

from sklearn.model_selection import train_test_split
from sklearn.datasets import load_iris
import numpy as np
import matplotlib.pyplot as plt
from sklearn.ensemble import IsolationForest

rng = np.random.RandomState(42)
data = load_iris()

X=data.data
y=data.target
X_outliers = rng.uniform(low=-4, high=4, size=(X.shape[0], X.shape[1]))

X_train, X_test, y_train, y_test = train_test_split( X, y, test_size=0.3, random_state=0)

clf = IsolationForest(random_state=0)
clf.fit(X_train)

y_pred_train = clf.predict(X_train)
y_pred_test = clf.predict(X_test)
y_pred_outliers = clf.predict(X_outliers)

print(y_pred_test)
print(y_pred_outliers)

Result:

[-1 -1 -1 -1  1 -1  1  1  1  1  1  1  1  1  1  1  1  1  1 -1  1  1  1 -1
  1 -1 -1  1 -1  1  1  1  1  1  1  1 -1  1  1  1  1  1  1 -1  1]

[-1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1
 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1
 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1
 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1
 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1
 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1
 -1 -1 -1 -1 -1 -1]

Interpretation:

The print(y_pred_test) returns 1 and -1. This means that some samples of X_test are not outliers and some are (source).

On the other hand, print(y_pred_outliers) return only -1. This means that all the samples (150 in total for iris data) of X_outliers are outliers.

Using your code

After your code just print the y_pred_outliers:

# fit the model
clf = IsolationForest(max_samples=100, random_state=rng)
clf.fit(X_train)
y_pred_train = clf.predict(X_train)
y_pred_test = clf.predict(X_test)
y_pred_outliers = clf.predict(X_outliers)

print(y_pred_outliers)

ContentLicense: CC BY-SA 4.0


问:
Xamarin.Forms.Forms.Init(e) FileNotFoundExeception in Onlaunched
My Android Application works fine but when I launch my UWP application it crashes in the OnLaunched of my App.xaml.cs at the line of Xamarin.Forms.Forms.Init(e)

This is the error I'm getting:

System.IO.FileNotFoundException: 'Could not load file or assembly
  'clrcompression, Culture=neutral, PublicKeyToken=null'. The system
  cannot find the file specified.'

It completely makes my app crash, only thing I can see is my Splashscreen.

In IOS got a similar issue. It also show an error of FileNotFoundexception but it doesn't break and I can go past it. It show the error in my Main.cs at the line of UIApplication.Main(args, null, "AppDelegate");

答:
As discussed in the comments of the original post, and for anyone else that stumbles accross this thread with the same exception, in most instances the cause would appear to be related to Xlabs assemblies either not loading correctly, or having not been removed completely. This appears to have been an issue for at least the last half a year (past example of similar situation can be found Here).

The solution in this instance if you removed the xlab references but still get the error, is to delete the obj/bin/.VS folders from your project folder. Then for a UWP project, rebuild and then deploy. The issue should be resolved.


问:
Font scaling based on size of container
I'm having a hard time getting my head around font scaling.

I currently have a website with a body font-size of 100%. 100% of what though? This seems to compute out at 16 pixels.

I was under the impression that 100% would somehow refer to the size of the browser window, but apparently not because it's always 16 pixels whether the window is resized down to a mobile width or full-blown widescreen desktop.

How can I make the text on my site scale in relation to its container? I tried using em, but this doesn't scale either.

My reasoning is that things like my menu become squished when you resize, so I need to reduce the px font-size of .menuItem among other elements in relation to the width of the container. (For example, in the menu on a large desktop, 22px works perfectly. Move down to tablet width and 16px is more appropriate.)

I'm aware I can add breakpoints, but I really want the text to scale as well as having extra breakpoints, otherwise, I'll end up with hundreds of breakpoints for every 100pixels decrease in width to control the text.

答:
Try to use the fitText plugin, because Viewport sizes isn't the solution of this problem.

Just add the library:

```<code><script src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
</code>```

And change font-size for correct by settings the coefficient of text:

```<code>$("#text_div").fitText(0.8);
</code>```

You can set maximum and minimum values of text:

```<code>$("#text_div").fitText(0.8, { minFontSize: '12px', maxFontSize: '36px' });
</code>```

Title: Font scaling based on size of container

Body:
Try to use the fitText plugin, because Viewport sizes isn't the solution of this problem.

Just add the library:

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>

And change font-size for correct by settings the coefficient of text:

$("#text_div").fitText(0.8);

You can set maximum and minimum values of text:

$("#text_div").fitText(0.8, { minFontSize: '12px', maxFontSize: '36px' });


问:
How can I make a dynamic width for elements based on the screen size?
Here is my code:

.container{
  border:1px solid;
  width: 70%;
}

.el {
  border: 1px solid red;
  display: inline-block;
  min-width: 250px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="container">
  <div class="el">one</div>
  <div class="el">two</div>
  <div class="el">three</div>
  <div class="el">four</div>
  <div class="el">five</div>
  <div class="el">six</div>
  <div class="el">seven</div>
  <div class="el">eight</div>
</div></code>```

Please run the code snippet above, click on Full page button and resize the page. I want to divide div.container to equal parts.

So if there are three elements (div.el) in a row, then the width of them should be 33%. If two elements in a row, then the width should be 50%.

How can I do that? Noted that I don't want to use any framework like Bootstrap.

答:
Have a look to Media Queries

Example of use :

```<code>// Foo's original width is 100%
.foo {
    width: 100%
}

@media screen and (max-width: 100px){
    // Foo's width will be 50% when the view's width is below 100px
    .foo {
        width: 50%
    }
}

... OR ...

@media screen and (min-width: 100px){
    // Foo's width will be 50% when the view's width is over 100px
    .foo {
        width: 50%
    }
}
</code>```

Body:
Here is my code:

.container{
  border:1px solid;
  width: 70%;
}

.el {
  border: 1px solid red;
  display: inline-block;
  min-width: 250px;
}

one

two

three

four

five

six

seven

eight

Please run the code snippet above, click on Full page button and resize the page. I want to divide div.container to equal parts.

So if there are three elements (div.el) in a row, then the width of them should be 33%. If two elements in a row, then the width should be 50%.

How can I do that? Noted that I don't want to use any framework like Bootstrap.

Body:
Have a look to Media Queries

Example of use :

// Foo's original width is 100%
.foo {
    width: 100%
}

@media screen and (max-width: 100px){
    // Foo's width will be 50% when the view's width is below 100px
    .foo {
        width: 50%
    }
}

... OR ...

@media screen and (min-width: 100px){
    // Foo's width will be 50% when the view's width is over 100px
    .foo {
        width: 50%
    }
}


问:
Where can I get a lifecycle-action-token for aws autoscaling complete-lifecycle-action?
```aws autoscaling complete-lifecycle-action --lifecycle-action-token ???????? --lifecycle-hook-name ReadyForSoftwareInstall --auto-scaling-group-name  --lifecycle-action-result CONTINUE```

答:
Actually you can avoid to use the token and use the instance_id:</p>

```<code>aws autoscaling complete-lifecycle-action --auto-scaling-group-name my_service  --lifecycle-hook-name my_lifecycle_hook --instance-id my_instance_id --lifecycle-action-result CONTINUE
</code>```

Body:
Actually you can avoid to use the token and use the instance_id:

aws autoscaling complete-lifecycle-action --auto-scaling-group-name my_service  --lifecycle-hook-name my_lifecycle_hook --instance-id my_instance_id --lifecycle-action-result CONTINUE


问:
Link variable to data set in JMeter
I'm using JMeter 3.2 to create some performance tests.

I have a set up where a thread group has multiple threads (users) which perform multiple loops requesting a resource, form a server, every time.

Each of the threads go through an once only controller which retrieves a token from a server, which identifies the user, and is required on all subsequent requests. The token is different every time it is generated, I cannot store it in a data set (csv) as it would later be invalid.

I have a data set (.csv file) containing username and password of my test users.

So far so good.. Now the threads need to request a resource on the server requiring the token to be sent. It goes well the first time, but the second time it starts messing up. It seems like each iteration uses data from the next row in the dataset, but the token retrieved (from the once only controller) is not linked to row of data (username and password) used, so something like this happens:

thread1: data1/token1 - good

thread2: data2/token2 - good

Perhaps thread2 finishes first and starts the new iteration:

thread2: data1/token2 - error

thread1: data2/token1 - error

So my question is: how can I link the token retrieved to a row in data set (as a variable), so that the correct token will be sent every time that piece of data is used for a request?

Edit
I have an idea. Creating a Hashtable with some data, from the data set, as key and the token as value, but I have some issue. I've created the following code:

```<code>import java.util.Hashtable;
map = new Hashtable();
vars.putObject("map", map);
</code>```

but it cast the following error:

```<code>java.util.Hashtable cannot be cast to java.lang.String
</code>```

答:
I finally figured it out, though it might not be the most optimal solution. What I did is to create a property (variables won't work), which is a JSONObject. In this I can store an id (for my data) and the token linked to it. I transform it to a string and store it in the property.

In a preprocessor to the http request requiring the token I retrieve the property and parses it back to a JSONObject and can look up the token using the id.

Title: Link variable to data set in JMeter

Body:
I'm using JMeter 3.2 to create some performance tests.

I have a set up where a thread group has multiple threads (users) which perform multiple loops requesting a resource, form a server, every time.

Each of the threads go through an once only controller which retrieves a token from a server, which identifies the user, and is required on all subsequent requests. The token is different every time it is generated, I cannot store it in a data set (csv) as it would later be invalid.

I have a data set (.csv file) containing username and password of my test users.

So far so good.. Now the threads need to request a resource on the server requiring the token to be sent. It goes well the first time, but the second time it starts messing up. It seems like each iteration uses data from the next row in the dataset, but the token retrieved (from the once only controller) is not linked to row of data (username and password) used, so something like this happens:

thread1: data1/token1 - good

thread2: data2/token2 - good

Perhaps thread2 finishes first and starts the new iteration:

thread2: data1/token2 - error

thread1: data2/token1 - error

So my question is: how can I link the token retrieved to a row in data set (as a variable), so that the correct token will be sent every time that piece of data is used for a request?

Edit
I have an idea. Creating a Hashtable with some data, from the data set, as key and the token as value, but I have some issue. I've created the following code:

import java.util.Hashtable;
map = new Hashtable();
vars.putObject("map", map);

but it cast the following error:

java.util.Hashtable cannot be cast to java.lang.String


问:
Delphi: Logging UI events fired by user
I've been asked to put something in place into our programs in order to log somewhere what's happening on forms...

Logging something such ...clicked either this or that button, context menu, events fired on components and so on..

This mostly because we are dealing with legacy code, not quite structured unfortunately that we are adjusting/reviewing (Delphi XE10) when possible and we would like to track everything is happening (or most of it) from an user's point of view in order to
- being able to have a lead on what the user did when something mysterious happens
- being able to review the code where necessary when we have no idea of how thing have happened
- eventually speed issues

I'm not talking about exceptions or data logging...those are properly handled.

It's just about the UI.

Do you know if there is any library that might do something similar?
If not, how would you try to achieve this?

Code examples are happily accepted (even simple such as one/more form/s with a few buttons etc)

Thanks all!!!

答:
You could develop a non visual component and drop it on every form, but this would have to be a very complex component that either uses RTTI or peeks at windows messages to try to listen to what is happening to the other visual components in the form.

I see two simpler ways to do at least part of what you are asking...

1) Intercept calls to eventhandlers

Develop a component (somewhat simpler than the one I hinted at above) that hooks up to the events of the control classes you're interested in, logs the calls, and then forwards them to the original eventhandler procedures (if any).

Suppose you are interested in TWinControl.OnEnter and OnExit, TButton.OnClick and TEdit.OnChange...

```<code>TEventLogger = Class(TComponent)
Private
  Procedure Hookup(Const EventName: String; Const Component: TComponent; Const LoggingHandler: TNotifyEvent; Var Handler: TNotifyEvent);
Public
  Procedure Setup(Const Container: TComponent);
  Procedure HandleChange(Sender: TObject);
  Procedure HandleClick(Sender: TObject);
  Procedure HandleEnter(Sender: TObject);
  Procedure HandleExit(Sender: TObject);
End;

Procedure TEventLoggerHookup(Const EventName: String; Const Component: TComponent; Const LoggingHandler: TNotifyEvent; Var Handler: TNotifyEvent);
Begin
  if Assigned(Handler) Then
    Handlers.AddObject(Component.Name + ';' + EventName, Handler);
  Handler := LoggingHandler;
End;

Procedure TEventLogger.Setup(Const Container: TComponent);
Var
  i: Integer;
  c: TComponent;
Begin
  For i:=0 to Container.ComponentCount - 1 Do Begin
    c := Container.Components[i];
    if c Is TWinControl Then Begin
      Hookup('Enter',HandleEnter,TWinControl(c).OnEnter;
      Hookup('Exit',HandleExit,TWinControl(c).OnExit;
    End;
    If c Is TButton Then
      Hookup('Click',HandleClick,TButton(c).OnClick;
    If c Is TEdit Then
      Hookup('Change',HandleChange,TEdit(c).OnChange;
  End;
End;

Procedure TEventLogger.Procedure HandleChange(Sender: TObject);
Var
  s: String;
  i: Integer;
  e: TNotifyEvent;
Begin
  With Sender As TComponent Do Begin
    s := Name + ';Change';
    Log(s);
    i:= Handlers.IndexOf(s);
    If i <> -1 Then Begin
      e := Handlers.Objects[i];
      e(Sender);
    End;
  End;
End;
</code>```

This is not tested, but I think you got the point. Things to keep in mind:

Handlers is a simple TStringList... but you could do better with a generic TDictionary<Key,Value>. Of course you should create it and destroy it appropriately.

All the listed events are TNotifyEvents. But you can easily overload the Hookup procedure to handle other types ov events.

Setup must be executed when components have been already created and properties streamed in from the dfm. This may require you add some code to each form.

This technique may (and will) backfire if your application creates controls at runtime in a dynamic way, or if it messes with eventhandlers at runtime.

2) Use inheritance

Derive a new class of visual component for each one used that you want to log. All you need to define for each of these is a Log method and override the specific "event" methods your're interested in. For example:

```<code>TLogButton = class(TButton)
private
  procedure Log(Const Event: String);
protected
  procedure Click; override;
end;

TLogButton.Click;
begin
  Log('Click');
  Inherited;
end;
</code>```

You could then implement the Log method adding all the info you need (form and component class and name, or others). If you want to do something complex, then you will be better off delegating the log operation to a specialized class.

This is also not tested. Things to keep in mind:

To set it up, you can just use a massive Search and Replace... to
modify TButton in TLogButton... in both pas and dfm files (I do hope
you are using text dfm, if not you better convert them to text).

You'll have to add your new unit to the Interface section of all
forms that contain controls you're interested in

You should
register you new classes in a custom library so as to have them
available in the IDE, otherwise you won't be able to open your forms
at design time.

You have to do this for every class you're
interested in... which can become messy if the application uses many
different but similar classes of controls.

You have to know the
internals of the classes you want to log... not all methods are
overridable... many third party libraries do not come with sources...
it can be hell.

Conclusions

Overall... I'd probably go with the latter solution. It is basically easier to implement on a single class of controls, and you could probably already get some very useful tracing of user activity with just a bunch of classes. The former solution is a bit more sophisticated, and could probably be extended to cover some situations... but it is harder to test throughly and it is too risky if you do not know your code base very well.

Title: Delphi: Logging UI events fired by user

Body:
You could develop a non visual component and drop it on every form, but this would have to be a very complex component that either uses RTTI or peeks at windows messages to try to listen to what is happening to the other visual components in the form.

I see two simpler ways to do at least part of what you are asking...

1) Intercept calls to eventhandlers

Develop a component (somewhat simpler than the one I hinted at above) that hooks up to the events of the control classes you're interested in, logs the calls, and then forwards them to the original eventhandler procedures (if any).

Suppose you are interested in TWinControl.OnEnter and OnExit, TButton.OnClick and TEdit.OnChange...

TEventLogger = Class(TComponent)
Private
  Procedure Hookup(Const EventName: String; Const Component: TComponent; Const LoggingHandler: TNotifyEvent; Var Handler: TNotifyEvent);
Public
  Procedure Setup(Const Container: TComponent);
  Procedure HandleChange(Sender: TObject);
  Procedure HandleClick(Sender: TObject);
  Procedure HandleEnter(Sender: TObject);
  Procedure HandleExit(Sender: TObject);
End;

Procedure TEventLoggerHookup(Const EventName: String; Const Component: TComponent; Const LoggingHandler: TNotifyEvent; Var Handler: TNotifyEvent);
Begin
  if Assigned(Handler) Then
    Handlers.AddObject(Component.Name + ';' + EventName, Handler);
  Handler := LoggingHandler;
End;

Procedure TEventLogger.Setup(Const Container: TComponent);
Var
  i: Integer;
  c: TComponent;
Begin
  For i:=0 to Container.ComponentCount - 1 Do Begin
    c := Container.Components[i];
    if c Is TWinControl Then Begin
      Hookup('Enter',HandleEnter,TWinControl(c).OnEnter;
      Hookup('Exit',HandleExit,TWinControl(c).OnExit;
    End;
    If c Is TButton Then
      Hookup('Click',HandleClick,TButton(c).OnClick;
    If c Is TEdit Then
      Hookup('Change',HandleChange,TEdit(c).OnChange;
  End;
End;

Procedure TEventLogger.Procedure HandleChange(Sender: TObject);
Var
  s: String;
  i: Integer;
  e: TNotifyEvent;
Begin
  With Sender As TComponent Do Begin
    s := Name + ';Change';
    Log(s);
    i:= Handlers.IndexOf(s);
    If i <> -1 Then Begin
      e := Handlers.Objects[i];
      e(Sender);
    End;
  End;
End;

This is not tested, but I think you got the point. Things to keep in mind:

Handlers is a simple TStringList... but you could do better with a generic TDictionary<Key,Value>. Of course you should create it and destroy it appropriately.

All the listed events are TNotifyEvents. But you can easily overload the Hookup procedure to handle other types ov events.

Setup must be executed when components have been already created and properties streamed in from the dfm. This may require you add some code to each form.

This technique may (and will) backfire if your application creates controls at runtime in a dynamic way, or if it messes with eventhandlers at runtime.

2) Use inheritance

Derive a new class of visual component for each one used that you want to log. All you need to define for each of these is a Log method and override the specific "event" methods your're interested in. For example:

TLogButton = class(TButton)
private
  procedure Log(Const Event: String);
protected
  procedure Click; override;
end;

TLogButton.Click;
begin
  Log('Click');
  Inherited;
end;

You could then implement the Log method adding all the info you need (form and component class and name, or others). If you want to do something complex, then you will be better off delegating the log operation to a specialized class.

This is also not tested. Things to keep in mind:

To set it up, you can just use a massive Search and Replace... to
modify TButton in TLogButton... in both pas and dfm files (I do hope
you are using text dfm, if not you better convert them to text).

You'll have to add your new unit to the Interface section of all
forms that contain controls you're interested in

You should
register you new classes in a custom library so as to have them
available in the IDE, otherwise you won't be able to open your forms
at design time.

You have to do this for every class you're
interested in... which can become messy if the application uses many
different but similar classes of controls.

You have to know the
internals of the classes you want to log... not all methods are
overridable... many third party libraries do not come with sources...
it can be hell.

Conclusions

Overall... I'd probably go with the latter solution. It is basically easier to implement on a single class of controls, and you could probably already get some very useful tracing of user activity with just a bunch of classes. The former solution is a bit more sophisticated, and could probably be extended to cover some situations... but it is harder to test throughly and it is too risky if you do not know your code base very well.


问:
Jenkins on Windows - Matlab Doesn't Exit
The following command on Jenkins freestyle doesn't exit(runs forever) in Windows environment. However when I run the same command in CMD it works as expected.

```<code>matlab -nodesktop -nosplash -minimize -c "path_to_license" -r "run('path_to_run_all_tests_script')" -wait -logfile unittestlog.txt set output=%errorlevel% MORE unittestlog.txt EXIT %output%
</code>```

What am I doing wrong?

EDIT:

This is the Matlab script that the command calls:

```<code>import matlab.unittest.TestSuite;

disp('Hello from TestSuite');
try
    suite = TestSuite.fromPackage('test','IncludingSubpackages',true);
    results = run(suite);
    display(results);
catch e
    disp(getReport(e,'extended'));
    exit(1);
end
exit(any([results.Failed])+1);
</code>```

答:
Problem was related to licensing. Jenkins should be run by the same user who has Matlab license.

In addition to Sam Roberts answer: To change Jenkins's user, go to services in computer management, find the Jenkins service and change the user from properties.

Body:
The following command on Jenkins freestyle doesn't exit(runs forever) in Windows environment. However when I run the same command in CMD it works as expected.

matlab -nodesktop -nosplash -minimize -c "path_to_license" -r "run('path_to_run_all_tests_script')" -wait -logfile unittestlog.txt set output=%errorlevel% MORE unittestlog.txt EXIT %output%

What am I doing wrong?

EDIT:

This is the Matlab script that the command calls:

import matlab.unittest.TestSuite;

disp('Hello from TestSuite');
try
    suite = TestSuite.fromPackage('test','IncludingSubpackages',true);
    results = run(suite);
    display(results);
catch e
    disp(getReport(e,'extended'));
    exit(1);
end
exit(any([results.Failed])+1);


答:
Try using css flex-box. Apply display:flex; property for your container and manipulate the items .el inside that container using flex-grow: 1; to stretch them out to remaining width of screen and share the space accordingly.

.container{
  display: flex;
  width: 70%;
  border: 1px solid black;
}
.el {
  border: 1px solid red;
  flex-grow: 1;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="container">
  <div class="el">one</div>
  <div class="el">two</div>
  <div class="el">three</div>
  <div class="el">four</div>
  <div class="el">five</div>
  <div class="el">six</div>
  <div class="el">seven</div>
  <div class="el">eight</div>
</div></code>```

CodePen example: https://codepen.io/CapySloth/pen/LLBgEB

Title: How can I make a dynamic width for elements based on the screen size?

Body:
Try using css flex-box. Apply display:flex; property for your container and manipulate the items .el inside that container using flex-grow: 1; to stretch them out to remaining width of screen and share the space accordingly.

.container{
  display: flex;
  width: 70%;
  border: 1px solid black;
}
.el {
  border: 1px solid red;
  flex-grow: 1;
}

<div class="container">
  <div class="el">one</div>
  <div class="el">two</div>
  <div class="el">three</div>
  <div class="el">four</div>
  <div class="el">five</div>
  <div class="el">six</div>
  <div class="el">seven</div>
  <div class="el">eight</div>
</div>

CodePen example: https://codepen.io/CapySloth/pen/LLBgEB


问:
how to get previous value of textbox in jquery on change event

 $(".whitebox").on('change', function () {
       var previousAmt = $(this).data("old"); //  i want previous value
        var id = this.id;
        var slpitid = id.split("_");

        var checkboxid = "#chck_" + slpitid[0];
        if ($(checkboxid).is(':checked')) {
            var tipFlag = true;
        }
        else {
            var tipFlag = false;
        }

        if (tipFlag === true)
        {
            $("#amounttipchange").modal('show');
        }
        //alert(previousAmount);
    });```

i want to store previous value on change event how can i perform in jquery  i am not able to store value using $(this).data("old"); any help will be appreciated

答:
var prevVal = $('input').val(); //init val
var valuesHistory = [prevVal];
$('input').data('prevData', prevVal);

$('input').on('change', function() {
  console.log('prev value from data: ', $(this).data('prevData'));
  console.log('prev value from var: ', prevVal);
  console.log('log: ', valuesHistory);
  valuesHistory.push($('input').val());
  $('input').data('prevData', $('input').val());
  prevVal = $(this).val();
});
// you can also get the prev value, like that valuesHistory[valuesHistory.length-2];```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text"></code>```

Body:
 $(".whitebox").on('change', function () {
       var previousAmt = $(this).data("old"); //  i want previous value
        var id = this.id;
        var slpitid = id.split("_");

        var checkboxid = "#chck_" + slpitid[0];
        if ($(checkboxid).is(':checked')) {
            var tipFlag = true;
        }
        else {
            var tipFlag = false;
        }

        if (tipFlag === true)
        {
            $("#amounttipchange").modal('show');
        }
        //alert(previousAmount);
    });

i want to store previous value on change event how can i perform in jquery  i am not able to store value using $(this).data("old"); any help will be appreciated

Body:
var prevVal = $('input').val(); //init val
var valuesHistory = [prevVal];
$('input').data('prevData', prevVal);

$('input').on('change', function() {
  console.log('prev value from data: ', $(this).data('prevData'));
  console.log('prev value from var: ', prevVal);
  console.log('log: ', valuesHistory);
  valuesHistory.push($('input').val());
  $('input').data('prevData', $('input').val());
  prevVal = $(this).val();
});
// you can also get the prev value, like that valuesHistory[valuesHistory.length-2];

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text">


问:
Why does an attribute has a method?
I use pytorch define a Variable x, compute and get its gradient x.grad, meaning grad is an attribute of instance x. But, I can use x.grad.data.zero_() to set x.grad to zero meaning that data.zero_() is method of x.grad. Why does an attribute has a method? Thanks a lot.</p>

答: It will be just an object attribute, for example we can have an attribute of type String. And we all now String have his own methods including the method that prints out the value of itself</p>

Title: Why does an attribute has a method?


问:
Faster way to query Access table
I have two access tables, A and B:

```<code>Table A
Identifier BenefitBase    PlanNav
1        131368.46      131368.46
2        201768.8       201768.79
3        54057.46       54057.46
4        7397.51        7397.51
5        9931.4         9931.4
6        178200         178200
Table B
p      ValidityDate LockInAmount
1      2016-4       3.82
2      2016-4       19.97
3      2016-4       26.85
4      2016-6       34.95
</code>```

I just want to create a query which extracts records from B where the "p" ID is not found in table A.
My current code is:

```<code>SELECT B.p, B.ValidityDate, B.LockInAmount
FROM B
WHERE (((B.p) Not In (select Identifier from A)));
</code>```

Now to me, this code should work fine. However, because the tables are so large (B consists  of 486,000 rows (the "p"'s repeats in this table for different dates) whereas A consists of circa 19,000), whenever I run the query, access fills the query progress bar but freezes when near full.

Is there another way to do this?

Thanks

答:
You could "reverse" the seek - first find those that have a match, then exclude these from Table B:</p>

```<code>Select B.*
From B
Where B.ID Not In
    (Select A.Id
    From A, B
    Where A.ID = B.ID)
</code>```

Title: Faster way to query Access table

Body:
I have two access tables, A and B:

Table A
Identifier BenefitBase    PlanNav
1        131368.46      131368.46
2        201768.8       201768.79
3        54057.46       54057.46
4        7397.51        7397.51
5        9931.4         9931.4
6        178200         178200
Table B
p      ValidityDate LockInAmount
1      2016-4       3.82
2      2016-4       19.97
3      2016-4       26.85
4      2016-6       34.95

I just want to create a query which extracts records from B where the "p" ID is not found in table A.
My current code is:

SELECT B.p, B.ValidityDate, B.LockInAmount
FROM B
WHERE (((B.p) Not In (select Identifier from A)));

Now to me, this code should work fine. However, because the tables are so large (B consists  of 486,000 rows (the "p"'s repeats in this table for different dates) whereas A consists of circa 19,000), whenever I run the query, access fills the query progress bar but freezes when near full.

Is there another way to do this?

Thanks

Body:
You could "reverse" the seek - first find those that have a match, then exclude these from Table B:

Select B.*
From B
Where B.ID Not In
    (Select A.Id
    From A, B
    Where A.ID = B.ID)


问:
Shell script to check if user exist in remote server
I have script to check remote servers if user exist, but it only checks the first user. The script reads a text file for server list and does SSH to each server and then checks if id exist:

export users

for SERVER in `cat ./serverlist.txt`
do
        ssh $SERVER <<+
        set -A users "John" "Mary" "Joe" "Ana" "Jake" "Jana" "Ben"
        for ids in {0..6}
        do
          id ${users[$ids]}
        done
+
done ```

Please help

答:
Use '+' to prevent the local shell expands variables in the here document.

```<code>for SERVER in `cat ./serverlist.txt`
do
        ssh $SERVER <<'+'
        set -A users "John" "Mary" "Joe" "Ana" "Jake" "Jana" "Ben"
        for ids in {0..6}
        do
          id ${users[$ids]}
        done
+
done
</code>```

FYI.

```<code>for server in `cat ./serverlist.txt`
do
        ssh -- "$server" <<'+'
        set -A ids "John" "Mary" "Joe" "Ana" "Jake" "Jana" "Ben"
        for id in "${ids[@]}"
        do
          id "$id"
        done
+
done
</code>```

Body:
I have script to check remote servers if user exist, but it only checks the first user. The script reads a text file for server list and does SSH to each server and then checks if id exist:

export users

for SERVER in `cat ./serverlist.txt`
do
        ssh $SERVER <<+
        set -A users "John" "Mary" "Joe" "Ana" "Jake" "Jana" "Ben"
        for ids in {0..6}
        do
          id ${users[$ids]}
        done
+
done

Please help

Body:
Use '+' to prevent the local shell expands variables in the here document.

for SERVER in `cat ./serverlist.txt`
do
        ssh $SERVER <<'+'
        set -A users "John" "Mary" "Joe" "Ana" "Jake" "Jana" "Ben"
        for ids in {0..6}
        do
          id ${users[$ids]}
        done
+
done

FYI.

for server in `cat ./serverlist.txt`
do
        ssh -- "$server" <<'+'
        set -A ids "John" "Mary" "Joe" "Ana" "Jake" "Jana" "Ben"
        for id in "${ids[@]}"
        do
          id "$id"
        done
+
done


问:
Mongo readpreference Secondarypreferred
We deployed MongoDB on EC2 with r3.8xlarge with 10000 IOPS. We are running a replicaset with 1 primary, 1 secondary, and 1 arbiter. In our applications we have readPreference set to secondaryPreferred.

Now, I am watching the EBS Read Throughput metrics on EBS for Mongo instances. I can see it's hitting 10k IOPs on the Mongo Primary node which is surprising for me; I see spikes on the secondary node which is obvious, but spikes on Primary are what is confusing me?

Why do I see spikes on the Primary mongo node EBS, even though I set readPreference to be secondaryPreferred?

答:
Just remind you

In most situations, operations read from secondary members but if no secondary members are available, operations read from the primary.

In your case please confirm your secondary node still alive.

And what is driver you used to connect mongodb? Node, Python, Java, ..?

I'm having same issues with Mongo driver for Node, and i submitted a ticket to Mongo.
You can check in here:
NODE-1049

Title: Mongo readpreference Secondarypreferred


问:
MVC5 ComponentModel.DataAnnotation is not working
Please tell me why ComponentModel.DataAnnotations is not working here i have done every thing but in vain so tell me where i have mistakes in this code. here i am posting my view along with model. </p>

```<code><script src="~/Scripts/jquery-1.8.2.min.js"></script>
<script src="~/Scripts/jquery.validate.min.js"></script>
<script src="~/Scripts/jquery.validate.unobtrusive.min.js"></script>
<form>

    <div id="par" class="form-horizontal">
        <hr />

        @Html.ValidationSummary(true)

        <div class="form-group">
            @Html.LabelFor(model => model.BrandCode, htmlAttributes: new { @class = "control-label col-md-2" })

            <div class="col-md-10">
                @Html.EditorFor(model => model.BrandCode, new { @class = "form-control" })
                @Html.ValidationMessageFor(model => model.BrandCode, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.ProductSubGroupCode, new { @class = "control-label col-md-2 col-ld-2 col-sd-2" })

            <div class="col-md-10">
                @(Html.Kendo().ComboBoxFor(model => model.ProductSubGroupCode)

              .DataTextField("ProductSubGroupName")
              .DataValueField("ProductSubGroupCode")
              .DataSource(d => d.Read(r => r.Action("GetProductSubGroup", "Product")))
                      .Placeholder("Select Product Sub Group...")
                      .Suggest(true)
                      .HighlightFirst(true)
                )
                @Html.ValidationMessageFor(model => model.ProductSubGroupCode, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.ProductGroupCode, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @(Html.Kendo().ComboBoxFor(model => model.ProductGroupCode)
                .MinLength(100)
              .DataTextField("ProductGroupName")
              .DataValueField("ProductGroupCode")
      .DataSource(d => d.Read(r => r.Action("GetProductGroup", "Product")))
                      .Placeholder("Select Product Group...")
                      .Suggest(true)
                      .HighlightFirst(true)
                )
                @Html.ValidationMessageFor(model => model.ProductGroupCode, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.BrandName, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.BrandName, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.BrandName, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.BrandDescription, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.BrandDescription, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.BrandDescription, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.Active, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.CheckBoxFor(model => model.Active)
                @Html.ValidationMessageFor(model => model.Active, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.SortOrder, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.SortOrder, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.SortOrder, "", new { @class = "text-danger" })
            </div>
        </div>

    </div>

    <div class="form-group">
        <div class="col-md-offset-2 col-md-10">
            <input type="submit" value="Create" id="Save" class="btn btn-info" />
            <p id="content"></p>
        </div>
    </div>

</form>
</code>```

<p>This is the model </p>

```<code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ComponentModel.DataAnnotations;
using System.Web.Mvc;

public class BrandViewModels
    {

        [Display(Name = "Brand Code")]
        [Required(ErrorMessage = "Brand Code is required")]
        [RegularExpression(@"(\S)+", ErrorMessage = "White space is not allowed.")]
        [Remote("IsUniqueBrandCode", "Product", AdditionalFields = "BrandCode", HttpMethod = "POST", ErrorMessage = "Brand Code already exists.")]
        public string BrandCode { get; set; }
        public int CompanyId { get; set; }
        public List<ProductSubGroupList> ProductSubGroupList { get; set; }
        public List<ProductGroupList> ProductGroupList { get; set; }

        [Required(ErrorMessage = "Please select product group")]
        [Display(Name = "Product Group")]
        public string ProductGroupCode { get; set; }

        [Required(ErrorMessage = "Please select product sub group")]
        [Display(Name = "Product Sub Group")]
        public string ProductSubGroupCode { get; set; }

        [Required(ErrorMessage = "Brand name is required")]
        [Display(Name = "Brand Name")]
        public string BrandName { get; set; }

        [Required(ErrorMessage = "Description is required")]
        [Display(Name = "Description")]
        public string BrandDescription { get; set; }

        [Display(Name = "Active")]
        public bool Active { get; set; }

        [Display(Name = "Sort Order")]
        [Required(ErrorMessage = "Sorting order is required")]
        public int? SortOrder { get; set; }

    }
</code>```

答:
Here is my code Working perfect i seen your Code you may have these Error,

you should use @using (Html.BeginForm()) instead of <form>

@Html.ValidationSummary(false) in place of @Html.ValidationSummary(true)
please see my Code.

```<code>           <div class="container">
            @using (Html.BeginForm())
            {
                @Html.AntiForgeryToken()

                <div class="form-horizontal">
                    <h4>mymodel</h4>
                    <hr />
                    @Html.ValidationSummary(false)

                    <div class="form-group">
                        @Html.LabelFor(model => model.id, new { @class = "control-label col-md-2" })
                        <div class="col-md-10">
                            @Html.EditorFor(model => model.id)
                            @Html.ValidationMessageFor(model => model.id)
                        </div>
                    </div>
                    <div class="form-group">
                        @Html.LabelFor(model => model.name, new { @class = "control-label col-md-2" })
                        <div class="col-md-10">
                            @Html.EditorFor(model => model.name)
                            @Html.ValidationMessageFor(model => model.name)
                        </div>
                    </div>

                    <div class="form-group">
                        <div class="col-md-offset-2 col-md-10">
                            <input type="submit" value="Create" class="btn btn-default" />
                        </div>
                    </div>
                </div>
            }
        </div>
        <div>
            @Html.ActionLink("Back to List", "Index")
        </div>
        <script src="~/Scripts/jquery-1.10.2.min.js"></script>
        <script src="~/Scripts/jquery.validate.min.js"></script>
        <script src="~/Scripts/jquery.validate.unobtrusive.min.js"></script>
</code>```

Body:
Please tell me why ComponentModel.DataAnnotations is not working here i have done every thing but in vain so tell me where i have mistakes in this code. here i am posting my view along with model.

<form>

        @Html.ValidationSummary(true)

            @Html.LabelFor(model => model.BrandCode, htmlAttributes: new { @class = "control-label col-md-2" })

                @Html.EditorFor(model => model.BrandCode, new { @class = "form-control" })
                @Html.ValidationMessageFor(model => model.BrandCode, "", new { @class = "text-danger" })

            @Html.LabelFor(model => model.ProductSubGroupCode, new { @class = "control-label col-md-2 col-ld-2 col-sd-2" })

                @(Html.Kendo().ComboBoxFor(model => model.ProductSubGroupCode)

              .DataTextField("ProductSubGroupName")
              .DataValueField("ProductSubGroupCode")
              .DataSource(d => d.Read(r => r.Action("GetProductSubGroup", "Product")))
                      .Placeholder("Select Product Sub Group...")
                      .Suggest(true)
                      .HighlightFirst(true)
                )
                @Html.ValidationMessageFor(model => model.ProductSubGroupCode, "", new { @class = "text-danger" })

            @Html.LabelFor(model => model.ProductGroupCode, htmlAttributes: new { @class = "control-label col-md-2" })

                @(Html.Kendo().ComboBoxFor(model => model.ProductGroupCode)
                .MinLength(100)
              .DataTextField("ProductGroupName")
              .DataValueField("ProductGroupCode")
      .DataSource(d => d.Read(r => r.Action("GetProductGroup", "Product")))
                      .Placeholder("Select Product Group...")
                      .Suggest(true)
                      .HighlightFirst(true)
                )
                @Html.ValidationMessageFor(model => model.ProductGroupCode, "", new { @class = "text-danger" })

            @Html.LabelFor(model => model.BrandName, htmlAttributes: new { @class = "control-label col-md-2" })

                @Html.EditorFor(model => model.BrandName, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.BrandName, "", new { @class = "text-danger" })

            @Html.LabelFor(model => model.BrandDescription, htmlAttributes: new { @class = "control-label col-md-2" })

                @Html.EditorFor(model => model.BrandDescription, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.BrandDescription, "", new { @class = "text-danger" })

            @Html.LabelFor(model => model.Active, htmlAttributes: new { @class = "control-label col-md-2" })

                @Html.CheckBoxFor(model => model.Active)
                @Html.ValidationMessageFor(model => model.Active, "", new { @class = "text-danger" })

            @Html.LabelFor(model => model.SortOrder, htmlAttributes: new { @class = "control-label col-md-2" })

                @Html.EditorFor(model => model.SortOrder, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.SortOrder, "", new { @class = "text-danger" })

            <input type="submit" value="Create" id="Save" class="btn btn-info" />

</form>

This is the model

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ComponentModel.DataAnnotations;
using System.Web.Mvc;

public class BrandViewModels
    {

        [Display(Name = "Brand Code")]
        [Required(ErrorMessage = "Brand Code is required")]
        [RegularExpression(@"(\S)+", ErrorMessage = "White space is not allowed.")]
        [Remote("IsUniqueBrandCode", "Product", AdditionalFields = "BrandCode", HttpMethod = "POST", ErrorMessage = "Brand Code already exists.")]
        public string BrandCode { get; set; }
        public int CompanyId { get; set; }
        public List<ProductSubGroupList> ProductSubGroupList { get; set; }
        public List<ProductGroupList> ProductGroupList { get; set; }

        [Required(ErrorMessage = "Please select product group")]
        [Display(Name = "Product Group")]
        public string ProductGroupCode { get; set; }

        [Required(ErrorMessage = "Please select product sub group")]
        [Display(Name = "Product Sub Group")]
        public string ProductSubGroupCode { get; set; }

        [Required(ErrorMessage = "Brand name is required")]
        [Display(Name = "Brand Name")]
        public string BrandName { get; set; }

        [Required(ErrorMessage = "Description is required")]
        [Display(Name = "Description")]
        public string BrandDescription { get; set; }

        [Display(Name = "Active")]
        public bool Active { get; set; }

        [Display(Name = "Sort Order")]
        [Required(ErrorMessage = "Sorting order is required")]
        public int? SortOrder { get; set; }

    }

Body:
Here is my code Working perfect i seen your Code you may have these Error,

you should use @using (Html.BeginForm()) instead of <form>

@Html.ValidationSummary(false) in place of @Html.ValidationSummary(true)
please see my Code.

           <div class="container">
            @using (Html.BeginForm())
            {
                @Html.AntiForgeryToken()

                <div class="form-horizontal">
                    <h4>mymodel</h4>
                    <hr />
                    @Html.ValidationSummary(false)

                    <div class="form-group">
                        @Html.LabelFor(model => model.id, new { @class = "control-label col-md-2" })
                        <div class="col-md-10">
                            @Html.EditorFor(model => model.id)
                            @Html.ValidationMessageFor(model => model.id)
                        </div>
                    </div>
                    <div class="form-group">
                        @Html.LabelFor(model => model.name, new { @class = "control-label col-md-2" })
                        <div class="col-md-10">
                            @Html.EditorFor(model => model.name)
                            @Html.ValidationMessageFor(model => model.name)
                        </div>
                    </div>

                    <div class="form-group">
                        <div class="col-md-offset-2 col-md-10">
                            <input type="submit" value="Create" class="btn btn-default" />
                        </div>
                    </div>
                </div>
            }
        </div>
        <div>
            @Html.ActionLink("Back to List", "Index")
        </div>
        <script src="~/Scripts/jquery-1.10.2.min.js"></script>
        <script src="~/Scripts/jquery.validate.min.js"></script>
        <script src="~/Scripts/jquery.validate.unobtrusive.min.js"></script>


问:
ThreadLocal - Is it required if we are setting the value in constructor?
I have a class, MyThread which implements Callable <String>. The class has a constructor which takes  parameters like a blockingqueue and others. In my main class, I instantiate this class, MyThread,  with a new blocking queue and other parameters. Also, I maintain two maps, one to keep MyThread reference with one of unique parameter as key and other to keep blocking queue reference with the same unique key.

During the process, I get this blocking queue from the hashmap, add my custom message and take the corresponding MyThread instance and submit to ThreadPoolTaskExecutor (Spring version).

As far as I understand, each thread should get its own copy of values (like blocking queue etc), as am passing them during the construction and creating a thread later using ThreadPoolTaskExecutor.submit(myThreadObj). I was just wondering if someone could confirm if that is true OR whether I am required to use ThreadLocal in this scenario. So far with the testing, I did not encounter problem, but then I am yet to do the load testing.

Thanks in advance.

答: You have effectively reinvented ThreadLocal.  Enjoy!</p>


问:
Cannot find symbol variable activity_main
I am new. Whenever i try to build and run this code this message appears.

Here is the XML code:

```<code>xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context="com.example.android.justjava.MainActivity">

<TextView
    android:id="@+id/quantity_text_view"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="quantity"
    android:textAllCaps="true"
    android:textSize="16sp"
    android:textColor="@android:color/black"
    android:layout_marginLeft="16dp"
    android:layout_marginTop="16dp"/>

<TextView
    android:id="@+id/zero_text_view"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="0"
    android:layout_below="@+id/quantity_text_view"
    android:textSize="16sp"
    android:textColor="@android:color/black"
    android:layout_marginLeft="16dp"
    android:layout_marginTop="16dp"/>

<Button
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="order"
    android:textAllCaps="true"
    android:layout_below="@+id/zero_text_view"
    android:layout_marginLeft="16dp"
    android:layout_marginTop="16dp"
    android:onClick="submitOrder"/>
</code>```

Here is the Java code:

/**  * IMPORTANT: Add your package below. Package name can be found in
  the project's AndroidManifest.xml file.  * This is the package name
  our example uses:  *  * package com.example.android.justjava;   *  */

import android.R; import android.os.Bundle; import
  android.support.v7.app.AppCompatActivity; import android.view.View;
  import android.widget.TextView;

import static com.example.android.justjava.R.id.quantity_text_view;

/**  * This app displays an order form to order coffee.  */ public
  class MainActivity extends AppCompatActivity {

```<code>@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main_activity);
}

/**
 * This method is called when the order button is clicked.
 */
public void submitOrder(View view) {
    display(1);
}

/**
 * This method displays the given quantity value on the screen.
 */
private void display(int number) {
    TextView quantityTextView = (TextView) findViewById(R.id/quantity_text_view);
    quantityTextView.setText("" + number);
} }
</code>```

Here is the pic of the error:

https://i.stack.imgur.com/tlrUi.png

Please Help me

答:
Check your xml file name.

Check your imports statement

Clean and build the project again.

if above does not work then  Delete the R file and clean it

Body:
I am new. Whenever i try to build and run this code this message appears.

Here is the XML code:

xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context="com.example.android.justjava.MainActivity">

<TextView
    android:id="@+id/quantity_text_view"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="quantity"
    android:textAllCaps="true"
    android:textSize="16sp"
    android:textColor="@android:color/black"
    android:layout_marginLeft="16dp"
    android:layout_marginTop="16dp"/>

<TextView
    android:id="@+id/zero_text_view"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="0"
    android:layout_below="@+id/quantity_text_view"
    android:textSize="16sp"
    android:textColor="@android:color/black"
    android:layout_marginLeft="16dp"
    android:layout_marginTop="16dp"/>

<Button
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="order"
    android:textAllCaps="true"
    android:layout_below="@+id/zero_text_view"
    android:layout_marginLeft="16dp"
    android:layout_marginTop="16dp"
    android:onClick="submitOrder"/>

Here is the Java code:

/**  * IMPORTANT: Add your package below. Package name can be found in
  the project's AndroidManifest.xml file.  * This is the package name
  our example uses:  *  * package com.example.android.justjava;   *  */

import android.R; import android.os.Bundle; import
  android.support.v7.app.AppCompatActivity; import android.view.View;
  import android.widget.TextView;

import static com.example.android.justjava.R.id.quantity_text_view;

/**  * This app displays an order form to order coffee.  */ public
  class MainActivity extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main_activity);
}

/**
 * This method is called when the order button is clicked.
 */
public void submitOrder(View view) {
    display(1);
}

/**
 * This method displays the given quantity value on the screen.
 */
private void display(int number) {
    TextView quantityTextView = (TextView) findViewById(R.id/quantity_text_view);
    quantityTextView.setText("" + number);
} }

Here is the pic of the error:

https://i.stack.imgur.com/tlrUi.png

Please Help me


问:
How to Redirect to another php file using javascript
Okay, so here's my code

```<code><?php
$cn = new mysqli ("localhost", "root", "root", "dbsam");
$username = isset ($_POST['username']) ? $_POST['username']:"";
$password = isset ($_POST['password']) ? $_POST['password']:"";
$sql = "SELECT * FROM tbluser WHERE username=? AND password=?";
$upass = hash("SHA256", $password);
$qry = $cn->prepare($sql);
$qry->bind_param("ss", $username, $upass);
$qry->execute();
$qry->fetch();
if ($qry->num_rows()==1) {
    echo "Logged in!";
}
else {
    echo "<script>alert('Account did not match the database records!')</script>>";
    header ("location: login.php");
}
?>
</code>```

If the username and password did not match, an alert box will appear. So the problem is that it doesn't appear anymore it only executes the header that I put under it but if I remove the header, the alert dialog box will appear. I want the alert box to appear then the user will be redirected to the log-in page after that. How can I do that? Great Thanks!

答:
You can set document.location, inside a script tag.
Something like

```<code><script> document.location = 'login.php'; </script>
</code>```

Beside the answer to the direct question, I feel like you will need a timeout, or something more complex to handle the time spent reading the alert.

Body:
Okay, so here's my code

<?php
$cn = new mysqli ("localhost", "root", "root", "dbsam");
$username = isset ($_POST['username']) ? $_POST['username']:"";
$password = isset ($_POST['password']) ? $_POST['password']:"";
$sql = "SELECT * FROM tbluser WHERE username=? AND password=?";
$upass = hash("SHA256", $password);
$qry = $cn->prepare($sql);
$qry->bind_param("ss", $username, $upass);
$qry->execute();
$qry->fetch();
if ($qry->num_rows()==1) {
    echo "Logged in!";
}
else {
    echo ">";
    header ("location: login.php");
}
?>

If the username and password did not match, an alert box will appear. So the problem is that it doesn't appear anymore it only executes the header that I put under it but if I remove the header, the alert dialog box will appear. I want the alert box to appear then the user will be redirected to the log-in page after that. How can I do that? Great Thanks!

Body:
You can set document.location, inside a script tag.
Something like

<script> document.location = 'login.php'; </script>

Beside the answer to the direct question, I feel like you will need a timeout, or something more complex to handle the time spent reading the alert.


问:
Set timeout in Alamofire
I am using Alamofire 4.0.1 and I want to set a timeout for my request. I tried the solutions gived in this question:

In the first case, it throws a NSURLErrorDomain (timeout is set correctly):

```<code>let configuration = URLSessionConfiguration.default
configuration.timeoutIntervalForRequest = 10

    let sessionManager = Alamofire.SessionManager(configuration: configuration)
    sessionManager.request("yourUrl", method: .post, parameters: ["parameterKey": "value"])
            .responseJSON {
                response in
                switch (response.result) {
                case .success:
                    //do json stuff
                    break
                case .failure(let error):
                    if error._code == NSURLErrorTimedOut {
                        //timeout here
                    }
                    print("\n\nAuth request failed with error:\n \(error)")
                    break
                }
            }
</code>```

In the second case, the time out is not replaced and still set as 60 seconds.

```<code>let manager = Alamofire.SessionManager.default
manager.session.configuration.timeoutIntervalForRequest = 10

manager.request("yourUrl", method: .post, parameters: ["parameterKey": "value"])
</code>```

I am running in ios 10.1

My code: (it doesn't work)

```<code>    let configuration = URLSessionConfiguration.default
    configuration.timeoutIntervalForRequest = 10 // seconds
    configuration.timeoutIntervalForResource = 10
    let alamoFireManager = Alamofire.SessionManager(configuration: configuration)

    alamoFireManager.request("my_url", method: .post, parameters: parameters).responseJSON { response in

        switch (response.result) {
        case .success:
                 //Success....
            break
        case .failure(let error):
            // failure...
            break
        }
    }
</code>```

Solved Alamofire github thread: Alamofire 4.3.0 setting timeout throws NSURLErrorDomain error #1931

答:
I have same problem too, I think I found the solution. Try to declare SessionManager?or in your case alamofireManager in class, outside the function

```<code>class ViewController: UIViewController {
   var alamoFireManager : SessionManager? // this line

   func alamofire(){
        let configuration = URLSessionConfiguration.default
        configuration.timeoutIntervalForRequest = 10
        configuration.timeoutIntervalForResource = 10
        alamoFireManager = Alamofire.SessionManager(configuration: configuration) // not in this line

        alamoFireManager.request("my_url", method: .post, parameters: parameters).responseJSON { response in

        switch (response.result) {
        case .success:
                 //Success....
            break
        case .failure(let error):
               // failure...
             break
       }
     }
   }

}
</code>```

Title: Set timeout in Alamofire

Body:
I am using Alamofire 4.0.1 and I want to set a timeout for my request. I tried the solutions gived in this question:

In the first case, it throws a NSURLErrorDomain (timeout is set correctly):

let configuration = URLSessionConfiguration.default
configuration.timeoutIntervalForRequest = 10

    let sessionManager = Alamofire.SessionManager(configuration: configuration)
    sessionManager.request("yourUrl", method: .post, parameters: ["parameterKey": "value"])
            .responseJSON {
                response in
                switch (response.result) {
                case .success:
                    //do json stuff
                    break
                case .failure(let error):
                    if error._code == NSURLErrorTimedOut {
                        //timeout here
                    }
                    print("\n\nAuth request failed with error:\n \(error)")
                    break
                }
            }

In the second case, the time out is not replaced and still set as 60 seconds.

let manager = Alamofire.SessionManager.default
manager.session.configuration.timeoutIntervalForRequest = 10

manager.request("yourUrl", method: .post, parameters: ["parameterKey": "value"])

I am running in ios 10.1

My code: (it doesn't work)

    let configuration = URLSessionConfiguration.default
    configuration.timeoutIntervalForRequest = 10 // seconds
    configuration.timeoutIntervalForResource = 10
    let alamoFireManager = Alamofire.SessionManager(configuration: configuration)

    alamoFireManager.request("my_url", method: .post, parameters: parameters).responseJSON { response in

        switch (response.result) {
        case .success:
                 //Success....
            break
        case .failure(let error):
            // failure...
            break
        }
    }

Solved Alamofire github thread: Alamofire 4.3.0 setting timeout throws NSURLErrorDomain error #1931

Body:
I have same problem too, I think I found the solution. Try to declare SessionManager?or in your case alamofireManager in class, outside the function

class ViewController: UIViewController {
   var alamoFireManager : SessionManager? // this line

   func alamofire(){
        let configuration = URLSessionConfiguration.default
        configuration.timeoutIntervalForRequest = 10
        configuration.timeoutIntervalForResource = 10
        alamoFireManager = Alamofire.SessionManager(configuration: configuration) // not in this line

        alamoFireManager.request("my_url", method: .post, parameters: parameters).responseJSON { response in

        switch (response.result) {
        case .success:
                 //Success....
            break
        case .failure(let error):
               // failure...
             break
       }
     }
   }

}


问:
Excel graph plotting - frequency of low cardinality column vs bins
I've 2 columns and a set of bin values.
Column A contains numeric random values. Column B (contains another property of column A) contains 'True', 'False', and blank cells, i.e 3 distinct values.

I need to plot a single graph as following:

X axis contains the bin values, e.g., 0, 250, 500.

3 curves showing frequency value for three distinct values of column B. B relates to bins through the medium of column A.

I think this type of graph would be a standard type graph. If so, please let me know the name.

Please either provide precise steps to plot it or provide a pointer which could help me plot this graph.

答:
You are looking to create a histogram, it sounds like.  This is a standard Excel tool, though it is not in the standard toolbar because it is not as common as pie charts and the like.

Everything you need can be located on Microsoft's website.


问:
T-SQL - Help with MAX Operation Over Many-to-Many
This is closely related to a previous question i asked.

I have a many-to-many relationship between Post and Location.

The join table is called PostLocations, and has nothing but the FK's. (LocationId, PostId)

I'm trying to pull back the top post for each location.

This is the query i have (which was given in the answer to my previous question):

```<code>SELECT pl.LocationId, p.postid, p.UniqueUri, p.Content, MAX(s.BaseScore) as topscore
from dbo.PostLocations pl
inner join dbo.posts p on pl.PostId = p.PostId
inner join dbo.reviews r on p.postid = r.postid
inner join dbo.scores s on r.scoreid = s.scoreid
group by pl.locationid, p.postid, p.UniqueUri, p.Content
</code>```

But the problem is, because PostLocations could have entries like this:

```<code>LocationId   PostId
1            213213
2            498324
1            230943
</code>```

So my above query is returning LocationId 1 twice, because it has two records in the join table. I only want 1 record per location - the top post per locationid.

I've also tried this:

```<code>SELECT l.LocationId, p.postid, p.UniqueUri, p.Content, MAX(s.BaseScore) as topscore
from dbo.PostLocations pl
inner join dbo.Locations l on pl.LocationId = l.LocationId
inner join dbo.posts p on pl.PostId = p.PostId
inner join dbo.reviews r on p.postid = r.postid
inner join dbo.scores s on r.scoreid = s.scoreid
group by l.locationid, p.postid, p.UniqueUri, p.Content
</code>```

Same result - this is what comes back:

```<code>LocationId   PostId   UniqueUri   Content   TopScore
1            213213   some-post   pew pew   2.00
2            498324   anot-post   blah bl   4.50
1            230943   sadjsa-as   asijd a   3.5
</code>```

This is what should come back:

```<code>LocationId   PostId   UniqueUri   Content   TopScore
1            230943   sadjsa-as   asijd a   3.5
2            498324   anot-post   blah bl   4.50
</code>```

Because LocationId 1 has 2 posts, but PostId 230943 has the highest score so that is the one returned.

Any ideas on what i'm missing?

答:
If you are using SQL Server 2005 or later, you can do something like:</p>

```<code>With RankedLocations As
    (
    Select PL.LocationId
        , S.BaseScore
        , P.PostID
        , P.UniqueUri
        , P.Content
        , Row_Number() Over( Partition By PL.LocationId Order By S.BaseScore Desc ) As ScoreRank
    From dbo.PostLocations As PL
        Join dbo.Posts As P
            On P.PostId = PL.PostId
        Join dbo.Reviews As R
            On R.PostId = P.PostId
        Join dbo.Scores As S
            On S.ScoreId = R.ScoreId
    )
Select LocationId, BaseScore, PostID, UniqueUri, Content
From RankedLocations
Where ScoreRank = 1
</code>```

Body:
This is closely related to a previous question i asked.

I have a many-to-many relationship between Post and Location.

The join table is called PostLocations, and has nothing but the FK's. (LocationId, PostId)

I'm trying to pull back the top post for each location.

This is the query i have (which was given in the answer to my previous question):

SELECT pl.LocationId, p.postid, p.UniqueUri, p.Content, MAX(s.BaseScore) as topscore
from dbo.PostLocations pl
inner join dbo.posts p on pl.PostId = p.PostId
inner join dbo.reviews r on p.postid = r.postid
inner join dbo.scores s on r.scoreid = s.scoreid
group by pl.locationid, p.postid, p.UniqueUri, p.Content

But the problem is, because PostLocations could have entries like this:

LocationId   PostId
1            213213
2            498324
1            230943

So my above query is returning LocationId 1 twice, because it has two records in the join table. I only want 1 record per location - the top post per locationid.

I've also tried this:

SELECT l.LocationId, p.postid, p.UniqueUri, p.Content, MAX(s.BaseScore) as topscore
from dbo.PostLocations pl
inner join dbo.Locations l on pl.LocationId = l.LocationId
inner join dbo.posts p on pl.PostId = p.PostId
inner join dbo.reviews r on p.postid = r.postid
inner join dbo.scores s on r.scoreid = s.scoreid
group by l.locationid, p.postid, p.UniqueUri, p.Content

Same result - this is what comes back:

LocationId   PostId   UniqueUri   Content   TopScore
1            213213   some-post   pew pew   2.00
2            498324   anot-post   blah bl   4.50
1            230943   sadjsa-as   asijd a   3.5

This is what should come back:

LocationId   PostId   UniqueUri   Content   TopScore
1            230943   sadjsa-as   asijd a   3.5
2            498324   anot-post   blah bl   4.50

Because LocationId 1 has 2 posts, but PostId 230943 has the highest score so that is the one returned.

Any ideas on what i'm missing?

Body:
If you are using SQL Server 2005 or later, you can do something like:

With RankedLocations As
    (
    Select PL.LocationId
        , S.BaseScore
        , P.PostID
        , P.UniqueUri
        , P.Content
        , Row_Number() Over( Partition By PL.LocationId Order By S.BaseScore Desc ) As ScoreRank
    From dbo.PostLocations As PL
        Join dbo.Posts As P
            On P.PostId = PL.PostId
        Join dbo.Reviews As R
            On R.PostId = P.PostId
        Join dbo.Scores As S
            On S.ScoreId = R.ScoreId
    )
Select LocationId, BaseScore, PostID, UniqueUri, Content
From RankedLocations
Where ScoreRank = 1


问:
Why use size of character pointer

What is the meaning of this statement?

```<code>char *str[10];
</code>```

Why do we need to specify the size?

答:
Why size is provided is actually a basic rule. Then you must ask why int is used for storing integers. From C complete Reference Book

In C89, the size of an array must be specified using a constant expression. Thus, in C89, the size of
  an array is fixed at compile time. C99 allows arrays whose sizes are determined at run time.

Title: Why use size of character pointer

Body:
What is the meaning of this statement?

char *str[10];

Why do we need to specify the size?


问:
Android Studio cannot open layout xml
suddenly my android studio damaged and it cannot to open a XML of layout.
When I double click on layout xml it doesn't show in code editor also when I drag and drop xml file from project path android studio cannot to show it
please help me
thanks!

答:
Please check your gradle-wrapper.properties file and make sure proper url is given</p>

```<code>distributionUrl=https\://services.gradle.org/distributions/gradle-4.0-milestone-1-all.zip
</code>```

Title: Android Studio cannot open layout xml

Body:
Please check your gradle-wrapper.properties file and make sure proper url is given

distributionUrl=https\://services.gradle.org/distributions/gradle-4.0-milestone-1-all.zip


问:
Calendar.getInstance gives wrong date
I create few small methods as an Util class, like the following code:

```<code>public class Util
{
  public static final String DATETIME_PATTERN="YYYY/MM/DD - HH:mm:ss";

  public static String getDateTime()
  {
    SimpleDateFormat sdf=new SimpleDateFormat(DATETIME_PATTERN);
    return sdf.format(getToday());
  }

  public static Date getToday()
  {
    //Calendar today=Calendar.getInstance(); //didn't help
    Calendar today=Calendar.getInstance(Locale.TAIWAN); //didn't fix
    //Calendar today=Calendar.getInstance(TimeZone.getTimeZone("GMT+08:00")); //didn't fix as well
    return today.getTime();
  }
}
</code>```

And, did a very simple run, like this:

```<code>//run in main class
System.out.println("Generating sitemap.xml, please wait..."+Util.getDateTime());
</code>```

The result is a quite weird date -> 2017/07/187

```<code>//Console result:
Generating sitemap.xml, please wait...2017/07/187 - 15:27:21
</code>```

Searched for similar question, and tried TimeZone, Locale, but didn't help.
Any suggestions ?

BTW, here's my environment:

Windows7 x86

JDK 1.8.0.131 x86

eclipse oxygen x86

答:
James Owen’s answer is correct: you need to use lowercase yyyy and lowercase dd in your format pattern string. That should do it.

What I want to contribute here is the modern and improved version of your utility class:

```<code>public class Util
{
    public static final String DATETIME_PATTERN = "yyyy/MM/dd - HH:mm:ss";

    public static String getDateTime()
    {
        DateTimeFormatter dtf = DateTimeFormatter.ofPattern(DATETIME_PATTERN);
        return getNow().format(dtf);
    }

    public static ZonedDateTime getNow()
    {
        return ZonedDateTime.now(ZoneId.of("Asia/Taipei"));
    }
}
</code>```

Since you are using Java 8, there is no reason for you to take the trouble with the long outdated classes SimpleDateFormat, Date and Calendar. The modern classes are generally much nicer to work with. I took the freedom of also returning a bit more information from getToday() (and renamed it to getNow): it now tells you both the current time and the time zone, which makes sure that getDateTime() also formats the time in this time zone.

I preferred Asia/Taipei as time zone. It gives the same result as GMT+08:00, but (1) is futureproof in case Taiwan again introduces summer time (DST) (2) is clearer to read and tells the reader more about why this particular offset was chosen (Taiwan has had summer time before, last time was in 1979).

An example of the trouble with SimpleDateFormat

One out of many objections to the old classes is they tend to pretend everything is well when it isn’t. You got an incorrect output and no explanation why. You would have preferred some error message. The modern classes behave a bit better on this point. Say you had used your pattern string with my code. It gives

java.time.DateTimeException: Field DayOfYear cannot be printed as the
  value 187 exceeds the maximum print width of 2

Day of year? You may have to check the documentation to see that capital D is for day-of-year while small d is for day-of-month. Let’s fix:

```<code>public static final String DATETIME_PATTERN = "YYYY/MM/dd - HH:mm:ss";
</code>```

Unfortunately DateTimeFormatter does not catch your other error, the uppercase YYYY. This means week-based year and is only useful with a week number. But theoretically you might have intended this, the class has no chance to tell. If you had tried to parse with the same format, you would have been told you couldn’t.

If you need a Date

Maybe you need a Date object for some legacy API that you cannot change. In Java 8 the old classes have been fitted with conversion methods, so it’s easy (when you know how). You may for example add this method:

```<code>public static Date getNowAsOldfashionedDateObject() {
    return Date.from(getNow().toInstant());
}
</code>```

Title: Calendar.getInstance gives wrong date

Body:
I create few small methods as an Util class, like the following code:

public class Util
{
  public static final String DATETIME_PATTERN="YYYY/MM/DD - HH:mm:ss";

  public static String getDateTime()
  {
    SimpleDateFormat sdf=new SimpleDateFormat(DATETIME_PATTERN);
    return sdf.format(getToday());
  }

  public static Date getToday()
  {
    //Calendar today=Calendar.getInstance(); //didn't help
    Calendar today=Calendar.getInstance(Locale.TAIWAN); //didn't fix
    //Calendar today=Calendar.getInstance(TimeZone.getTimeZone("GMT+08:00")); //didn't fix as well
    return today.getTime();
  }
}

And, did a very simple run, like this:

//run in main class
System.out.println("Generating sitemap.xml, please wait..."+Util.getDateTime());

The result is a quite weird date -> 2017/07/187

//Console result:
Generating sitemap.xml, please wait...2017/07/187 - 15:27:21

Searched for similar question, and tried TimeZone, Locale, but didn't help.
Any suggestions ?

BTW, here's my environment:

Windows7 x86

JDK 1.8.0.131 x86

eclipse oxygen x86

Body:
James Owen’s answer is correct: you need to use lowercase yyyy and lowercase dd in your format pattern string. That should do it.

What I want to contribute here is the modern and improved version of your utility class:

public class Util
{
    public static final String DATETIME_PATTERN = "yyyy/MM/dd - HH:mm:ss";

    public static String getDateTime()
    {
        DateTimeFormatter dtf = DateTimeFormatter.ofPattern(DATETIME_PATTERN);
        return getNow().format(dtf);
    }

    public static ZonedDateTime getNow()
    {
        return ZonedDateTime.now(ZoneId.of("Asia/Taipei"));
    }
}

Since you are using Java 8, there is no reason for you to take the trouble with the long outdated classes SimpleDateFormat, Date and Calendar. The modern classes are generally much nicer to work with. I took the freedom of also returning a bit more information from getToday() (and renamed it to getNow): it now tells you both the current time and the time zone, which makes sure that getDateTime() also formats the time in this time zone.

I preferred Asia/Taipei as time zone. It gives the same result as GMT+08:00, but (1) is futureproof in case Taiwan again introduces summer time (DST) (2) is clearer to read and tells the reader more about why this particular offset was chosen (Taiwan has had summer time before, last time was in 1979).

An example of the trouble with SimpleDateFormat

One out of many objections to the old classes is they tend to pretend everything is well when it isn’t. You got an incorrect output and no explanation why. You would have preferred some error message. The modern classes behave a bit better on this point. Say you had used your pattern string with my code. It gives

java.time.DateTimeException: Field DayOfYear cannot be printed as the
  value 187 exceeds the maximum print width of 2

Day of year? You may have to check the documentation to see that capital D is for day-of-year while small d is for day-of-month. Let’s fix:

public static final String DATETIME_PATTERN = "YYYY/MM/dd - HH:mm:ss";

Unfortunately DateTimeFormatter does not catch your other error, the uppercase YYYY. This means week-based year and is only useful with a week number. But theoretically you might have intended this, the class has no chance to tell. If you had tried to parse with the same format, you would have been told you couldn’t.

If you need a Date

Maybe you need a Date object for some legacy API that you cannot change. In Java 8 the old classes have been fitted with conversion methods, so it’s easy (when you know how). You may for example add this method:

public static Date getNowAsOldfashionedDateObject() {
    return Date.from(getNow().toInstant());
}