问:
Matplotlib y-tick labels not showing
For some reason the y-tick and y-tick labels aren't showing up on my plot. The variable data is a pandas dataframe: rfr_scatter = pd.DataFrame({'Actual':y_test, 'Model Predicted':rfr_predictions})

```<code>import matplotlib
matplotlib.use("TkAgg")
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg, NavigationToolbar2TkAgg
from matplotlib.figure import Figure
import matplotlib.animation as animation
from matplotlib import style
from matplotlib import pyplot as plt
import numpy as np
import pandas as pd
import tkinter as tk
from tkinter import *

def ScatterPlotter(notebooktab, data, test, pred):
    f = Figure(figsize=(7,5), dpi=100)
    ax1 = f.add_subplot(111, title="Model Performance")

    for item in ([ax1.title, ax1.xaxis.label, ax1.yaxis.label] +
                 ax1.get_xticklabels() + ax1.get_yticklabels()):
        item.set_fontsize(8)
        item.set_color('black')

    markersize = 0.8
    alpha = 0.05

    line = np.arange(min(test), min(test) + 35, 5)
    data.plot.scatter(x='Actual', y='Model Predicted', ax=ax1, s=markersize, alpha=alpha)
    ax1.set_xlim((min(test),max(test)))
    ax1.set_ylim((pred.min(),pred.max()))
    ax1.plot(line,line,clr_red,'--', label = "Perfect")

    canvas = FigureCanvasTkAgg(f, notebooktab)
    canvas.show()
    canvas.get_tk_widget().pack()
</code>```

And i get this:

I have tried setting the yticks to visible, with no luck. I'm probably missing something simple...

EDIT: removing ax1.set_ylim((pred.min(),pred.max())) gives me a couple marks on the graph, it almost looks like the label is over the text, or the text isn't finishing rendering.

答: Changing ax1.plot(line,line,clr_red,'--', label = "Perfect") to ax1.plot(line,line,'r--', label = "Perfect") fixed the problem

Title: Matplotlib y-tick labels not showing

Body:
For some reason the y-tick and y-tick labels aren't showing up on my plot. The variable data is a pandas dataframe: rfr_scatter = pd.DataFrame({'Actual':y_test, 'Model Predicted':rfr_predictions})

import matplotlib
matplotlib.use("TkAgg")
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg, NavigationToolbar2TkAgg
from matplotlib.figure import Figure
import matplotlib.animation as animation
from matplotlib import style
from matplotlib import pyplot as plt
import numpy as np
import pandas as pd
import tkinter as tk
from tkinter import *

def ScatterPlotter(notebooktab, data, test, pred):
    f = Figure(figsize=(7,5), dpi=100)
    ax1 = f.add_subplot(111, title="Model Performance")

    for item in ([ax1.title, ax1.xaxis.label, ax1.yaxis.label] +
                 ax1.get_xticklabels() + ax1.get_yticklabels()):
        item.set_fontsize(8)
        item.set_color('black')

    markersize = 0.8
    alpha = 0.05

    line = np.arange(min(test), min(test) + 35, 5)
    data.plot.scatter(x='Actual', y='Model Predicted', ax=ax1, s=markersize, alpha=alpha)
    ax1.set_xlim((min(test),max(test)))
    ax1.set_ylim((pred.min(),pred.max()))
    ax1.plot(line,line,clr_red,'--', label = "Perfect")

    canvas = FigureCanvasTkAgg(f, notebooktab)
    canvas.show()
    canvas.get_tk_widget().pack()

And i get this:

I have tried setting the yticks to visible, with no luck. I'm probably missing something simple...

EDIT: removing ax1.set_ylim((pred.min(),pred.max())) gives me a couple marks on the graph, it almost looks like the label is over the text, or the text isn't finishing rendering.


来源: stackexchange

问:
System.UnauthorizedAccessException was unhandled
I am getting a access denied exception. How can I fix this?

Here is the exception:

System.UnauthorizedAccessException was unhandled   HResult=-2147024891
  Message=Access to the path 'c:\message.txt' is denied.

  Source=mscorlib

Here is the code:

```<code>    public static void WriteToFile(string s)
    {
        fs = new FileStream("c:\\message.txt",
        FileMode.Append, FileAccess.Write);
        sw = new StreamWriter(fs);
        sw.WriteLine(s);
        sw.Flush();
        sw.Close();
        fs.Close();
    }
</code>```

EDIT: It works if I run vs2012 as administrator, but is there a way or a reason to do it as normal user?

And this works:

```<code>    public static void WriteToFile(string s)
    {
        fs = new FileStream(@"C:\Users\KristjanBEstur\Documents\message.txt",
        FileMode.Append, FileAccess.Write);
        sw = new StreamWriter(fs);
        sw.WriteLine(s);
        sw.Flush();
        sw.Close();
        fs.Close();
        File.Delete(@"C:\Users\KristjanBEstur\Documents\message.txt");
    }
</code>```

答:
Just to add to Mujahed's answer (I can't comment yet), you don't need uiAccess="true" if you just wanted to run with administrator privileges. Setting this option to true could cause you some headache (e.g. you might not be able to run your project in debug mode.)

```<code>    <requestedExecutionLevel level="requireAdministrator" uiAccess="false" />
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I am getting a access denied exception. How can I fix this?

Here is the exception:

System.UnauthorizedAccessException was unhandled   HResult=-2147024891
  Message=Access to the path 'c:\message.txt' is denied.

  Source=mscorlib

Here is the code:

    public static void WriteToFile(string s)
    {
        fs = new FileStream("c:\\message.txt",
        FileMode.Append, FileAccess.Write);
        sw = new StreamWriter(fs);
        sw.WriteLine(s);
        sw.Flush();
        sw.Close();
        fs.Close();
    }

EDIT: It works if I run vs2012 as administrator, but is there a way or a reason to do it as normal user?

And this works:

    public static void WriteToFile(string s)
    {
        fs = new FileStream(@"C:\Users\KristjanBEstur\Documents\message.txt",
        FileMode.Append, FileAccess.Write);
        sw = new StreamWriter(fs);
        sw.WriteLine(s);
        sw.Flush();
        sw.Close();
        fs.Close();
        File.Delete(@"C:\Users\KristjanBEstur\Documents\message.txt");
    }

Body:
Just to add to Mujahed's answer (I can't comment yet), you don't need uiAccess="true" if you just wanted to run with administrator privileges. Setting this option to true could cause you some headache (e.g. you might not be able to run your project in debug mode.)

    <requestedExecutionLevel level="requireAdministrator" uiAccess="false" />


问:
Variables with decimals on Javascript calculations
I' ve made this simple form which calculates the BMI from Height and Weight Variables. It works when i insert integers to Height and Weight variables respectively, but unfortunately it doesn't work the way it should when i insert decimal numbers.

Any thoughts on fixing this issue?

function Calculate() {
  var manWeight = document.getElementById('manWeight').value;
  var manHeight = document.getElementById('manHeight').value;

  document.getElementById('manBMI').value = parseInt(document.getElementById('manWeight').value) / Math.pow(parseInt(document.getElementById('manHeight').value), 2);

}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><label for="manWeight">Weight: *</label>
  <input type="text" name="manWeight" size="35" id="manWeight" required autocomplete="off">
  <br>

<label for="manHeight">Height: *</label>
  <input type="text" name="manHeight" size="35" id="manHeight" required autocomplete="off"> <br>

<label for="manBMI">BMI:</label>
  <input type="text" name="manBMI" size="35" id="manBMI" required disabled autocomplete="off">

<button type="button" id="calculator" name="calculator" onclick="Calculate();">Calculate</button></code>```

答:
You don't need to use parseInt(value) when calculating the final values. parseInt will round down any floats that you can pass in.

You can instead use Number(value). Which will parse floats. But this will return NaN if you input invalid characters.

You can use the input type of Number in limit the inputs to valid numbers. (on supported browsers)

function Calculate() {
  var manWeight = document.getElementById('manWeight').value;
  var manHeight = document.getElementById('manHeight').value;

  document.getElementById('manBMI').value = Number(document.getElementById('manWeight').value) / Math.pow(Number(document.getElementById('manHeight').value), 2);

}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><label for="manWeight">Weight: *</label>
  <input type="number" name="manWeight" size="35" id="manWeight" required autocomplete="off">
  <br>

<label for="manHeight">Height: *</label>
  <input type="number" name="manHeight" size="35" id="manHeight" required autocomplete="off"> <br>

<label for="manBMI">BMI:</label>
  <input type="text" name="manBMI" size="35" id="manBMI" required disabled autocomplete="off">

<button type="button" id="calculator" name="calculator" onclick="Calculate();">Calculate</button></code>```

Body:
I' ve made this simple form which calculates the BMI from Height and Weight Variables. It works when i insert integers to Height and Weight variables respectively, but unfortunately it doesn't work the way it should when i insert decimal numbers.

Any thoughts on fixing this issue?

function Calculate() {
  var manWeight = document.getElementById('manWeight').value;
  var manHeight = document.getElementById('manHeight').value;

  document.getElementById('manBMI').value = parseInt(document.getElementById('manWeight').value) / Math.pow(parseInt(document.getElementById('manHeight').value), 2);

}

Weight: *
  <input type="text" name="manWeight" size="35" id="manWeight" required autocomplete="off">

Height: *
  <input type="text" name="manHeight" size="35" id="manHeight" required autocomplete="off">

BMI:
  <input type="text" name="manBMI" size="35" id="manBMI" required disabled autocomplete="off">

<button type="button" id="calculator" name="calculator" onclick="Calculate();">Calculate</button>

Body:
You don't need to use parseInt(value) when calculating the final values. parseInt will round down any floats that you can pass in.

You can instead use Number(value). Which will parse floats. But this will return NaN if you input invalid characters.

You can use the input type of Number in limit the inputs to valid numbers. (on supported browsers)

function Calculate() {
  var manWeight = document.getElementById('manWeight').value;
  var manHeight = document.getElementById('manHeight').value;

  document.getElementById('manBMI').value = Number(document.getElementById('manWeight').value) / Math.pow(Number(document.getElementById('manHeight').value), 2);

}

<label for="manWeight">Weight: *</label>
  <input type="number" name="manWeight" size="35" id="manWeight" required autocomplete="off">
  <br>

<label for="manHeight">Height: *</label>
  <input type="number" name="manHeight" size="35" id="manHeight" required autocomplete="off"> <br>

<label for="manBMI">BMI:</label>
  <input type="text" name="manBMI" size="35" id="manBMI" required disabled autocomplete="off">

<button type="button" id="calculator" name="calculator" onclick="Calculate();">Calculate</button>


问:
Inflated button has wrong width and height
I'm building a navigation fragment. There is a button which is always present (main button) and others which are dynamically added and removed.

I have a xml resource file from which I inflate a button, change it's icon and add it to the fragments root layout.

Almost everything works, except for the button size. Button size after is 0 (getWidth()/getHeight()).

button_navigation.xml

```<code><?xml version="1.0" encoding="utf-8"?>
<Button xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/navigation_button"
    android:layout_width="60dp"
    android:layout_height="60dp"
    android:background="@drawable/icon_test"
    android:backgroundTint="@drawable/selector_bar_button"></Button>
</code>```

inflating code

```<code>Button butt = (Button) inflater.inflate(R.layout.button_navigation, null, false);

buttons.add(butt);
root_view.addView(butt);
</code>```

creating inflater

```<code>public void setParent(MainActivity activity){
        parent = activity;
        inflater = (LayoutInflater) activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    }
</code>```

variables

```<code>MainActivity parent;
LayoutInflater inflater;

int index;

ArrayList<Button> buttons;
Button button_main;
LinearLayout root_view;
</code>```

Main button, has the exact code as button_navigation.xml and occurs in the layout file of the fragment. The main button's size is good.

答:
Wrap your button inside a layout.

```<code><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical">

<Button
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/nickname_message"
    android:layout_width="60dp"
    android:layout_height="60dp"
    android:text="adawd awdaw"
    android:textSize="18sp"
    android:textStyle="bold" />
</code>```

Then add it at runtime.

```<code>linearLayout.addView(LayoutInflater.from(this).inflate(R.layout.item_layout,null));
</code>```

Body:
I'm building a navigation fragment. There is a button which is always present (main button) and others which are dynamically added and removed.

I have a xml resource file from which I inflate a button, change it's icon and add it to the fragments root layout.

Almost everything works, except for the button size. Button size after is 0 (getWidth()/getHeight()).

button_navigation.xml

<?xml version="1.0" encoding="utf-8"?>
<Button xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/navigation_button"
    android:layout_width="60dp"
    android:layout_height="60dp"
    android:background="@drawable/icon_test"
    android:backgroundTint="@drawable/selector_bar_button"></Button>

inflating code

Button butt = (Button) inflater.inflate(R.layout.button_navigation, null, false);

buttons.add(butt);
root_view.addView(butt);

creating inflater

public void setParent(MainActivity activity){
        parent = activity;
        inflater = (LayoutInflater) activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    }

variables

MainActivity parent;
LayoutInflater inflater;

int index;

ArrayList<Button> buttons;
Button button_main;
LinearLayout root_view;

Main button, has the exact code as button_navigation.xml and occurs in the layout file of the fragment. The main button's size is good.

Body:
Wrap your button inside a layout.

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical">

<Button
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/nickname_message"
    android:layout_width="60dp"
    android:layout_height="60dp"
    android:text="adawd awdaw"
    android:textSize="18sp"
    android:textStyle="bold" />

Then add it at runtime.

linearLayout.addView(LayoutInflater.from(this).inflate(R.layout.item_layout,null));


问:
Xamarin, Android: ImageView.SetColorFilter() has NO effect whatsover on my ImageView?
I have an imageView that uses an alpha channel, is round and basically made up only from black outlines. In a simple instance, I need to, however, display the imageview not as black, but as white. Everything else needs to stay the same. After a bit of googling, this is what I came up with:

```<code>ImageButton btnHeader = new ImageButton(this);
btnHeader.SetBackgroundResource(Resource.Drawable.mainmenu_btn_news_bol);
btnHeader.SetColorFilter(new Color(Color.White), PorterDuff.Mode.SrcIn);
</code>```

This should at least have some effect on the ImageView , but it just doesn't. It is, as if the 3rd line of code just gets jumped. Can anyone maybe explain to me if this is a bug or me?

答:
Setting a color filter directly on the ImageButton will affect only its source image, not the background. That is, it will affect those images set with the SetImage*() methods. If that's what you mean to do, then simply change the SetBackgroundResource() call to SetImageResource().

If, instead, you are trying to filter the background specifically, you'll need to set the filter directly on the background Drawable. For example:

```<code>btnHeader.Background.SetColorFilter(new Color(Color.White), PorterDuff.Mode.SrcIn);
</code>```

Furthermore, separate Drawables created from the same resource will share a common state by default, so if you have multiple Views using the same resource image, then setting a filter on one will affect all of the others, as well. You can force a new, separate state to be created for a particular Drawable by calling Mutate() on it first, before applying the filter. For example, with the background image:

```<code>btnHeader.Background.Mutate().SetColorFilter(new Color(Color.White), PorterDuff.Mode.SrcIn);
</code>```

Body:
I have an imageView that uses an alpha channel, is round and basically made up only from black outlines. In a simple instance, I need to, however, display the imageview not as black, but as white. Everything else needs to stay the same. After a bit of googling, this is what I came up with:

ImageButton btnHeader = new ImageButton(this);
btnHeader.SetBackgroundResource(Resource.Drawable.mainmenu_btn_news_bol);
btnHeader.SetColorFilter(new Color(Color.White), PorterDuff.Mode.SrcIn);

This should at least have some effect on the ImageView , but it just doesn't. It is, as if the 3rd line of code just gets jumped. Can anyone maybe explain to me if this is a bug or me?

Body:
Setting a color filter directly on the ImageButton will affect only its source image, not the background. That is, it will affect those images set with the SetImage*() methods. If that's what you mean to do, then simply change the SetBackgroundResource() call to SetImageResource().

If, instead, you are trying to filter the background specifically, you'll need to set the filter directly on the background Drawable. For example:

btnHeader.Background.SetColorFilter(new Color(Color.White), PorterDuff.Mode.SrcIn);

Furthermore, separate Drawables created from the same resource will share a common state by default, so if you have multiple Views using the same resource image, then setting a filter on one will affect all of the others, as well. You can force a new, separate state to be created for a particular Drawable by calling Mutate() on it first, before applying the filter. For example, with the background image:

btnHeader.Background.Mutate().SetColorFilter(new Color(Color.White), PorterDuff.Mode.SrcIn);


问:
String concatenation: concat() vs "+" operator
Assuming String a and b:

```<code>a += b
a = a.concat(b)
</code>```

Under the hood, are they the same thing?

Here is concat decompiled as reference. I'd like to be able to decompile the + operator as well to see what that does.

```<code>public String concat(String s) {

    int i = s.length();
    if (i == 0) {
        return this;
    }
    else {
        char ac[] = new char[count + i];
        getChars(0, count, ac, 0);
        s.getChars(0, i, ac, count);
        return new String(0, count + i, ac);
    }
}
</code>```

答:
Tom is correct in describing exactly what the + operator does.  It creates a temporary StringBuilder, appends the parts, and finishes with toString().

However, all of the answers so far are ignoring the effects of HotSpot runtime optimizations.  Specifically, these temporary operations are recognized as a common pattern and are replaced with more efficient machine code at run-time.

@marcio: You've created a micro-benchmark; with modern JVM's this is not a valid way to profile code.

The reason run-time optimization matters is that many of these differences in code -- even including object-creation -- are completely different once HotSpot gets going.  The only way to know for sure is profiling your code in situ.

Finally, all of these methods are in fact incredibly fast.  This might be a case of premature optimization.  If you have code that concatenates strings a lot, the way to get maximum speed probably has nothing to do with which operators you choose and instead the algorithm you're using!

OwnerDisplayName: shs

Body:
Assuming String a and b:

a += b
a = a.concat(b)

Under the hood, are they the same thing?

Here is concat decompiled as reference. I'd like to be able to decompile the + operator as well to see what that does.

public String concat(String s) {

    int i = s.length();
    if (i == 0) {
        return this;
    }
    else {
        char ac[] = new char[count + i];
        getChars(0, count, ac, 0);
        s.getChars(0, i, ac, count);
        return new String(0, count + i, ac);
    }
}

LastEditorDisplayName: shs

OwnerDisplayName: Jason Cohen

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: Jason Cohen


问:
That A-Ha Moment for Understanding OO Design in C#
I've been studying C# for a couple of years, reading voraciously, even taking a few C# data access courses from Microsoft.  I've also been reading books on OOP.  I'm coding a web-based database application at work.  While my job title is not "programmer", I'm fortunate enough to be able to work on this as a side project.  I coded in Basic in the early 80's and was even good at utilizing pokes and peeks to manipulate the Apple ][ + and the TRS-80 to astound and amaze my friends.  But that was a very linear approach to coding.

All this being said, something is just not clicking with me.  I haven't had that a-ha moment with either C# or OOP that gives me the ability to sit down, open up VS2008, and start coding.  I have to study other people's code so much that it simply seems like I'm not doing anything on my own.  I'm getting discouraged.

It's not like I'm not capable of it.  I picked up t-sql really quickly.  Someone can tell me what information they want out of the database and I can code out the tsql in a matter of a few minutes to give them what they want.  SQL is something that I get.  This isn't happening for me with OOP or C#.  Granted, C# is inherently more complex, but at some point it has to click.  Right?

I read over stackoverflow and I'm overwhelmed at how infinitely smart you all are.

What was it for you that made it click?

Edited to add:
A lot of the answers here were outstanding.  However, one in particular seemed to have risen to the top and that's the one I marked as the "answer".  I also hate not marking my questions with the answer.

答:
Object Oriented design in general requires mental snuggling, but for me C-type OOD seemed rather natural after the university using JAVA to teach us OOD.

After much practice with hobby projects where an elegant architecture is required to meet some of the use cases - OOP seem to become more and more automatic.

OwnerDisplayName: GregD

LastEditorDisplayName: GregD

OwnerDisplayName: vanslly


问:
How to add a toctree entry?

I am trying to get started with Sphinx for documenting Python, and I seem to be missing some very basic step in getting started.

I'm following the http://www.sphinx-doc.org/en/stable/tutorial.html and have installed and configured (with defaults, wherever possible) the tool.

The problem is that I am unable to link another RST file to index. My index file is as below:

```<code>Welcome to FirstProject's documentation!
====================================
.. toctree::
   :maxdepth: 2

intro
</code>```

Note that intro.rst is in the same directory with the following content:

```<code>Introduction to the FirstProject project!!
======================================

.. toctree::
    :maxdepth: 2
</code>```

The output type is html. When  I try

```<code>make html
</code>```

I  get a warning saying:

```<code>/home/ngk/Code/Projects/Twitter/botscore/doc/intro.rst: WARNING: document isn't included in any toctree
</code>```

I expected that a hyperlink with 'the intro' string would be created in index.html with the link pointing to intro.html

Instead, there is just a string 'intro' in the expected location in the index.html file. Note that the intro.html file is created, but not hyperlinked from index.html

Can someone suggest what seemingly small step I have missed?

答:
It looks like the problem was that Sphinx-doc was expecting 3 whitespaces at the start of each line of the included RSTs. Changing my index.rst as below fixed the problem!

```<code>.. toctree::
   :maxdepth: 2

   intro
</code>```

Sphinx-doc seems to be sensitive to the exact number of whitespaces. I tried using fewer and also tried using a tabspace, but neither worked.

Hope this is useful to others who come across this problem.

Edit:
It works with other numbers of whitespaces too, as long as each entry in the toctree has the same number of whitespaces.

ContentLicense: CC BY-SA 4.0

Title: How to add a toctree entry?

Body:
I am trying to get started with Sphinx for documenting Python, and I seem to be missing some very basic step in getting started.

I'm following the http://www.sphinx-doc.org/en/stable/tutorial.html and have installed and configured (with defaults, wherever possible) the tool.

The problem is that I am unable to link another RST file to index. My index file is as below:

Welcome to FirstProject's documentation!
====================================
.. toctree::
   :maxdepth: 2

intro

Note that intro.rst is in the same directory with the following content:

Introduction to the FirstProject project!!
======================================

.. toctree::
    :maxdepth: 2

The output type is html. When  I try

make html

I  get a warning saying:

/home/ngk/Code/Projects/Twitter/botscore/doc/intro.rst: WARNING: document isn't included in any toctree

I expected that a hyperlink with 'the intro' string would be created in index.html with the link pointing to intro.html

Instead, there is just a string 'intro' in the expected location in the index.html file. Note that the intro.html file is created, but not hyperlinked from index.html

Can someone suggest what seemingly small step I have missed?

Body:
It looks like the problem was that Sphinx-doc was expecting 3 whitespaces at the start of each line of the included RSTs. Changing my index.rst as below fixed the problem!

.. toctree::
   :maxdepth: 2

   intro

Sphinx-doc seems to be sensitive to the exact number of whitespaces. I tried using fewer and also tried using a tabspace, but neither worked.

Hope this is useful to others who come across this problem.

Edit:
It works with other numbers of whitespaces too, as long as each entry in the toctree has the same number of whitespaces.


问:
pluralsight cours--not having the same result in Plnkr
Im doing the AngularJS Directives Fundamentals, and I'm stuck in the first exemple.
Here is the link to see the Plnkr
link to see the Plnkr
this is the html

```<code><!DOCTYPE html>
<html ng-app="app">

<head>
    <script data-require="angular.js@*" data-semver="4.0.0"
     src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/2.0.0-
     beta.17/angular2.min.js"></script>
    <link rel="stylesheet" href="style.css" />
    <script src="script.js"></script>
    <script src="angular.min.js"></script>
    </head>

 <body ng-controller="mainCtrl">
    <h1>Hello Plunker!</h1>
    <div user-info-card></div>
 </body>
</code>```

I'm supposed to get these result:

Please help, I'm really stuck

答:
Swap the order:

```<code><script src="angular.min.js"></script>
<script src="script.js"></script>
</code>```

You should be loading angular before your script.

Also I think you are loading Angular 2 in there for some reason. It's completely different from AngularJS.

Body:
Im doing the AngularJS Directives Fundamentals, and I'm stuck in the first exemple.
Here is the link to see the Plnkr
link to see the Plnkr
this is the html

<!DOCTYPE html>

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

Hello Plunker!

I'm supposed to get these result:

Please help, I'm really stuck

Body:
Swap the order:

<script src="angular.min.js"></script>
<script src="script.js"></script>

You should be loading angular before your script.

Also I think you are loading Angular 2 in there for some reason. It's completely different from AngularJS.


问:
Create one list of numbers by combining numbers from three lists of uneven length
I'm trying to create a list of id's, where the numbers are made up of three different lists: the first part of the number should be from the list pers:

```<code>pers = list(range(1,12))
</code>```

The second part should be a combination of the person id, and the number 1 or 2 (not necessarily a list, as it is just two numbers), like this:

```<code>ids = [11, 12, 21, 22, 31, 32, 41, 42, 51, 52, 61, 62, 71, 72, 81, 82, 91,
       92, 101, 102, 111, 112]
</code>```

The third part should be a combination of the above and the values in the list reps:

```<code>reps = list(range(1,13))
</code>```

like this:

```<code>ids = [111, 112, 113, 114, 115, 116, 117, 118, 119, 1110, 1111, 1112,
       121, 122, 123, 124, 125, 126, 127, 128, 129, 1210, 1211, 1212 ...]
</code>```

and so on, all the way up to 11212 (person 11, condition 2,  repetition 12). In total around 2250 items in the list.

I've tried various itertools functions, or nested for loops, lists of lists and tips in this post, but none seem to yield what I need.

Body:
I'm trying to create a list of id's, where the numbers are made up of three different lists: the first part of the number should be from the list pers:

pers = list(range(1,12))

The second part should be a combination of the person id, and the number 1 or 2 (not necessarily a list, as it is just two numbers), like this:

ids = [11, 12, 21, 22, 31, 32, 41, 42, 51, 52, 61, 62, 71, 72, 81, 82, 91,
       92, 101, 102, 111, 112]

The third part should be a combination of the above and the values in the list reps:

reps = list(range(1,13))

like this:

ids = [111, 112, 113, 114, 115, 116, 117, 118, 119, 1110, 1111, 1112,
       121, 122, 123, 124, 125, 126, 127, 128, 129, 1210, 1211, 1212 ...]

and so on, all the way up to 11212 (person 11, condition 2,  repetition 12). In total around 2250 items in the list.

I've tried various itertools functions, or nested for loops, lists of lists and tips in this post, but none seem to yield what I need.

Body:
Everyone is going to give you loop solution :

what about without loop and without any external module ?

instead of three loops you can just try:

print(list(map(lambda x:(list(map(lambda y:(list(map(lambda s:(x,y,s),reps))),cond))),pers)))

output:

[[[(1, 1, 1), (1, 1, 2), (1, 1, 3), (1, 1, 4), (1, 1, 5), (1, 1, 6), (1, 1, 7), (1, 1, 8), (1, 1, 9), (1, 1, 10), (1, 1, 11), (1, 1, 12)], [(1, 2, 1), (1, 2, 2), (1, 2, 3), (1, 2, 4), (1, 2, 5), (1, 2, 6), (1, 2, 7), (1, 2, 8), (1, 2, 9), (1, 2, 10), (1, 2, 11), (1, 2, 12)]], [[(2, 1, 1), (2, 1, 2), (2, 1, 3), (2, 1, 4), (2, 1, 5), (2, 1, 6), (2, 1, 7), (2, 1, 8), (2, 1, 9), (2, 1, 10), (2, 1, 11), (2, 1, 12)], [(2, 2, 1), (2, 2, 2), (2, 2, 3), (2, 2, 4), (2, 2, 5), (2, 2, 6), (2, 2, 7), (2, 2, 8), (2, 2, 9), (2, 2, 10), (2, 2, 11), (2, 2, 12)]], [[(3, 1, 1), (3, 1, 2), (3, 1, 3), (3, 1, 4), (3, 1, 5), (3, 1, 6), (3, 1, 7), (3, 1, 8), (3, 1, 9), (3, 1, 10), (3, 1, 11), (3, 1, 12)], [(3, 2, 1), (3, 2, 2), (3, 2, 3), (3, 2, 4), (3, 2, 5), (3, 2, 6), (3, 2, 7), (3, 2, 8), (3, 2, 9), (3, 2, 10), (3, 2, 11), (3, 2, 12)]], [[(4, 1, 1), (4, 1, 2), (4, 1, 3), (4, 1, 4), (4, 1, 5), (4, 1, 6), (4, 1, 7), (4, 1, 8), (4, 1, 9), (4, 1, 10), (4, 1, 11), (4, 1, 12)], [(4, 2, 1), (4, 2, 2), (4, 2, 3), (4, 2, 4), (4, 2, 5), (4, 2, 6), (4, 2, 7), (4, 2, 8), (4, 2, 9), (4, 2, 10), (4, 2, 11), (4, 2, 12)]], [[(5, 1, 1), (5, 1, 2), (5, 1, 3), (5, 1, 4), (5, 1, 5), (5, 1, 6), (5, 1, 7), (5, 1, 8), (5, 1, 9), (5, 1, 10), (5, 1, 11), (5, 1, 12)], [(5, 2, 1), (5, 2, 2), (5, 2, 3), (5, 2, 4), (5, 2, 5), (5, 2, 6), (5, 2, 7), (5, 2, 8), (5, 2, 9), (5, 2, 10), (5, 2, 11), (5, 2, 12)]], [[(6, 1, 1), (6, 1, 2), (6, 1, 3), (6, 1, 4), (6, 1, 5), (6, 1, 6), (6, 1, 7), (6, 1, 8), (6, 1, 9), (6, 1, 10), (6, 1, 11), (6, 1, 12)], [(6, 2, 1), (6, 2, 2), (6, 2, 3), (6, 2, 4), (6, 2, 5), (6, 2, 6), (6, 2, 7), (6, 2, 8), (6, 2, 9), (6, 2, 10), (6, 2, 11), (6, 2, 12)]], [[(7, 1, 1), (7, 1, 2), (7, 1, 3), (7, 1, 4), (7, 1, 5), (7, 1, 6), (7, 1, 7), (7, 1, 8), (7, 1, 9), (7, 1, 10), (7, 1, 11), (7, 1, 12)], [(7, 2, 1), (7, 2, 2), (7, 2, 3), (7, 2, 4), (7, 2, 5), (7, 2, 6), (7, 2, 7), (7, 2, 8), (7, 2, 9), (7, 2, 10), (7, 2, 11), (7, 2, 12)]], [[(8, 1, 1), (8, 1, 2), (8, 1, 3), (8, 1, 4), (8, 1, 5), (8, 1, 6), (8, 1, 7), (8, 1, 8), (8, 1, 9), (8, 1, 10), (8, 1, 11), (8, 1, 12)], [(8, 2, 1), (8, 2, 2), (8, 2, 3), (8, 2, 4), (8, 2, 5), (8, 2, 6), (8, 2, 7), (8, 2, 8), (8, 2, 9), (8, 2, 10), (8, 2, 11), (8, 2, 12)]], [[(9, 1, 1), (9, 1, 2), (9, 1, 3), (9, 1, 4), (9, 1, 5), (9, 1, 6), (9, 1, 7), (9, 1, 8), (9, 1, 9), (9, 1, 10), (9, 1, 11), (9, 1, 12)], [(9, 2, 1), (9, 2, 2), (9, 2, 3), (9, 2, 4), (9, 2, 5), (9, 2, 6), (9, 2, 7), (9, 2, 8), (9, 2, 9), (9, 2, 10), (9, 2, 11), (9, 2, 12)]], [[(10, 1, 1), (10, 1, 2), (10, 1, 3), (10, 1, 4), (10, 1, 5), (10, 1, 6), (10, 1, 7), (10, 1, 8), (10, 1, 9), (10, 1, 10), (10, 1, 11), (10, 1, 12)], [(10, 2, 1), (10, 2, 2), (10, 2, 3), (10, 2, 4), (10, 2, 5), (10, 2, 6), (10, 2, 7), (10, 2, 8), (10, 2, 9), (10, 2, 10), (10, 2, 11), (10, 2, 12)]], [[(11, 1, 1), (11, 1, 2), (11, 1, 3), (11, 1, 4), (11, 1, 5), (11, 1, 6), (11, 1, 7), (11, 1, 8), (11, 1, 9), (11, 1, 10), (11, 1, 11), (11, 1, 12)], [(11, 2, 1), (11, 2, 2), (11, 2, 3), (11, 2, 4), (11, 2, 5), (11, 2, 6), (11, 2, 7), (11, 2, 8), (11, 2, 9), (11, 2, 10), (11, 2, 11), (11, 2, 12)]]]


问:
Pushing and Pulling Columns - Bootstrap 4
This is what I need:

Desktop: B A

Mobile:

```<code>A
B
</code>```

Here is my HTML:

```<code><div class="row">

    <div class="col-md-7 col-sm-7 push-md-5">
        A
    </div>

    <div class="col-md-5 col-sm-5 pull-md-7">
        B
    </div>

</div>
</code>```

It is in correct order on mobile device but not on Desktop. I have tried a couple of guides and help material but without luck. In most guides they are moving equal columns like 4 or 6 so it's a bit confusing to understand it clearly.

答:
Since Bootstrap v4.x It is worth noting that the push-* and pull-* classes have been replaced by the order-* class.

Use .order- classes for controlling the visual order of your content. These classes are responsive, so you can set the order by breakpoint (e.g., .order-1.order-md-2). Includes support for 1 through 12 across all five grid tiers.

more details and examples can be found here

This means that your example (and answer):

            A

            B

```
<p>Becomes:</p>
<pre class="lang-html prettyprint-override"><code>    <div class="row">
        <div class="col-md-7 order-md-5">
            A
        </div>

        <div class="col-md-5 order-md-7">
            B
        </div>
    </div>
</code>```

And with the example given in the question, it would work.

However, as mentioned in the comments below, you don't need to use order-md-5 and order-md-7 as the order classes are not bound to the grid system other than to allow full control of the positioning of up to 12 columns.

This means that order-md-1 and order-md-2 are a more suitable solution for this.

There are also helpers such as this:

          First, but last

          Second, but unordered

          Third, but first

```

Body:
This is what I need:

Desktop: B A

Mobile:

A
B

Here is my HTML:

        A

        B

It is in correct order on mobile device but not on Desktop. I have tried a couple of guides and help material but without luck. In most guides they are moving equal columns like 4 or 6 so it's a bit confusing to understand it clearly.

Body:
Since Bootstrap v4.x It is worth noting that the push-* and pull-* classes have been replaced by the order-* class.

Use .order- classes for controlling the visual order of your content. These classes are responsive, so you can set the order by breakpoint (e.g., .order-1.order-md-2). Includes support for 1 through 12 across all five grid tiers.

more details and examples can be found here

This means that your example (and answer):

    <div class="row">
        <div class="col-md-7 push-md-5">
            A
        </div>

        <div class="col-md-5 pull-md-7">
            B
        </div>
    </div>

Becomes:

    <div class="row">
        <div class="col-md-7 order-md-5">
            A
        </div>

        <div class="col-md-5 order-md-7">
            B
        </div>
    </div>

And with the example given in the question, it would work.

However, as mentioned in the comments below, you don't need to use order-md-5 and order-md-7 as the order classes are not bound to the grid system other than to allow full control of the positioning of up to 12 columns.

This means that order-md-1 and order-md-2 are a more suitable solution for this.

There are also helpers such as this:

    <div class="container">
      <div class="row">
        <div class="col order-last">
          First, but last
        </div>
        <div class="col">
          Second, but unordered
        </div>
        <div class="col order-first">
          Third, but first
        </div>
      </div>
    </div>


问:
SQL multiple columns value multiplications
I want to multiply 2 columns in a single table the thing is one column is in the table but the other one is  calculated.

My table structure :

```<code>cart_id(pk)    pro_id(fk)    pro_name    pro_price
</code>```

My query is:

```<code>SELECT *, COUNT(pro_id) AS ID
FROM cart
WHERE session_id='" . $_SESSION['session'] . "'
GROUP BY pro_id;
</code>```

Now I want to calculate product price (pro_price) multiply ID which does not exist but calculated by product counts (count(pro_id)AS ID ).

答:
try

```<code>select pro_id, sum(pro_price)
from cart
where session_id='" . $_SESSION['session'] . "'
group by pro_id
</code>```

if the price is equal for all carts with identical pro_id, then sum(pro_price) equals count(*) * pro_price.

Body:
I want to multiply 2 columns in a single table the thing is one column is in the table but the other one is  calculated.

My table structure :

cart_id(pk)    pro_id(fk)    pro_name    pro_price

My query is:

SELECT *, COUNT(pro_id) AS ID
FROM cart
WHERE session_id='" . $_SESSION['session'] . "'
GROUP BY pro_id;

Now I want to calculate product price (pro_price) multiply ID which does not exist but calculated by product counts (count(pro_id)AS ID ).

Body:
try

select pro_id, sum(pro_price)
from cart
where session_id='" . $_SESSION['session'] . "'
group by pro_id

if the price is equal for all carts with identical pro_id, then sum(pro_price) equals count(*) * pro_price.


问:
Cannot insert explicit value for identity column in table 'TBL_AT_INOUT' when IDENTITY_INSERT is set OFF
```<code>Insert into HWT FINAL. DO. TBL_AT_INOUT
(ID)
SELECT ID FROM TBL_AT_INOUT_20171208
WHERE ID=904017
</code>```

Getting error while executing

答:
This is what you're looking for:</p>

```<code>IF object_id(N'tempdb..#test_table_01', N'U') IS NOT NULL
    DROP TABLE #test_table_01;

go

CREATE TABLE #test_table_01
  (
       [id]     INT IDENTITY(1, 1)
       , [name] SYSNAME
  );

--
-- fail method
-------------------------------------------------
BEGIN
    BEGIN try
        INSERT INTO #test_table_01
                    ([id]
                     , [name])
        VALUES      (1,N'Lucy');
    END try
    BEGIN catch
        SELECT N'This throws an error' AS [result]
               , ERROR_MESSAGE()       AS [error_message];
    END catch;

    SELECT N'No records were inserted' AS [note]
           , [id]
           , [name]
    FROM   #test_table_01;
END;

--
-- success method
-------------------------------------------------
BEGIN
    BEGIN try
        SET IDENTITY_INSERT #test_table_01 ON;

        INSERT INTO #test_table_01
                    ([id]
                     , [name])
        VALUES      (1,N'Lucy');

        --
        -- REMEMBER TO SET IDENTITY_INSERT BACK OFF!!!
        SET IDENTITY_INSERT #test_table_01 OFF;
    END try
    BEGIN catch
        SELECT N'This allows the insert' AS [result]
               , ERROR_MESSAGE()         AS [error_message];
    END catch;

    SELECT N'Records were inserted as desired!' AS [note]
           , [id]
           , [name]
    FROM   #test_table_01;
END;
</code>```

Body:
Insert into HWT FINAL. DO. TBL_AT_INOUT
(ID)
SELECT ID FROM TBL_AT_INOUT_20171208
WHERE ID=904017

Getting error while executing

Body:
This is what you're looking for:

IF object_id(N'tempdb..#test_table_01', N'U') IS NOT NULL
    DROP TABLE #test_table_01;

go

CREATE TABLE #test_table_01
  (
       [id]     INT IDENTITY(1, 1)
       , [name] SYSNAME
  );

--
-- fail method
-------------------------------------------------
BEGIN
    BEGIN try
        INSERT INTO #test_table_01
                    ([id]
                     , [name])
        VALUES      (1,N'Lucy');
    END try
    BEGIN catch
        SELECT N'This throws an error' AS [result]
               , ERROR_MESSAGE()       AS [error_message];
    END catch;

    SELECT N'No records were inserted' AS [note]
           , [id]
           , [name]
    FROM   #test_table_01;
END;

--
-- success method
-------------------------------------------------
BEGIN
    BEGIN try
        SET IDENTITY_INSERT #test_table_01 ON;

        INSERT INTO #test_table_01
                    ([id]
                     , [name])
        VALUES      (1,N'Lucy');

        --
        -- REMEMBER TO SET IDENTITY_INSERT BACK OFF!!!
        SET IDENTITY_INSERT #test_table_01 OFF;
    END try
    BEGIN catch
        SELECT N'This allows the insert' AS [result]
               , ERROR_MESSAGE()         AS [error_message];
    END catch;

    SELECT N'Records were inserted as desired!' AS [note]
           , [id]
           , [name]
    FROM   #test_table_01;
END;


问:
Getting string after first comma and before second comma
I have a string like this - "5,password,6099000,tree,city".

I want to extract only password from it. This means anything after first comma and before second comma.

How do I do this?

答:
The easiest solution might be to split the string on comma:</p>

```<code>String input = "5,password,6099000,tree,city";
String[] parts = input.split(",");
String password = parts[1];
</code>```

Body:
The easiest solution might be to split the string on comma:

String input = "5,password,6099000,tree,city";
String[] parts = input.split(",");
String password = parts[1];


问:
Robo 3T Error : Network is unreachable
I am trying to connect Robo 3T to my online database and it doesn't seem to be working. I am able to connect to local database with it. I tried connecting using MongoDB Compass and the Details and Auth are working fine and I am able to connect. But when I connect with the same details in Robo 3T, it doesn't seem to be working. How do I fix this?
I am using Robo 3T Version 1.1
I tried same with Robomongo 1.0, and still getting the same error

答: Just change your bind_ip in /etc/mongod.conf from 127.0.0.1 to 0.0.0.0 then restart the service, and it works for me~</p>

Title: Robo 3T Error : Network is unreachable


问:
SAS: Expressions in IF statement
does Sas provide mechanism of chain-expressions?

does Sas provide mechanism of In-clause?

Simple examples:

```<code>  a = '09MAY2010'd;
  b = '17MAY2010'd;

if (a<=c<=b) then do; /*code*/ end;
if (c in (a:b)) then do; /*code*/ end;
</code>```

maybe any good techniques of if/where statements?

your suggestions and advises, please.

Thanks!

答:
Apart from the IN operator, which only accepts constant values inside the paranthesis, there is also an (undocumented) IN function, which can be used with variables, so instead of if c in(a,b) you can use if in(c,a,b) which will work also when a and b are variables.

Another possibility is to use WHICHN or WHICHC functions, which has the same syntax, and which return 0 (FALSE) when a match is not found, and otherwise the number of the (first) match.

Title: SAS: Expressions in IF statement

Body:
does Sas provide mechanism of chain-expressions?

does Sas provide mechanism of In-clause?

Simple examples:

  a = '09MAY2010'd;
  b = '17MAY2010'd;

if (a<=c<=b) then do; /*code*/ end;
if (c in (a:b)) then do; /*code*/ end;

maybe any good techniques of if/where statements?

your suggestions and advises, please.

Thanks!


问:
"you are not allowed to access this page" error when using add_submenu_page
I'm using the add_submenu_page function of wp to add a sub menu inside a parent men, but I'm getting this error when accessing that submenu:

Sorry, you are not allowed to access this page.

I'm logged in as admin, flushed permalinks and logged out then logged in but nothing is changing.

my code:

```<code>class SPSetup {

    public function reg_func() {
        add_action( 'admin_menu', array( $this, 'sp_menu', ) );
    }

    public function sp_menu() {
        add_submenu_page(
            'montheme_options', 'SP Dashboard', 'SP Dashboard',
            'manage_options', 'sp-control',
            array( $this, 'callback' )
        );
    }
}

if ( class_exists( 'SPSetup ' ) ) {
    $SP= new SPSetup ();
    $SP->reg_func();
}
</code>```

答:
I had same issue.
Try to add priority in 'admin_menu' hook and remove hyphens from submenu slug.

```<code>add_action( 'admin_menu', array( $this, 'sp_menu'), 11);
</code>```

This solved my problem.

Also check this https://wordpress.stackexchange.com/questions/91377/admin-menu-as-submenu-from-another-plugin

Body:
I'm using the add_submenu_page function of wp to add a sub menu inside a parent men, but I'm getting this error when accessing that submenu:

Sorry, you are not allowed to access this page.

I'm logged in as admin, flushed permalinks and logged out then logged in but nothing is changing.

my code:

class SPSetup {

    public function reg_func() {
        add_action( 'admin_menu', array( $this, 'sp_menu', ) );
    }

    public function sp_menu() {
        add_submenu_page(
            'montheme_options', 'SP Dashboard', 'SP Dashboard',
            'manage_options', 'sp-control',
            array( $this, 'callback' )
        );
    }
}

if ( class_exists( 'SPSetup ' ) ) {
    $SP= new SPSetup ();
    $SP->reg_func();
}

Body:
I had same issue.
Try to add priority in 'admin_menu' hook and remove hyphens from submenu slug.

add_action( 'admin_menu', array( $this, 'sp_menu'), 11);

This solved my problem.

Also check this https://wordpress.stackexchange.com/questions/91377/admin-menu-as-submenu-from-another-plugin


问:
Excluding rows from sql operation when no entry exists for an earlier timestamp
I would like to sum over rows but only include values for which there exists a timestamp five minutes ago. I am using bigquery, which doesn't appear to support a timestamp_diff operation (but a datediff).

Consider the following data (mytable):

```<code>time (timestamp)    meter (int) value (float)
2013-07-03 07:50:00  1           3
2013-07-03 07:50:00  2           4
2013-07-03 07:55:00  1           3
2013-07-03 07:55:00  2           4
2013-07-03 08:00:00  1           3
2013-07-03 08:00:00  2           4
2013-07-03 08:05:00  1           3
2013-07-03 08:10:00  1           3
2013-07-03 08:10:00  2           4
</code>```

The query I would like to expand upon can first be defined as:

```<code>SELECT time, SUM(value) AS sumValue, COUNT(value) AS obs
FROM mytable
GROUP BY time
</code>```

The output is then:

```<code>time                 sumValue  obs
2013-07-03 07:50:00  7         2
2013-07-03 07:55:00  7         2
2013-07-03 08:00:00  7         2
2013-07-03 08:05:00  3         1
2013-07-03 08:10:00  7         2
</code>```

I would like this query to be expanded so that meter 2's value is not included in sumValue for 2013-07-03 08:10:00 (so sumValue here = 3), because it did not have an entry for five minutes earlier. Another consequence of this is that sumValue for the first timestamp would be zero. The desired output would then be:

```<code>time                 sumValue  obs
2013-07-03 07:50:00  0         0
2013-07-03 07:55:00  7         2
2013-07-03 08:00:00  7         2
2013-07-03 08:05:00  3         1
2013-07-03 08:10:00  3         1
</code>```

Can this be done in bigquery?

答:
Below is for BigQuery Standard SQL

#standardSQL
SELECT
  time,
  SUM(IF(delta = 300, value, 0)) sumValue,
  COUNTIF(delta = 300) obs
FROM (
  SELECT time, meter, value,
    UNIX_SECONDS(time) - LAG(UNIX_SECONDS(time))
        OVER(PARTITION BY meter ORDER BY time) delta
  FROM `project.dataset.table`
)
GROUP BY time
```

<p>You can test / play with above using dummy data from  your question   </p>

<pre class="lang-sql prettyprint-override"><code>#standardSQL
WITH `project.dataset.table` AS (
  SELECT TIMESTAMP '2013-07-03 07:50:00' time, 1 meter, 3 value UNION ALL
  SELECT TIMESTAMP '2013-07-03 07:50:00', 2, 4 UNION ALL
  SELECT TIMESTAMP '2013-07-03 07:55:00', 1, 3 UNION ALL
  SELECT TIMESTAMP '2013-07-03 07:55:00', 2, 4 UNION ALL
  SELECT TIMESTAMP '2013-07-03 08:00:00', 1, 3 UNION ALL
  SELECT TIMESTAMP '2013-07-03 08:00:00', 2, 4 UNION ALL
  SELECT TIMESTAMP '2013-07-03 08:05:00', 1, 3 UNION ALL
  SELECT TIMESTAMP '2013-07-03 08:10:00', 1, 3 UNION ALL
  SELECT TIMESTAMP '2013-07-03 08:10:00', 2, 4
)
SELECT
  time,
  SUM(IF(delta = 300, value, 0)) sumValue,
  COUNTIF(delta = 300) obs
FROM (
  SELECT time, meter, value,
    UNIX_SECONDS(time) - LAG(UNIX_SECONDS(time))
        OVER(PARTITION BY meter ORDER BY time) delta
  FROM `project.dataset.table`
)
GROUP BY time
ORDER BY time
</code>```

result is

time                        sumValue    obs
2013-07-03 07:50:00 UTC     0           0
2013-07-03 07:55:00 UTC     7           2
2013-07-03 08:00:00 UTC     7           2
2013-07-03 08:05:00 UTC     3           1
2013-07-03 08:10:00 UTC     3           1
```

Body:
I would like to sum over rows but only include values for which there exists a timestamp five minutes ago. I am using bigquery, which doesn't appear to support a timestamp_diff operation (but a datediff).

Consider the following data (mytable):

time (timestamp)    meter (int) value (float)
2013-07-03 07:50:00  1           3
2013-07-03 07:50:00  2           4
2013-07-03 07:55:00  1           3
2013-07-03 07:55:00  2           4
2013-07-03 08:00:00  1           3
2013-07-03 08:00:00  2           4
2013-07-03 08:05:00  1           3
2013-07-03 08:10:00  1           3
2013-07-03 08:10:00  2           4

The query I would like to expand upon can first be defined as:

SELECT time, SUM(value) AS sumValue, COUNT(value) AS obs
FROM mytable
GROUP BY time

The output is then:

time                 sumValue  obs
2013-07-03 07:50:00  7         2
2013-07-03 07:55:00  7         2
2013-07-03 08:00:00  7         2
2013-07-03 08:05:00  3         1
2013-07-03 08:10:00  7         2

I would like this query to be expanded so that meter 2's value is not included in sumValue for 2013-07-03 08:10:00 (so sumValue here = 3), because it did not have an entry for five minutes earlier. Another consequence of this is that sumValue for the first timestamp would be zero. The desired output would then be:

time                 sumValue  obs
2013-07-03 07:50:00  0         0
2013-07-03 07:55:00  7         2
2013-07-03 08:00:00  7         2
2013-07-03 08:05:00  3         1
2013-07-03 08:10:00  3         1

Can this be done in bigquery?

Body:
Below is for BigQuery Standard SQL

#standardSQL
SELECT
  time,
  SUM(IF(delta = 300, value, 0)) sumValue,
  COUNTIF(delta = 300) obs
FROM (
  SELECT time, meter, value,
    UNIX_SECONDS(time) - LAG(UNIX_SECONDS(time))
        OVER(PARTITION BY meter ORDER BY time) delta
  FROM `project.dataset.table`
)
GROUP BY time

You can test / play with above using dummy data from  your question

#standardSQL
WITH `project.dataset.table` AS (
  SELECT TIMESTAMP '2013-07-03 07:50:00' time, 1 meter, 3 value UNION ALL
  SELECT TIMESTAMP '2013-07-03 07:50:00', 2, 4 UNION ALL
  SELECT TIMESTAMP '2013-07-03 07:55:00', 1, 3 UNION ALL
  SELECT TIMESTAMP '2013-07-03 07:55:00', 2, 4 UNION ALL
  SELECT TIMESTAMP '2013-07-03 08:00:00', 1, 3 UNION ALL
  SELECT TIMESTAMP '2013-07-03 08:00:00', 2, 4 UNION ALL
  SELECT TIMESTAMP '2013-07-03 08:05:00', 1, 3 UNION ALL
  SELECT TIMESTAMP '2013-07-03 08:10:00', 1, 3 UNION ALL
  SELECT TIMESTAMP '2013-07-03 08:10:00', 2, 4
)
SELECT
  time,
  SUM(IF(delta = 300, value, 0)) sumValue,
  COUNTIF(delta = 300) obs
FROM (
  SELECT time, meter, value,
    UNIX_SECONDS(time) - LAG(UNIX_SECONDS(time))
        OVER(PARTITION BY meter ORDER BY time) delta
  FROM `project.dataset.table`
)
GROUP BY time
ORDER BY time

result is

time                        sumValue    obs
2013-07-03 07:50:00 UTC     0           0
2013-07-03 07:55:00 UTC     7           2
2013-07-03 08:00:00 UTC     7           2
2013-07-03 08:05:00 UTC     3           1
2013-07-03 08:10:00 UTC     3           1


答:
Use the function Split(),

```<code>String example = "5,password,6099000,tree,city";
String[] parts = example.split(",");
System.out.println(parts[1]);
</code>```

Also look here:
How to split a string in Java

Title: Getting string after first comma and before second comma

Body:
I have a string like this - "5,password,6099000,tree,city".

I want to extract only password from it. This means anything after first comma and before second comma.

How do I do this?

Body:
Use the function Split(),

String example = "5,password,6099000,tree,city";
String[] parts = example.split(",");
System.out.println(parts[1]);

Also look here:
How to split a string in Java


问:
Datatable is not showing after using django pagination
I am having problem with pagination in django. After using pagination,not even able to show table in the template.Please find below views.py and template.I mark the problem area. Any help will be much appreciated.</p>

答:
```<code>paginator=Paginator('test',10)# show 10 results per page
</code>```

here you pass a 'test' string to Paginator, instead pass test object so it will be

```<code>paginator=Paginator(test,10)# show 10 results per page
</code>```

hope it will work

Body:
paginator=Paginator('test',10)# show 10 results per page

here you pass a 'test' string to Paginator, instead pass test object so it will be

paginator=Paginator(test,10)# show 10 results per page

hope it will work


问:
Tomcat, Docker, Logging, and STDOUT?
I'm running tomcat in docker, but I can't see the logs. They are written to various log files under tomcat/logs, but I can't see them when tomcat is running in a docker container.

Here is my Dockerfile

```<code>FROM tomcat:7-jre8
COPY target/MYAPP.war /usr/local/tomcat/webapps/MYAPP.war
RUN ["/usr/local/tomcat/bin/catalina.sh", "start"]
</code>```

This is how I build image & start container from it:

```<code>docker build -t MYAPP .
docker run -it --rm -p 8080:8080 --name MYAPP MYAPP
</code>```

My app creates log file: /var/log/MYAPP.log after tomcat deploys MYAPP.war

How should I amend Dockerfile and which command should I use to run it ("docker run ...") so that right after starting the container MYAPP using the oneliner "docker run -it --rm -p 8080:8080 --name MYAPP MYAPP" the contents of /var/log/MYAPP.log would be printed to stdout?

I tried to add to Dockerfile the command below but it didn't help.

```<code>CMD tail -f /usr/local/MYAPP.log
</code>```

答:
May be it will be better to write logs directly to the stdout instead of the file in the container. It will be lost after restart.

See for more details https://12factor.net/logs

Title: Tomcat, Docker, Logging, and STDOUT?

Body:
I'm running tomcat in docker, but I can't see the logs. They are written to various log files under tomcat/logs, but I can't see them when tomcat is running in a docker container.

Here is my Dockerfile

FROM tomcat:7-jre8
COPY target/MYAPP.war /usr/local/tomcat/webapps/MYAPP.war
RUN ["/usr/local/tomcat/bin/catalina.sh", "start"]

This is how I build image & start container from it:

docker build -t MYAPP .
docker run -it --rm -p 8080:8080 --name MYAPP MYAPP

My app creates log file: /var/log/MYAPP.log after tomcat deploys MYAPP.war

How should I amend Dockerfile and which command should I use to run it ("docker run ...") so that right after starting the container MYAPP using the oneliner "docker run -it --rm -p 8080:8080 --name MYAPP MYAPP" the contents of /var/log/MYAPP.log would be printed to stdout?

I tried to add to Dockerfile the command below but it didn't help.

CMD tail -f /usr/local/MYAPP.log


问:
Separation of plane by line given two points
Given two points with x-y coordinates I have a line specified. Now I want to distinguish in an 2-d numpy array the points left to the line from those on the right.

The following code does the trick - but the double loop hurts my religious feelings (towards numpy). There must be a smarter way?

```<code>def myline(a_x,a_y,b_x,b_y):
start=np.zeros((100,100))
for x in range(100):
    for y in range(100):
        val= (b_x - a_x)*(y - a_y) - (x - a_x)*(b_y - a_y)
        if val<=0:
            start[x,y]=1
return start
</code>```

答:
This can be vectorized using ogrid:

```<code>x, y = np.ogrid[:100, :100]
start = (b_x - a_x)*(y - a_y) - (x - a_x)*(b_y - a_y) <= 0
</code>```

This will give you a boolean mask. If you want some other dtype

```<code>start = start.astype(np.int)
</code>```

Body:
Given two points with x-y coordinates I have a line specified. Now I want to distinguish in an 2-d numpy array the points left to the line from those on the right.

The following code does the trick - but the double loop hurts my religious feelings (towards numpy). There must be a smarter way?

def myline(a_x,a_y,b_x,b_y):
start=np.zeros((100,100))
for x in range(100):
    for y in range(100):
        val= (b_x - a_x)*(y - a_y) - (x - a_x)*(b_y - a_y)
        if val<=0:
            start[x,y]=1
return start

Body:
This can be vectorized using ogrid:

x, y = np.ogrid[:100, :100]
start = (b_x - a_x)*(y - a_y) - (x - a_x)*(b_y - a_y) <= 0

This will give you a boolean mask. If you want some other dtype

start = start.astype(np.int)


问:
Python Child object not accessing parent attribute
so I'm writing a program in PyQt5 and making use of the QObject class. Here's the basic program.

```<code>class Object(QObject):

    def __init__(self, parent=None):
        super(Object, self).__init__(parent)
        self.field = []

class Object2(Object):

    def __init__(self):
        super(Object, self).__init__()
        self.field.append(1)

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

But I'm getting this error:

```<code>AttributeError: 'Object2' object has no attribute 'field'
</code>```

I can't seem to find the cause of problem. Is it that a python child class cannot access it's parents attributes?

答:
The error you are getting is because of the arguments you are passing into super. In Python 2 it takes 2 arguments: The first argument is the current class (Object2), and the second argument is the current instance (self).

The issue is you've passed the parent class instead of the current class.

So you want:

```<code>class Object2(Object):
    def __init__(self):
        super(Object2, self).__init__() # Current class: Object2
        self.field.append(1)
</code>```

In Python 3, it is no longer required to pass these arguments into super. So you would just do:

```<code>class Object2(Object):
    def __init__(self):
        super().__init__()
        self.field.append(1)
</code>```

See also:

https://stackoverflow.com/a/5066411/7220776

Python 2 docs: https://docs.python.org/2/library/functions.html#super

Python 3 docs: https://docs.python.org/3/library/functions.html#super

Body:
so I'm writing a program in PyQt5 and making use of the QObject class. Here's the basic program.

class Object(QObject):

    def __init__(self, parent=None):
        super(Object, self).__init__(parent)
        self.field = []

class Object2(Object):

    def __init__(self):
        super(Object, self).__init__()
        self.field.append(1)

if __name__ == '__main__':
    o = Object2()

But I'm getting this error:

AttributeError: 'Object2' object has no attribute 'field'

I can't seem to find the cause of problem. Is it that a python child class cannot access it's parents attributes?

Body:
The error you are getting is because of the arguments you are passing into super. In Python 2 it takes 2 arguments: The first argument is the current class (Object2), and the second argument is the current instance (self).

The issue is you've passed the parent class instead of the current class.

So you want:

class Object2(Object):
    def __init__(self):
        super(Object2, self).__init__() # Current class: Object2
        self.field.append(1)

In Python 3, it is no longer required to pass these arguments into super. So you would just do:

class Object2(Object):
    def __init__(self):
        super().__init__()
        self.field.append(1)

See also:

https://stackoverflow.com/a/5066411/7220776

Python 2 docs: https://docs.python.org/2/library/functions.html#super

Python 3 docs: https://docs.python.org/3/library/functions.html#super


问:
Empty string variable matching to LIKE conditions in SQL
I have a SQL Server table containing a nvarchar(max) column. I ran a query to select every row where this column contains the string 'remove'. Amongst the results, I have several rows where this column is populated with an empty string and I don't understand why these values have been returned.

I tried to investigate further, on one of the empty string values returned. I found that the empty string value would match to certain LIKE conditions, but not others. For instance, it will match to %remove% and %x%, but it won't match to %q%.

Within the results grid on SQL Server Management Studio, the nvarchar field is displayed as an empty field (it is not null). However, if I apply the len() function to this field, it returns the value of 649. When I export the results table from SQL Server Management Studio into Excel, the nvarchar(max) field is empty.

Assuming that there must be a bunch of whitespace characters populating the field, I tried to select the field after concatenating 'x' to either end of the value returned. In the results, the leading 'x' appears at the beginning of the string, but the 'x' concatenated onto the end is not displayed.

I'm totally confused as to what is going on. I can provide more information upon request.

```<code>select itemid, content
from objects
where itemid = 100 and content like '%remove%'

----------------

itemid  |  content
100     |
</code>```

```<code>select itemid, 'x' + content + 'x' as 'content'
from objects
where itemid = 100 and content like '%remove%'

----------------

itemid  |  content
100     |  x
</code>```

EDIT:

Trimming the field doesn't change the character count. However, when I do use substring to select the last character in the concatenated output, the character returned is 'x', which suggests that it just isn't visible in the GUI output due to the length of the string. I still can't see this trailing 'x' character when exporting the content into Excel though. I think that there are maybe unsupported characters present within the nvarchar variable.

```<code>select itemid, 'x' + ltrim(rtrim(content)) + 'x' as 'content'
from objects
where itemid = 100 and content like '%remove%'

----------------

itemid  |  content
100     |  x
</code>```

答:
My guess is that you have some control character(s) in the string.  If the first character is a newline, for example, that may cause the rest not to be displayed.

Try

```<code>select item_id, unicode(content)
from objects
where item_id = 100;
</code>```

This will show the unicode code point for the first character you can see the second character with:

```<code>unicode(substring(item, 2, 1))
</code>```

and so on.

Body:
I have a SQL Server table containing a nvarchar(max) column. I ran a query to select every row where this column contains the string 'remove'. Amongst the results, I have several rows where this column is populated with an empty string and I don't understand why these values have been returned.

I tried to investigate further, on one of the empty string values returned. I found that the empty string value would match to certain LIKE conditions, but not others. For instance, it will match to %remove% and %x%, but it won't match to %q%.

Within the results grid on SQL Server Management Studio, the nvarchar field is displayed as an empty field (it is not null). However, if I apply the len() function to this field, it returns the value of 649. When I export the results table from SQL Server Management Studio into Excel, the nvarchar(max) field is empty.

Assuming that there must be a bunch of whitespace characters populating the field, I tried to select the field after concatenating 'x' to either end of the value returned. In the results, the leading 'x' appears at the beginning of the string, but the 'x' concatenated onto the end is not displayed.

I'm totally confused as to what is going on. I can provide more information upon request.

select itemid, content
from objects
where itemid = 100 and content like '%remove%'

----------------

itemid  |  content
100     |

select itemid, 'x' + content + 'x' as 'content'
from objects
where itemid = 100 and content like '%remove%'

----------------

itemid  |  content
100     |  x

EDIT:

Trimming the field doesn't change the character count. However, when I do use substring to select the last character in the concatenated output, the character returned is 'x', which suggests that it just isn't visible in the GUI output due to the length of the string. I still can't see this trailing 'x' character when exporting the content into Excel though. I think that there are maybe unsupported characters present within the nvarchar variable.

select itemid, 'x' + ltrim(rtrim(content)) + 'x' as 'content'
from objects
where itemid = 100 and content like '%remove%'

----------------

itemid  |  content
100     |  x

Body:
My guess is that you have some control character(s) in the string.  If the first character is a newline, for example, that may cause the rest not to be displayed.

Try

select item_id, unicode(content)
from objects
where item_id = 100;

This will show the unicode code point for the first character you can see the second character with:

unicode(substring(item, 2, 1))

and so on.


问:
Rails locale changing but paths in links stay the same
I have a multilingual application that changes language on a link that it is always at the top of the page.

```<code><%= link_to "English", :locale => 'en' %>
<%= link_to "French", :locale => 'fr'  %>
</code>```

When I click on any of the links, the param[:locale] changes, and all the translations appear ok. However, when I click on any url, the link stays with the current locale. It does not change the actual path with the new url.

Controller

```<code>  before_action :set_locale

  def default_url_options
    { locale: I18n.locale }
  end

  def set_locale
    I18n.locale = params[:locale]
  end
</code>```

Routes

```<code>  namespace :admin do
    scope "(:locale)", locale: /en|fr/ do
        // resources
    end
  end
</code>```

I would like to when I click the link to change locale, everything in the page changes including the paths. Currently it only loads the correct translation file but does not update the paths.

Thanks!

答:
change the routes to

```<code>scope "(:locale)", locale: /en|fr/ do
  namespace :admin do
    // resources
  end
end
</code>```

it will give you routes like fr fr/admin

then do not forget the route in the view

```<code><%=link_to 'English', root_path(locale: 'en') %>
</code>```

or the admin route

Body:
I have a multilingual application that changes language on a link that it is always at the top of the page.

<%= link_to "English", :locale => 'en' %>
<%= link_to "French", :locale => 'fr'  %>

When I click on any of the links, the param[:locale] changes, and all the translations appear ok. However, when I click on any url, the link stays with the current locale. It does not change the actual path with the new url.

Controller

  before_action :set_locale

  def default_url_options
    { locale: I18n.locale }
  end

  def set_locale
    I18n.locale = params[:locale]
  end

Routes

  namespace :admin do
    scope "(:locale)", locale: /en|fr/ do
        // resources
    end
  end

I would like to when I click the link to change locale, everything in the page changes including the paths. Currently it only loads the correct translation file but does not update the paths.

Thanks!

Body:
change the routes to

scope "(:locale)", locale: /en|fr/ do
  namespace :admin do
    // resources
  end
end

it will give you routes like fr fr/admin

then do not forget the route in the view

<%=link_to 'English', root_path(locale: 'en') %>

or the admin route


问:
Syntax error (missing operator) in query expression: System.Data.OleDb.OleDbException
I am sending the following SQL query in MS Access 2016 as a string in ASP WebForm:

```<code>string showGridViewQuery = "select creditorName, amount, interestRate, interestType, interestCalculationMethod, insertedDate, o.fullName as owner, u.fullName as dataInsertedBy from tbl_savings s left join tbl_users o on ownerID = o.userID left join tbl_users u on dataEnteredByID = u.userID";
</code>```

When I run, I get the following error:

System.Data.OleDb.OleDbException: Syntax error (missing operator) in query expression 'ownerID = o.userID left join tbl_users u on dataEnteredByID = u.userID'.

when the execution reaches showGridViewCommand.ExecuteNonQuery(); in the following code:

```<code>string connectionString = GetConnString();
OleDbConnection con = new OleDbConnection(connectionString);
con.Open();
string showGridViewQuery = "select creditorName, amount, interestRate, interestType, interestCalculationMethod, insertedDate, o.fullName as owner, u.fullName as dataInsertedBy from tbl_savings s left join tbl_users o on ownerID = o.userID left join tbl_users u on dataEnteredByID = u.userID";
OleDbCommand showGridViewCommand = new OleDbCommand(showGridViewQuery, con);
showGridViewCommand.ExecuteNonQuery();
DataTable dt = new DataTable();
OleDbDataAdapter olda = new OleDbDataAdapter(showGridViewCommand);
olda.Fill(dt);
GridViewSavingsTracker.DataSource = dt;
GridViewSavingsTracker.DataBind();
con.Close();
</code>```

What am I missing here?

答:
After a lot of trails, I was able to come to the right solution:

```<code>string showGridViewQuery = "select savingsID, creditorName, amount, interestRate, interestType, interestCalculationMethod, insertedDate, o.fullName as owner, u.fullName as dataEnteredBy from ((tbl_savings as s) left join tbl_users as o on s.ownerID = o.userID) left join tbl_users as u on s.dataEnteredByID = u.userID";
</code>```

I knew MS Access was bad. But didn't know it was THIS bad!

Body:
I am sending the following SQL query in MS Access 2016 as a string in ASP WebForm:

string showGridViewQuery = "select creditorName, amount, interestRate, interestType, interestCalculationMethod, insertedDate, o.fullName as owner, u.fullName as dataInsertedBy from tbl_savings s left join tbl_users o on ownerID = o.userID left join tbl_users u on dataEnteredByID = u.userID";

When I run, I get the following error:

System.Data.OleDb.OleDbException: Syntax error (missing operator) in query expression 'ownerID = o.userID left join tbl_users u on dataEnteredByID = u.userID'.

when the execution reaches showGridViewCommand.ExecuteNonQuery(); in the following code:

string connectionString = GetConnString();
OleDbConnection con = new OleDbConnection(connectionString);
con.Open();
string showGridViewQuery = "select creditorName, amount, interestRate, interestType, interestCalculationMethod, insertedDate, o.fullName as owner, u.fullName as dataInsertedBy from tbl_savings s left join tbl_users o on ownerID = o.userID left join tbl_users u on dataEnteredByID = u.userID";
OleDbCommand showGridViewCommand = new OleDbCommand(showGridViewQuery, con);
showGridViewCommand.ExecuteNonQuery();
DataTable dt = new DataTable();
OleDbDataAdapter olda = new OleDbDataAdapter(showGridViewCommand);
olda.Fill(dt);
GridViewSavingsTracker.DataSource = dt;
GridViewSavingsTracker.DataBind();
con.Close();

What am I missing here?

Body:
After a lot of trails, I was able to come to the right solution:

string showGridViewQuery = "select savingsID, creditorName, amount, interestRate, interestType, interestCalculationMethod, insertedDate, o.fullName as owner, u.fullName as dataEnteredBy from ((tbl_savings as s) left join tbl_users as o on s.ownerID = o.userID) left join tbl_users as u on s.dataEnteredByID = u.userID";

I knew MS Access was bad. But didn't know it was THIS bad!


问:
Connecting and manuplating data on an access database?
I'm working on my thesis project with Windows Phone 7. I'm developing an application requires store data in a database, my thesis supervisor said an Microsoft Access database is enough for this step, because I'm newbie at developing applications for Windows Phone 7.

How can i do that?

答:
For access 2010, IT allows one to build web databases. You need SharePoint (Enterprise), and access 2010. You also be able to use Office 365 and skydrive (not out yet).

The resulting access web database can thus be used on the windows 7 phone with the browser. In fact, I have a windows 7 phone and have tested my access applications on it.

In the following video, note how at the half way point, I swtich to using and running the access application in a web browser.

http://www.youtube.com/watch?v=AU4mH0jPntI


问:
Private server for firebase admin
My question is if I'm using firebase and I also need to do backend stuff, i.e. send an email to the user, register the user in my database. Then I will also need firebase's admin service account set up to verify the user. Now, can I use my own server to run admin service account or does firebase/Google force me to use Google's app engine?</p>

答:
The Firebase Admin SDK can be run on any server that can run the code.

For example, the Admin SDK for Node.js is just a regular node module. This means it can be run on any node environment: your own server, on App Engine Flex/GCE/GKE/etc, or on the serverless Cloud Functions for Firebase. All work equally fine.

Title: Private server for firebase admin


问:
If Value is true, create a new instance of an object
Create new instance of an object based on an if statement result comparing user input value with a random value. I want it to create a new instance of an object if that is true and do that each time this comparison yields true.

Would object.create() be the way to do this?

```<code> var firstthing = new thing();

 function createnewthing()
 {
    var entry = document.getElementById('theirentry').value;
    if (oneobjectinaclass == "type1")
    var firstvalueinarray = type1[0];
    else if (oneobjectinaclass == "type2")
    var firstvalueinarray = type2[0];
    else if (oneobjectinaclass == "type3")
    var firstvalueinanarray = type[0];
    if (variableassignedtowhichevertype[1] == avaluetocompare)
    {
        numCorrect++;
        alert('You\'re right! ' + numCorrect);

        //the code I'm trying to get to accomplish this goes here
        //var createanotherthingeachtimethisistrue = new Thing();

    }
    else {
        alert('Wrong!');
    }
}
</code>```

答:
Your problem arises from the concept of Scope, which in JavaScript to put it simple is based on functions.

Therefore, in order to solve your problem you can assign a variable outside of the current scope by typing

```<code>value = new Thing();
</code>```

Where value is a previously created variable in some functional context outside of the current function.

To dig deeper, we need to understand scopes in JavaScript. For more details, refer to Scope (computer science) and for more insight into the matter, Everything you wanted to know about JavaScript scope by Todd Motto goes over it in more detail.

To put it short; A scope is "created" whenever we enter a function, and the environment frame of that scope is used whenever we create or access variables. If a variable is not available, the outer context (or environment frame) is used. So to put it in an example.

Example 1

```<code>var toy = 'stick';
function changeToy() {
   var toy = 'ball';
}
changeToy();
</code>```

compared to Example 2

```<code>var toy = 'stick';
function changeToy() {
   toy = 'ball';
}
changeToy();
</code>```

In Example 1 a new variable will be created and assigned because the environment frame is local to the function changeToy. In Example 2 the variable toy is not found in the environment frame for changeToy, so the outer context (the global context in this case) is used; in which the variable is found, and reassigned.

Body:
Create new instance of an object based on an if statement result comparing user input value with a random value. I want it to create a new instance of an object if that is true and do that each time this comparison yields true.

Would object.create() be the way to do this?

 var firstthing = new thing();

 function createnewthing()
 {
    var entry = document.getElementById('theirentry').value;
    if (oneobjectinaclass == "type1")
    var firstvalueinarray = type1[0];
    else if (oneobjectinaclass == "type2")
    var firstvalueinarray = type2[0];
    else if (oneobjectinaclass == "type3")
    var firstvalueinanarray = type[0];
    if (variableassignedtowhichevertype[1] == avaluetocompare)
    {
        numCorrect++;
        alert('You\'re right! ' + numCorrect);

        //the code I'm trying to get to accomplish this goes here
        //var createanotherthingeachtimethisistrue = new Thing();

    }
    else {
        alert('Wrong!');
    }
}

Body:
Your problem arises from the concept of Scope, which in JavaScript to put it simple is based on functions.

Therefore, in order to solve your problem you can assign a variable outside of the current scope by typing

value = new Thing();

Where value is a previously created variable in some functional context outside of the current function.

To dig deeper, we need to understand scopes in JavaScript. For more details, refer to Scope (computer science) and for more insight into the matter, Everything you wanted to know about JavaScript scope by Todd Motto goes over it in more detail.

To put it short; A scope is "created" whenever we enter a function, and the environment frame of that scope is used whenever we create or access variables. If a variable is not available, the outer context (or environment frame) is used. So to put it in an example.

Example 1

var toy = 'stick';
function changeToy() {
   var toy = 'ball';
}
changeToy();

compared to Example 2

var toy = 'stick';
function changeToy() {
   toy = 'ball';
}
changeToy();

In Example 1 a new variable will be created and assigned because the environment frame is local to the function changeToy. In Example 2 the variable toy is not found in the environment frame for changeToy, so the outer context (the global context in this case) is used; in which the variable is found, and reassigned.


答:
there you go

this will work

```<code> String str="5,password,6099000,tree,city"
  String parts[]=str.split(",");
    String part1 = parts[0]; // 5
    String part2 = parts[1]; //Password

</code>```

Body:
there you go

this will work

 String str="5,password,6099000,tree,city"
  String parts[]=str.split(",");
    String part1 = parts[0]; // 5
    String part2 = parts[1]; //Password


问:
How do I pass arguments to bash?
So I am writing a bash script which will decrypt a file so I what the syntax of the the command to be decrypt [file.jpg]
 So far this is my script :

```<code>openssl enc -d -aes-256-cbc -in file.jpg > file
 echo "Please make sure you add the correct extension to
the file."
</code>```

Spent a lot time trying to achieve my goal but it doest work so I would like some help. Like suppose the file name is movie.mov I should be able to decrypt it using decrypt movie.mov or any other file.

EDIT: Thanks for all your answer but I found the answer which I approved to be simple and sorry I can't approve multiple answer all the answer give some new information!

答:
$1 will be the first argument you passed to your script, $2 the second, and so on.
Below is an example that takes $1 - the 1st argument and passes it to a function inside the script called decrypt_my_file. The function also use $1 as the 1st argument that was passed to it, kind of a small script inside your script </p>

```<code>   #!/bin/bash

    decrypt_my_file () {
      local file_that_was_given="${1}"

      openssl enc -d -aes-256-cbc -in "$file_that_was_given" \
            > decrypted."$file_that_was_given"
    }

    decrypt_my_file "$1"
</code>```

<p>this should then decrypt your filename, example ABC.jpg and created a decrypted file named
"decrypted.ABC.jpg" </p>

Title: How do I pass arguments to bash?

Body:
So I am writing a bash script which will decrypt a file so I what the syntax of the the command to be decrypt [file.jpg]
 So far this is my script :

openssl enc -d -aes-256-cbc -in file.jpg > file
 echo "Please make sure you add the correct extension to
the file."

Spent a lot time trying to achieve my goal but it doest work so I would like some help. Like suppose the file name is movie.mov I should be able to decrypt it using decrypt movie.mov or any other file.

EDIT: Thanks for all your answer but I found the answer which I approved to be simple and sorry I can't approve multiple answer all the answer give some new information!

Body:
$1 will be the first argument you passed to your script, $2 the second, and so on.
Below is an example that takes $1 - the 1st argument and passes it to a function inside the script called decrypt_my_file. The function also use $1 as the 1st argument that was passed to it, kind of a small script inside your script

   #!/bin/bash

    decrypt_my_file () {
      local file_that_was_given="${1}"

      openssl enc -d -aes-256-cbc -in "$file_that_was_given" \
            > decrypted."$file_that_was_given"
    }

    decrypt_my_file "$1"

this should then decrypt your filename, example ABC.jpg and created a decrypted file named
"decrypted.ABC.jpg"


问:
What is the rationale for limitations on pointer arithmetic or comparison?
In C/C++, addition or subtraction on pointer is defined only if the resulting pointer lies within the original pointed complete object. Moreover, comparison of two pointers can only be performed if the two pointed objects are subobjects of a unique complete object.

What are the reasons of such limitations?

I supposed that segmented memory model (see here §1.2.1) could be one of the reasons but since compilers can actually define a total order on all pointers as demonstrated by this answer, I am doubting this.

答:
There are architectures where program and data spaces are separated, and it's simply impossible to subtract two arbitrary pointers. A pointer to a function or to const static data will be in a completely different address space than a normal variable.

Even if you arbitrarily supplied a ranking between different address spaces, there's a possibility that the diff_t type would need to be a larger size. And the process of comparing or subtracting two pointers would be greatly complicated. That's a bad idea in a language that is designed for speed.


问:
Unable to lock files on Linux using java.nio.channels.FileLock
I was creating an application in Java for which I want only one instance running. For this purpose I created a file and got a lock while my application is running.

I have following code which works on Windows, but failed on Linux: once I acquire a lock without unlocking it I can get another lock on it.

```<code>import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.channels.FileChannel;
import java.nio.channels.FileLock;

public class MyApp {

private static File f;
private static FileChannel channel;
private static FileLock lock;

public static void main(String[] args) {
    try {
        f = new File("RingOnRequest.lock");
        // Check if the lock exist
        if (f.exists()) {
            // if exist try to delete it
            f.delete();
        }
        // Try to get the lock
        channel = new RandomAccessFile(f, "rw").getChannel();
        lock = channel.tryLock();
        if(lock == null)
        {
            // File is lock by other application
            channel.close();
            throw new RuntimeException("Only 1 instance of MyApp can run.");
        }
        // Add shutdown hook to release lock when application shutdown
        ShutdownHook shutdownHook = new ShutdownHook();
        Runtime.getRuntime().addShutdownHook(shutdownHook);

        //Your application tasks here..
        System.out.println("Running");
        try {
            Thread.sleep(10000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

    }
    catch(IOException e)
    {
        throw new RuntimeException("Could not start process.", e);
    }

}

public static void unlockFile() {
    // release and delete file lock
    try {
        if(lock != null) {
            lock.release();
            channel.close();
            f.delete();
        }
    } catch(IOException e) {
        e.printStackTrace();
    }
}

static class ShutdownHook extends Thread {

    public void run() {
        unlockFile();
    }
}

}
</code>```

答:
Recently i encountered the same kind of problem, but in my case i had an advantage: my application polled some directory only after some timeout. As my application did not immediately poll for directory i wrote special class that creates lock file with his own PID inside in init method, after  that before it tries to work with directory it needs to call ownedLock() - if it returns true then we can work otherwise exit(code is in Kotlin but you will get the main idea):

```<code>import java.io.File
import java.lang.management.ManagementFactory
class DirectoryLocker(private val directory: String, private val lockName: String) {
   private val lockFile by lazy { File("$directory/$lockName.lock") }

   // Will try to acquire lock to directory, whoever last writes its pid to file owns the directory
   fun acquireLock() = with(lockFile) {
      createNewFile()
      writeText(currentPID())
   }

   fun ownedLock(): Boolean = lockFilePid() == currentPID()

   fun releaseOwnedLock() {
      if(lockFilePid() == currentPID()) lockFile.delete()
   }

   private fun currentPID(): String {
      val processName = ManagementFactory.getRuntimeMXBean().name
      return processName.split("@".toRegex()).first()
   }

   private fun lockFilePid(): String? {
      return if(lockFile.exists()) lockFile.readLines().first() else null
   }
}
</code>```

Body:
I was creating an application in Java for which I want only one instance running. For this purpose I created a file and got a lock while my application is running.

I have following code which works on Windows, but failed on Linux: once I acquire a lock without unlocking it I can get another lock on it.

import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.channels.FileChannel;
import java.nio.channels.FileLock;

public class MyApp {

private static File f;
private static FileChannel channel;
private static FileLock lock;

public static void main(String[] args) {
    try {
        f = new File("RingOnRequest.lock");
        // Check if the lock exist
        if (f.exists()) {
            // if exist try to delete it
            f.delete();
        }
        // Try to get the lock
        channel = new RandomAccessFile(f, "rw").getChannel();
        lock = channel.tryLock();
        if(lock == null)
        {
            // File is lock by other application
            channel.close();
            throw new RuntimeException("Only 1 instance of MyApp can run.");
        }
        // Add shutdown hook to release lock when application shutdown
        ShutdownHook shutdownHook = new ShutdownHook();
        Runtime.getRuntime().addShutdownHook(shutdownHook);

        //Your application tasks here..
        System.out.println("Running");
        try {
            Thread.sleep(10000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

    }
    catch(IOException e)
    {
        throw new RuntimeException("Could not start process.", e);
    }

}

public static void unlockFile() {
    // release and delete file lock
    try {
        if(lock != null) {
            lock.release();
            channel.close();
            f.delete();
        }
    } catch(IOException e) {
        e.printStackTrace();
    }
}

static class ShutdownHook extends Thread {

    public void run() {
        unlockFile();
    }
}

}

Body:
Recently i encountered the same kind of problem, but in my case i had an advantage: my application polled some directory only after some timeout. As my application did not immediately poll for directory i wrote special class that creates lock file with his own PID inside in init method, after  that before it tries to work with directory it needs to call ownedLock() - if it returns true then we can work otherwise exit(code is in Kotlin but you will get the main idea):

import java.io.File
import java.lang.management.ManagementFactory
class DirectoryLocker(private val directory: String, private val lockName: String) {
   private val lockFile by lazy { File("$directory/$lockName.lock") }

   // Will try to acquire lock to directory, whoever last writes its pid to file owns the directory
   fun acquireLock() = with(lockFile) {
      createNewFile()
      writeText(currentPID())
   }

   fun ownedLock(): Boolean = lockFilePid() == currentPID()

   fun releaseOwnedLock() {
      if(lockFilePid() == currentPID()) lockFile.delete()
   }

   private fun currentPID(): String {
      val processName = ManagementFactory.getRuntimeMXBean().name
      return processName.split("@".toRegex()).first()
   }

   private fun lockFilePid(): String? {
      return if(lockFile.exists()) lockFile.readLines().first() else null
   }
}


问:
What are the Formspring authentication URLs? (OAuth iPhone)
I'm trying to gain authorization to Formspring using the OAuthConsumer found at https://github.com/jdg/oauthconsumer.

I've looked at many examples and thoroughly Googled for the answer, but I can't find the URL's you need to call for gaining access to the user's data.  URL's for authentication, token requesting, etc.  I imagine there should be something like: formspring.me/authentication or formspring.me/get_token_request etc, but I can't find anything.

Where can I look for these or if you know them what are they?

Thanks,
John

答:
The API is currently in beta. You need to request access at the following URL:
http://www.formstack.com/forms/?844272-7VPxuC7gnR

If you are granted access to the API, you'll be sent an email with more details on how to connect.


问:
Create one list of numbers by combining numbers from three lists of uneven length
I'm trying to create a list of id's, where the numbers are made up of three different lists: the first part of the number should be from the list pers:

```<code>pers = list(range(1,12))
</code>```

The second part should be a combination of the person id, and the number 1 or 2 (not necessarily a list, as it is just two numbers), like this:

```<code>ids = [11, 12, 21, 22, 31, 32, 41, 42, 51, 52, 61, 62, 71, 72, 81, 82, 91,
       92, 101, 102, 111, 112]
</code>```

The third part should be a combination of the above and the values in the list reps:

```<code>reps = list(range(1,13))
</code>```

like this:

```<code>ids = [111, 112, 113, 114, 115, 116, 117, 118, 119, 1110, 1111, 1112,
       121, 122, 123, 124, 125, 126, 127, 128, 129, 1210, 1211, 1212 ...]
</code>```

and so on, all the way up to 11212 (person 11, condition 2,  repetition 12). In total around 2250 items in the list.

I've tried various itertools functions, or nested for loops, lists of lists and tips in this post, but none seem to yield what I need.

答:
You can just use itertools.product as you suggested:

```<code>import itertools

pers = range(1,12)

ids = [1, 2]

reps = range(1,13)

combinations = [int("".join(map(str, x))) for x in itertools.product(pers, ids, reps)]

print(combinations[:20])
# [111, 112, 113, 114, 115, 116, 117, 118, 119, 1110, 1111, 1112, 121, 122, 123, 124, 125, 126, 127, 128]
</code>```

Body:
I'm trying to create a list of id's, where the numbers are made up of three different lists: the first part of the number should be from the list pers:

pers = list(range(1,12))

The second part should be a combination of the person id, and the number 1 or 2 (not necessarily a list, as it is just two numbers), like this:

ids = [11, 12, 21, 22, 31, 32, 41, 42, 51, 52, 61, 62, 71, 72, 81, 82, 91,
       92, 101, 102, 111, 112]

The third part should be a combination of the above and the values in the list reps:

reps = list(range(1,13))

like this:

ids = [111, 112, 113, 114, 115, 116, 117, 118, 119, 1110, 1111, 1112,
       121, 122, 123, 124, 125, 126, 127, 128, 129, 1210, 1211, 1212 ...]

and so on, all the way up to 11212 (person 11, condition 2,  repetition 12). In total around 2250 items in the list.

I've tried various itertools functions, or nested for loops, lists of lists and tips in this post, but none seem to yield what I need.

Body:
You can just use itertools.product as you suggested:

import itertools

pers = range(1,12)

ids = [1, 2]

reps = range(1,13)

combinations = [int("".join(map(str, x))) for x in itertools.product(pers, ids, reps)]

print(combinations[:20])
# [111, 112, 113, 114, 115, 116, 117, 118, 119, 1110, 1111, 1112, 121, 122, 123, 124, 125, 126, 127, 128]


问:
bat file programmatically press enter to go next line
When I run following command on cmd it ask me to press enter to continue. when I press enter it show the next thing and so on.we do this when  develop/create a new firefox addon using jpm tool.first it show default title if I hit enter it show default name and etc...

command jpm init

here is an snapshot

now I want to make a bat file for this. so it should go to next line like when I press enter .

I tried this. but it doesn't go to next line it show title..and wait..

create.bat

```<code>call jpm init
echo
echo
echo
echo
echo
echo
pause
</code>```

How can I make a bat file for this?

答:
another method, that may (or may not) work for you:

```<code><nul call jpm init
</code>```

Whenever an input is required, it is taken from the NUL device.

Pro: no need to know how many inputs are required

Con: every input request is answered with RETURN

Body:
When I run following command on cmd it ask me to press enter to continue. when I press enter it show the next thing and so on.we do this when  develop/create a new firefox addon using jpm tool.first it show default title if I hit enter it show default name and etc...

command jpm init

here is an snapshot

now I want to make a bat file for this. so it should go to next line like when I press enter .

I tried this. but it doesn't go to next line it show title..and wait..

create.bat

call jpm init
echo
echo
echo
echo
echo
echo
pause

How can I make a bat file for this?

Body:
another method, that may (or may not) work for you:

<nul call jpm init

Whenever an input is required, it is taken from the NUL device.

Pro: no need to know how many inputs are required

Con: every input request is answered with RETURN