问:
can i create ImageView programmatically before setcontentview android
can i initialize ImageView or any other view programmatically before setContentView(R.layout.activity_main); in android??

actually i am getting an instance of a custom class (not activity)
before onCreate method globally
like this

```<code>MyInAppPurchaseBilling myInAppPurchaseBilling = new MyInAppPurchaseBilling(MenuClass.this);
</code>```

and in that class constructor i have to use that context to initialize my preference class

```<code>public MyInAppPurchaseBilling(Activity launcher) {
        this.activity = launcher;
        tinyDB= new TinyDB(launcher);
    }
</code>```

Here is my logcat of error that i am facing

```<code>07-05 17:22:01.852 9660-9660/? E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.write.urdu.poetry.urdutexteditor, PID: 9660
java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.write.urdu.poetry.urdutexteditor/com.write.urdu.poetry.urdutexteditor.MenuClass}: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String android.content.Context.getPackageName()' on a null object reference
    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2339)
    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2494)
    at android.app.ActivityThread.access$900(ActivityThread.java:157)
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1356)
    at android.os.Handler.dispatchMessage(Handler.java:102)
    at android.os.Looper.loop(Looper.java:148)
    at android.app.ActivityThread.main(ActivityThread.java:5551)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:730)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:620)
 Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String android.content.Context.getPackageName()' on a null object reference
    at android.content.ContextWrapper.getPackageName(ContextWrapper.java:133)
    at android.preference.PreferenceManager.getDefaultSharedPreferencesName(PreferenceManager.java:375)
    at android.preference.PreferenceManager.getDefaultSharedPreferences(PreferenceManager.java:370)
    at com.write.urdu.poetry.urdutexteditor.TinyDB.<init>(TinyDB.java:55)
    at com.write.urdu.poetry.urdutexteditor.inapppurchase.MyInAppPurchaseBilling.<init>(MyInAppPurchaseBilling.java:48)
    at com.write.urdu.poetry.urdutexteditor.MenuClass.<init>(MenuClass.java:38)
    at java.lang.Class.newInstance(Native Method)
    at android.app.Instrumentation.newActivity(Instrumentation.java:1068)
    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2329)
    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2494)
    at android.app.ActivityThread.access$900(ActivityThread.java:157)
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1356)
    at android.os.Handler.dispatchMessage(Handler.java:102)
    at android.os.Looper.loop(Looper.java:148)
    at android.app.ActivityThread.main(ActivityThread.java:5551)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:730)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:620)
</code>```

答:
Try this:

```<code>View view = View.inflate(this, R.layout.activity_main, null); // view Exists after this code
TextView t = (TextView) view.findViewById(R.id.text);
setContentView(view);
t.setText("something");
</code>```

here you can see findViewById() is called before setContentView().  However the view exists because it is inflated but it might help you.

Body:
can i initialize ImageView or any other view programmatically before setContentView(R.layout.activity_main); in android??

actually i am getting an instance of a custom class (not activity)
before onCreate method globally
like this

MyInAppPurchaseBilling myInAppPurchaseBilling = new MyInAppPurchaseBilling(MenuClass.this);

and in that class constructor i have to use that context to initialize my preference class

public MyInAppPurchaseBilling(Activity launcher) {
        this.activity = launcher;
        tinyDB= new TinyDB(launcher);
    }

Here is my logcat of error that i am facing

07-05 17:22:01.852 9660-9660/? E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.write.urdu.poetry.urdutexteditor, PID: 9660
java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.write.urdu.poetry.urdutexteditor/com.write.urdu.poetry.urdutexteditor.MenuClass}: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String android.content.Context.getPackageName()' on a null object reference
    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2339)
    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2494)
    at android.app.ActivityThread.access$900(ActivityThread.java:157)
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1356)
    at android.os.Handler.dispatchMessage(Handler.java:102)
    at android.os.Looper.loop(Looper.java:148)
    at android.app.ActivityThread.main(ActivityThread.java:5551)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:730)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:620)
 Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String android.content.Context.getPackageName()' on a null object reference
    at android.content.ContextWrapper.getPackageName(ContextWrapper.java:133)
    at android.preference.PreferenceManager.getDefaultSharedPreferencesName(PreferenceManager.java:375)
    at android.preference.PreferenceManager.getDefaultSharedPreferences(PreferenceManager.java:370)
    at com.write.urdu.poetry.urdutexteditor.TinyDB.<init>(TinyDB.java:55)
    at com.write.urdu.poetry.urdutexteditor.inapppurchase.MyInAppPurchaseBilling.<init>(MyInAppPurchaseBilling.java:48)
    at com.write.urdu.poetry.urdutexteditor.MenuClass.<init>(MenuClass.java:38)
    at java.lang.Class.newInstance(Native Method)
    at android.app.Instrumentation.newActivity(Instrumentation.java:1068)
    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2329)
    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2494)
    at android.app.ActivityThread.access$900(ActivityThread.java:157)
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1356)
    at android.os.Handler.dispatchMessage(Handler.java:102)
    at android.os.Looper.loop(Looper.java:148)
    at android.app.ActivityThread.main(ActivityThread.java:5551)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:730)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:620)

Body:
Try this:

View view = View.inflate(this, R.layout.activity_main, null); // view Exists after this code
TextView t = (TextView) view.findViewById(R.id.text);
setContentView(view);
t.setText("something");

here you can see findViewById() is called before setContentView().  However the view exists because it is inflated but it might help you.


来源: stackexchange

问:
Getting a ConcurrentModificationException thrown when removing an element from a java.util.List during list iteration?
```<code>@Test
public void testListCur(){
    List<String> li=new ArrayList<String>();
    for(int i=0;i<10;i++){
        li.add("str"+i);
    }

    for(String st:li){
        if(st.equalsIgnoreCase("str3"))
            li.remove("str3");
    }
    System.out.println(li);
}
</code>```

When I run this code,I will throw a ConcurrentModificationException.

It looks as though when I remove the specified element from the list, the list does not know its size have been changed.

I'm wondering if this is a common problem with collections and removing elements?

答:
I think that best answer is from bigdev.de, but i would like to add something to it(like if the item is removed from a list, maybe you would like to log that somewhere or something):

List<String> list = new ArrayList<>();

list.removeIf(a -> {
                boolean condition = a.equalsIgnoreCase("some condition");
                if(condition)
                    logger.info("Item removed from the list: " + a);
                return condition;
  });
```

ContentLicense: CC BY-SA 4.0

Body:
@Test
public void testListCur(){
    List<String> li=new ArrayList<String>();
    for(int i=0;i<10;i++){
        li.add("str"+i);
    }

    for(String st:li){
        if(st.equalsIgnoreCase("str3"))
            li.remove("str3");
    }
    System.out.println(li);
}

When I run this code,I will throw a ConcurrentModificationException.

It looks as though when I remove the specified element from the list, the list does not know its size have been changed.

I'm wondering if this is a common problem with collections and removing elements?

ContentLicense: CC BY-SA 3.0


问:
GWT Cell Tree, Selecting too many options!
I am using a gwt cell tree and I want only one node to be selected in the whole tree but many nodes are being selected.

I am also trying this

```<code>S1= new SelectionModel();......
S1.setSelected(S1.getSelected(),false); but using this technique nothing is being selected.
</code>```

I am having the following problem:

Can someone help??

答: Code looks weird to me, because you firstly get selected object with S1.getSelected() command and then kinda re-select same object, so no wonder that nothing happens. Instead S1.getSelected() pass object that you want to select.

ContentLicense: CC BY-SA 2.5

Body:
I am using a gwt cell tree and I want only one node to be selected in the whole tree but many nodes are being selected.

I am also trying this

S1= new SelectionModel();......
S1.setSelected(S1.getSelected(),false); but using this technique nothing is being selected.

I am having the following problem:

Can someone help??


问:
How to get integer values from array based on first digits java
I have int number value and int[] numberArray.

I want to get all values from numberArray that starts with number.

What I am trying to do is

```<code>for (int i=0;i<numbers.length;i++){
    if(numberArray[i] "starts with" number){
        System.out.print(numberArray[i]);
     }
}
</code>```

I also need to use 2 and 3 digit numbers.

Could you help me find a solution for that?

EDIT: Thanks for help, found a solution. At the end code look like that:

```<code>String num = String.valueOf(number);
for (int i =0; i< numberArray.size();i++) {
    String anumber = String.valueOf(numberArray[i]);
    if (anumber.startsWith(num)){
        System.out.print(numberArray[i])
    }
}
</code>```

答:
If you don't want to perform any string conversions (while comparing) you can keep it to division.</p>

```<code>public void findIfStartingWithDigit(int number){
  int digits = String.valueOf(number).length();
  int tmpNumber;
  for (int i = 0; i < numbers.length; i++){
    tmpNumber = numbers[i];
    while (tmpNumber >= 10*digits){
      tmpNumber = tmpNumber / 10;
    }
    if (tmpNumber == number){
      System.out.println(numbers[i]);
    }
  }
}
</code>```

Body:
I have int number value and int[] numberArray.

I want to get all values from numberArray that starts with number.

What I am trying to do is

for (int i=0;i<numbers.length;i++){
    if(numberArray[i] "starts with" number){
        System.out.print(numberArray[i]);
     }
}

I also need to use 2 and 3 digit numbers.

Could you help me find a solution for that?

EDIT: Thanks for help, found a solution. At the end code look like that:

String num = String.valueOf(number);
for (int i =0; i< numberArray.size();i++) {
    String anumber = String.valueOf(numberArray[i]);
    if (anumber.startsWith(num)){
        System.out.print(numberArray[i])
    }
}

Body:
If you don't want to perform any string conversions (while comparing) you can keep it to division.

public void findIfStartingWithDigit(int number){
  int digits = String.valueOf(number).length();
  int tmpNumber;
  for (int i = 0; i < numbers.length; i++){
    tmpNumber = numbers[i];
    while (tmpNumber >= 10*digits){
      tmpNumber = tmpNumber / 10;
    }
    if (tmpNumber == number){
      System.out.println(numbers[i]);
    }
  }
}


问:
How to access child of a component in jest in a react/redux app
I like to test a component inside Connect in a Redux app:

```<code>this.component = TestUtils.renderIntoDocument(<Provider store={store}><Header path={this.path} /></Provider>);
</code>```

I have no idea about how to access Header inside Provider...(since I can not stop through in a debugger when running the jest from CLI.

So when I tried to get a child inside Header

```<code>      const path = findDOMNode(self.component.refs.pathElemSpan);
      console.log("path="+path)
</code>```

I got undefined on path

Any suggestion?

thanks

答:
Use enzyme, you have a bunch of nice selectors to navigate through your virtual DOM kingdom. :)

http://airbnb.io/enzyme/

A super simple test to access your component:

```<code>import { mount } from 'enzyme'
import Header from './header'

//... in your test
const wrapper = mount(<Provider store={store}><Header path='foo' /></Provider>)
const header = wrapper.find(Header).first()
expect(header.exists()).toBe(true)
// you can even check out the props
expect(header.prop('path')).toBe('foo')
</code>```

This example is using mount but you also have the option to do shallow rendering. I highly recommend you grab something to drink and read the docs a little. ;)

Body:
I like to test a component inside Connect in a Redux app:

this.component = TestUtils.renderIntoDocument(<Provider store={store}></Provider>);

I have no idea about how to access Header inside Provider...(since I can not stop through in a debugger when running the jest from CLI.

So when I tried to get a child inside Header

      const path = findDOMNode(self.component.refs.pathElemSpan);
      console.log("path="+path)

I got undefined on path

Any suggestion?

thanks

Body:
Use enzyme, you have a bunch of nice selectors to navigate through your virtual DOM kingdom. :)

http://airbnb.io/enzyme/

A super simple test to access your component:

import { mount } from 'enzyme'
import Header from './header'

//... in your test
const wrapper = mount(<Provider store={store}><Header path='foo' /></Provider>)
const header = wrapper.find(Header).first()
expect(header.exists()).toBe(true)
// you can even check out the props
expect(header.prop('path')).toBe('foo')

This example is using mount but you also have the option to do shallow rendering. I highly recommend you grab something to drink and read the docs a little. ;)


问:
Calculate Confidence interval over mean value for all the rows of a dataframe in Spark / Scala
I need to calculate confidence interval, max confidence interval and min confidence interval for my dataframe over mean value of value3 column and I need to apply it on all my dataframe. Here is my dataframe:

+--------+---------+------+
|  value1| value2  |value3|
+--------+---------+------+
|   a    |  2      |   3  |
+--------+---------+------+
|   b    |  5      |   4  |
+--------+---------+------+
|   b    |  5      |   4  |
+--------+---------+------+
|   c    |  3      |   4  |
+--------+---------+------+
```

<p>So my output should be something like below (x is the result of calculation):</p>

<pre class="lang-none prettyprint-override"><code>    +--------+---------+------+-------+--------+----------+
    |  value1| value2  |value3|max_int|min_int |    int   |      |
    +--------+---------+------+-------+--------+----------+
    |   a    |  2      |   3  |   x   |   x    |     x    |
    +--------+---------+------+-------+--------+----------+
    |   b    |  5      |   4  |   x   |   x    |     x    |
    +--------+---------+------+-------+--------+----------+
    |   b    |  5      |   4  |   x   |   x    |     x    |
    +--------+---------+------+-------+--------+----------+
    |   c    |  3      |   4  |   x   |   x    |     x    |
    +--------+---------+------+-------+--------+----------+
</code>```

Since I could't find a built-in function for it so, I found the following function to do that. Here is the code to calculate it.

```<code>    import org.apache.commons.math3.distribution.TDistribution
    import org.apache.commons.math3.exception.MathIllegalArgumentException
    import org.apache.commons.math3.stat.descriptive.SummaryStatistics
    import scala.collection.JavaConversions._

    object ConfidenceIntervalApp {

      def main(args: Array[String]): Unit = {

    ///my dataframe name is df

        }
    // Calculate 95% confidence interval
        val ci: Double = calcMeanCI(stats, 0.95)
        println(String.format("Mean: %f", stats.getMean))
        val lower: Double = stats.getMean - ci
        val upper: Double = stats.getMean + ci

      }
      def calcMeanCI(stats:Rdd, level: Double): Double =
        try {
    // Create T Distribution with N-1 degrees of freedom
          val tDist: TDistribution = new TDistribution(stats.getN - 1)
    // Calculate critical value
          val critVal: Double =
            tDist.inverseCumulativeProbability(1.0 - (1 - level) / 2)
    // Calculate confidence interval
          critVal * stats.getStandardDeviation / Math.sqrt(stats.getN)
        } catch {
          case e: MathIllegalArgumentException => java.lang.Double.NaN

        }

}
</code>```

Could you help or at least  guid me how to apply it on columns. Thanks in advance.

Can you help me?

答:
you can do something like

```<code>val cntInterval = df.select("value3").rdd.countApprox(timeout = 1000L,confidence = 0.95)
val (lowCnt,highCnt) = (cntInterval.getFinalValue().low, cntInterval.getFinalValue().high)

df.withColumn("max_int", lit(highCnt))
  .withColumn("min_int", lit(lowCnt))
  .withColumn("int", lit(cntInterval.getFinalValue().toString()))
  .show(false)
</code>```

I took help from In spark, how to estimate the number of elements in a dataframe quickly

Body:
I need to calculate confidence interval, max confidence interval and min confidence interval for my dataframe over mean value of value3 column and I need to apply it on all my dataframe. Here is my dataframe:

+--------+---------+------+
|  value1| value2  |value3|
+--------+---------+------+
|   a    |  2      |   3  |
+--------+---------+------+
|   b    |  5      |   4  |
+--------+---------+------+
|   b    |  5      |   4  |
+--------+---------+------+
|   c    |  3      |   4  |
+--------+---------+------+

So my output should be something like below (x is the result of calculation):

    +--------+---------+------+-------+--------+----------+
    |  value1| value2  |value3|max_int|min_int |    int   |      |
    +--------+---------+------+-------+--------+----------+
    |   a    |  2      |   3  |   x   |   x    |     x    |
    +--------+---------+------+-------+--------+----------+
    |   b    |  5      |   4  |   x   |   x    |     x    |
    +--------+---------+------+-------+--------+----------+
    |   b    |  5      |   4  |   x   |   x    |     x    |
    +--------+---------+------+-------+--------+----------+
    |   c    |  3      |   4  |   x   |   x    |     x    |
    +--------+---------+------+-------+--------+----------+

Since I could't find a built-in function for it so, I found the following function to do that. Here is the code to calculate it.

    import org.apache.commons.math3.distribution.TDistribution
    import org.apache.commons.math3.exception.MathIllegalArgumentException
    import org.apache.commons.math3.stat.descriptive.SummaryStatistics
    import scala.collection.JavaConversions._

    object ConfidenceIntervalApp {

      def main(args: Array[String]): Unit = {

    ///my dataframe name is df

        }
    // Calculate 95% confidence interval
        val ci: Double = calcMeanCI(stats, 0.95)
        println(String.format("Mean: %f", stats.getMean))
        val lower: Double = stats.getMean - ci
        val upper: Double = stats.getMean + ci

      }
      def calcMeanCI(stats:Rdd, level: Double): Double =
        try {
    // Create T Distribution with N-1 degrees of freedom
          val tDist: TDistribution = new TDistribution(stats.getN - 1)
    // Calculate critical value
          val critVal: Double =
            tDist.inverseCumulativeProbability(1.0 - (1 - level) / 2)
    // Calculate confidence interval
          critVal * stats.getStandardDeviation / Math.sqrt(stats.getN)
        } catch {
          case e: MathIllegalArgumentException => java.lang.Double.NaN

        }

}

Could you help or at least  guid me how to apply it on columns. Thanks in advance.

Can you help me?

Body:
you can do something like

val cntInterval = df.select("value3").rdd.countApprox(timeout = 1000L,confidence = 0.95)
val (lowCnt,highCnt) = (cntInterval.getFinalValue().low, cntInterval.getFinalValue().high)

df.withColumn("max_int", lit(highCnt))
  .withColumn("min_int", lit(lowCnt))
  .withColumn("int", lit(cntInterval.getFinalValue().toString()))
  .show(false)

I took help from In spark, how to estimate the number of elements in a dataframe quickly


问:
How to use azure file storage with Azure Function?
I have created two storage accounts, one have my azure function while another is a file storage account. What I want is to create a file from azure function and store it in my azure file storage. I went through official documentation of file storage as well as of Azure function, but I am not finding any connecting link between the two.

Is it possible to create file from azure function and store it in file storage account, if yes, please assist accordingly.

答:
There is a preview of Azure Functions External File bindings to upload file to external storage, but it doesn't work with Azure File Storage. There is a github issue to create a new type of binding for Files.

Meanwhile, you can upload the file just by using Azure Storage SDK directly. Something like

#r "Microsoft.WindowsAzure.Storage"
using Microsoft.WindowsAzure.Storage;
using Microsoft.WindowsAzure.Storage.File;

public static void Run(string input)
{
    var storageAccount = CloudStorageAccount.Parse("...");
    var fileClient = storageAccount.CreateCloudFileClient();
    var share = fileClient.GetShareReference("...");
    var rootDir = share.GetRootDirectoryReference();
    var sampleDir = rootDir.GetDirectoryReference("MyFolder");
    var fileToCreate = sampleDir.GetFileReference("output.txt");
    fileToCreate.UploadText("Hello " + input);
}
```


问:
Android Studio desgn mode for fullscreen app
I'm using AS 2.3.3 with a full screen app. I know how to put the app into full screen at run time but the design view still shows the status bar, a title and the nav buttons. How can I remove those from the preview so it looks as it will be when deployed?</p>

答: In your AS design view click the little round violet icon that says Theme. Select Theme dialog will pop up. Type "fullscreen" into the search bar and choose the full screen theme that works for you.


问:
Handling of binary data with Python + psycopg2 (DB: Postgres 9.5)
Lets say I have table test with columns id (of bigint type) & data (of bytea type).

I don't want to display actual binary data from column data when I execute below query in Python.

```<code>select * from test;
</code>```

I just want a place holder which display <binary data> or <BLOB>, because some of data are in hundreds of MB in that column which does not make any sense to display binary data in column.

Is it possible to identify and replace binary data with place holder in psycopg2 ?

```<code>#!/usr/bin/python

import psycopg2

conn = psycopg2.connect(database = "testdb", user = "postgres", password = "pass123", host = "127.0.0.1", port = "5432")
print "Opened database successfully"

cur = conn.cursor()

cur.execute("SELECT id, data from test")
rows = cur.fetchall()
for row in rows:
   print("ID = ", row[0])
   print("DATA = ", row[1])

print "Operation done successfully";
conn.close()
</code>```

We fetch the result from database and generate html report from the result, here user can provide any query in html textbox so query is not static, we execute that query and generate the html table. This is in-house report generation script.

答:
If the data is bytea you can write your own bytea typecaster as an object that wraps a binary string.

Note that the data is fetched and sent on the network anyway. If you don't want that overhead just don't select those fields.

```<code>>>> import psycopg2

>>> class Wrapper:
...     def __init__(self, thing):
...         self.thing = thing
...

>>> psycopg2.extensions.register_type(
...     psycopg2.extensions.new_type(
...         psycopg2.BINARY.values, "WRAPPER", lambda x, cur: Wrapper(x)))

>>> cnn = psycopg2.connect('')
>>> cur = cnn.cursor()
>>> cur.execute("create table btest(id serial primary key, data bytea)")
>>> cur.execute("insert into btest (data) values ('foobar')")
>>> cur.execute("select * from btest")
>>> r = cur.fetchone()
>>> r
(1, <__main__.Wrapper instance at 0x7fb8740eba70>)
>>> r[1].thing
'\\x666f6f626172'
</code>```

Please refer to the documentation for the extensions functions used.

Body:
Lets say I have table test with columns id (of bigint type) & data (of bytea type).

I don't want to display actual binary data from column data when I execute below query in Python.

select * from test;

I just want a place holder which display <binary data> or <BLOB>, because some of data are in hundreds of MB in that column which does not make any sense to display binary data in column.

Is it possible to identify and replace binary data with place holder in psycopg2 ?

#!/usr/bin/python

import psycopg2

conn = psycopg2.connect(database = "testdb", user = "postgres", password = "pass123", host = "127.0.0.1", port = "5432")
print "Opened database successfully"

cur = conn.cursor()

cur.execute("SELECT id, data from test")
rows = cur.fetchall()
for row in rows:
   print("ID = ", row[0])
   print("DATA = ", row[1])

print "Operation done successfully";
conn.close()

We fetch the result from database and generate html report from the result, here user can provide any query in html textbox so query is not static, we execute that query and generate the html table. This is in-house report generation script.

Body:
If the data is bytea you can write your own bytea typecaster as an object that wraps a binary string.

Note that the data is fetched and sent on the network anyway. If you don't want that overhead just don't select those fields.

>>> import psycopg2

>>> class Wrapper:
...     def __init__(self, thing):
...         self.thing = thing
...

>>> psycopg2.extensions.register_type(
...     psycopg2.extensions.new_type(
...         psycopg2.BINARY.values, "WRAPPER", lambda x, cur: Wrapper(x)))

>>> cnn = psycopg2.connect('')
>>> cur = cnn.cursor()
>>> cur.execute("create table btest(id serial primary key, data bytea)")
>>> cur.execute("insert into btest (data) values ('foobar')")
>>> cur.execute("select * from btest")
>>> r = cur.fetchone()
>>> r
(1, <__main__.Wrapper instance at 0x7fb8740eba70>)
>>> r[1].thing
'\\x666f6f626172'

Please refer to the documentation for the extensions functions used.


问:
making columns with specific textfile data in python 3.2
This is meant to ask a user for their username, find the username in a textfile and then output in columns, just their information. The information is ID, Last name, Year joined, Status, Nights booked and Points. How do I do this???</p>

```<code>import time
membr = int(input("Do you have a membership already?\n"
                  "1.Yes\n"
                  "2.No\n"
                  "Option: "))

if membr == 1:
    MemberID = []
    LastName = []
    YearJoined = []
    Status = []
    NightsBooked = []
    Points = []

    theirid = input("Please enter your id number (It is case sensitive): ")
    Myfile = open("Memberships.txt", "r")
    x = 0
    for line in Myfile:
        if theirid in line: return(line)
        information = line.split(",")
        MemberID.append(information[0])
        LastName.append(information[1])
        YearJoined.append(information[2])
        Status.append(information[3])
        NightsBooked.append(information[4])
        Points.append(information[5])
        x = x+1
    Myfile.close()
    print("{0:<18} {1:<18} {2:<18} {3:<18} {4:<18} {5:<18}".format("MemberID", "LastName", "YearJoined", "Status", "NightsBooked", "Points"))
    for y in range(1,x):
        print("{0:<18} {1:<18} {2:<18} {3:<18} {4:<18} {5:<18}".format(MemberID[y],LastName[y],YearJoined[y],Status[y],NightsBooked[y],Points[y]))
    time.sleep(2)
    mainmenu()
elif membr == 2:
    createnewuser()
else:
    print("Invalid")
    time.sleep(2)
    mainmenu()
</code>```

答:
You don't need to return the line there.</p>

```<code>    ...
    YearJoined = []
    Status = []
    NightsBooked = []
    Points = []

    theirid = input("Please enter your id number (It is case sensitive): ")
    Myfile = open("Memberships.txt", "r")
    x = 0
    for line in Myfile:
        # this will use the line found to do your work.
        if theirid in line:
            information = line.split(",")
            MemberID.append(information[0])
            LastName.append(information[1])
            YearJoined.append(information[2])
            Status.append(information[3])
            NightsBooked.append(information[4])
            Points.append(information[5])
            x = x+1
    Myfile.close()
    print("{0:<18} {1:<18} {2:<18} {3:<18} {4:<18} {5:<18}".format("MemberID", "LastName", "YearJoined", "Status", "NightsBooked", "Points"))
    for y in range(1,x):
        print("{0:<18} {1:<18} {2:<18} {3:<18} {4:<18} {5:<18}".format(MemberID[y],LastName[y],YearJoined[y],Status[y],NightsBooked[y],Points[y]))
    time.sleep(2)
    mainmenu()
elif membr == 2:
    createnewuser()
else:
    print("Invalid")
    time.sleep(2)
    mainmenu()
</code>```

Body:
This is meant to ask a user for their username, find the username in a textfile and then output in columns, just their information. The information is ID, Last name, Year joined, Status, Nights booked and Points. How do I do this???

import time
membr = int(input("Do you have a membership already?\n"
                  "1.Yes\n"
                  "2.No\n"
                  "Option: "))

if membr == 1:
    MemberID = []
    LastName = []
    YearJoined = []
    Status = []
    NightsBooked = []
    Points = []

    theirid = input("Please enter your id number (It is case sensitive): ")
    Myfile = open("Memberships.txt", "r")
    x = 0
    for line in Myfile:
        if theirid in line: return(line)
        information = line.split(",")
        MemberID.append(information[0])
        LastName.append(information[1])
        YearJoined.append(information[2])
        Status.append(information[3])
        NightsBooked.append(information[4])
        Points.append(information[5])
        x = x+1
    Myfile.close()
    print("{0:<18} {1:<18} {2:<18} {3:<18} {4:<18} {5:<18}".format("MemberID", "LastName", "YearJoined", "Status", "NightsBooked", "Points"))
    for y in range(1,x):
        print("{0:<18} {1:<18} {2:<18} {3:<18} {4:<18} {5:<18}".format(MemberID[y],LastName[y],YearJoined[y],Status[y],NightsBooked[y],Points[y]))
    time.sleep(2)
    mainmenu()
elif membr == 2:
    createnewuser()
else:
    print("Invalid")
    time.sleep(2)
    mainmenu()

Body:
You don't need to return the line there.

    ...
    YearJoined = []
    Status = []
    NightsBooked = []
    Points = []

    theirid = input("Please enter your id number (It is case sensitive): ")
    Myfile = open("Memberships.txt", "r")
    x = 0
    for line in Myfile:
        # this will use the line found to do your work.
        if theirid in line:
            information = line.split(",")
            MemberID.append(information[0])
            LastName.append(information[1])
            YearJoined.append(information[2])
            Status.append(information[3])
            NightsBooked.append(information[4])
            Points.append(information[5])
            x = x+1
    Myfile.close()
    print("{0:<18} {1:<18} {2:<18} {3:<18} {4:<18} {5:<18}".format("MemberID", "LastName", "YearJoined", "Status", "NightsBooked", "Points"))
    for y in range(1,x):
        print("{0:<18} {1:<18} {2:<18} {3:<18} {4:<18} {5:<18}".format(MemberID[y],LastName[y],YearJoined[y],Status[y],NightsBooked[y],Points[y]))
    time.sleep(2)
    mainmenu()
elif membr == 2:
    createnewuser()
else:
    print("Invalid")
    time.sleep(2)
    mainmenu()


问:
How can i add dynamic form field inside dynamic form field in angular?
I have created Dynamic add/delete form element using angular.

my expectation admin can add question first and admin can add options for that particular question question.

here i have added my code "ADD QUESTION" is working properly but once question added we need to create options for that particular question "ADD OPTIONS" not working properly

i have added both "ADD QUESTION" and "ADD OPTIONS" but when you add 2 or 3 question and remove its not working properly

for example i have added one question and 4 options for that qustion .after that if i click "ADD QUESTION" button question form is coming with 4 options field, here it should come only one option form field .its repeating the first question options

help me out to move forward

var app = angular.module('angularjs-starter', []);
app.controller('MainCtrl', function($scope) {

  $scope.data = {
   name: '',
    email: '',
    questions: [
      {
        id: 'choice1'
      }
    ],
 questionoption: [
      {
        id: 'option1'
      }
    ]
  };

  $scope.addNewChoice = function() {
    var newItemNo = $scope.data.questions.length + 1;
    $scope.data.questions.push({
      'id': 'choice' + newItemNo
    });
  };

  $scope.removeChoice = function() {
    var lastItem = $scope.data.questions.length - 1;
    $scope.data.questions.splice(lastItem);
  };

  $scope.OnSave = function() {
    console.log($scope.data);
  };

   $scope.addNewoptions = function() {
    var newItemNo = $scope.data.questionoption.length + 1;
    $scope.data.questionoption.push({
      'id': 'option' + newItemNo
    });
  };

  $scope.removeOption = function() {
    var lastItem = $scope.data.questionoption.length - 1;
    $scope.data.questionoption.splice(lastItem);
  };

});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>fieldset {
  background: #FCFCFC;
  padding: 16px;
  border: 1px solid #D5D5D5;
}
.fields {
  background: #FCFCFC;
  padding: 18px;
  border: 1px solid red;
}

.addfields {
  margin: 10px 0;
}

#choicesDisplay {
  padding: 10px;
  background: rgb(227, 250, 227);
  border: 1px solid rgb(171, 239, 171);
  color: rgb(9, 56, 9);
}

.remove {
  background: #C76868;
  color: #FFF;
  font-weight: bold;
  font-size: 21px;
  border: 0;
  cursor: pointer;
  display: inline-block;
  padding: 4px 9px;
  vertical-align: top;
  line-height: 100%;
}

input[type="text"],
select {
  padding: 5px;
}</code>```

  <button class="addfields" ng-click="addNewChoice()">Add question</button>

  name
  <input type="text" ng-model="data.name" name="" placeholder="Add name">

  email
  <input type="text" ng-model="data.email" name="" placeholder="Add emalil">

  <fieldset data-ng-repeat="choice in data.questions">
<button class="addfields" ng-click="addNewoptions()">Add options</button>

    Add Question

    <input type="text" ng-model="choice.name" name="" placeholder="Add Question">

    Question order
    <input type="text" ng-model="choice.order" name="" placeholder="Add Question order">

    <button class="remove" ng-show="$last" ng-click="removeChoice()">-</button>

   Add options

   <input type="text" ng-model="option.options" name="" placeholder="Add options">

   options order
   <input type="text" ng-model="option.order" name="" placeholder="Add Question order">

   <button class="remove" ng-show="$last" ng-click="removeOption()">-</button>

  </fieldset>

  <button type="submit" class="btn btn-primary" ng-click="OnSave()">Submit</button>

    {{ data.questions }}

```
</div>
</div>
</p>

<p>IF admin added one question(my expecttion result):</p>

```{

    "name": "test",
    "email": "as@gmail.com",
    "questions": [{
        "question": "Which of the following is the most important characteristic for a supervisor?",
        "questionorder": "1",
        "options": [{
                "val": "Approachable",
                "key": "options1"
            },
            {
                "val": "Qualified",
                "key": "options3"
            },
            {
                "val": "Honest",
                "key": "options2"
            }
        ]
    }]
}
```

DEMO

答:
Please refer this fiddle I have corrected your code working

Html code

```<code>    <div ng-app="angularjs-starter" ng-controller="MainCtrl">
  <button class="addfields" ng-click="addNewChoice()">Add question</button>
  <br>
  <label class="control-label col-sm-2">name</label>
  <input type="text" ng-model="data.name" name="" placeholder="Add name">
  <br>
  <br>
  <label class="control-label col-sm-2">email</label>
  <input type="text" ng-model="data.email" name="" placeholder="Add emalil">
  <br>
  <br>
  <fieldset data-ng-repeat="choice in data.questions" ng-init="Index = $index">
<button class="addfields" ng-click="addNewoptions(Index)">Add options</button><br>
    <label class="control-label col-sm-2">Add Question</label>

    <input type="text" ng-model="choice.name" name="" placeholder="Add Question">
    <br>
    <br>

    <label class="control-label col-sm-2">Question order</label>
    <input type="text" ng-model="choice.order" name="" placeholder="Add Question order">

    <button class="remove" ng-show="$last" ng-click="removeChoice()">-</button><br><br>
     <div class="fields" data-ng-repeat="option in choice.options">

      <br>
            <label class="control-label col-sm-2">Add options</label>

            <input type="text" ng-model="option.option" name="" placeholder="Add options">
            <br>
            <br>

            <label class="control-label col-sm-2">options order</label>
            <input type="text" ng-model="option.order" name="" placeholder="Add Question order">

            <button class="remove" ng-show="$last" ng-click="removeOption(Index)">-</button>
          </div>
  </fieldset>
  <br>
  <br>

  <button type="submit" class="btn btn-primary" ng-click="OnSave()">Submit</button>
  <br>
  <br>
  <br>

  <div id="choicesDisplay">
 <!--    {{ data.questions }} -->
  </div>
</div>
</code>```

Controller

```<code>    var app = angular.module('angularjs-starter', []);
app.controller('MainCtrl', function($scope) {

  $scope.data = {
    name: '',
    email: '',
    questions: [
      {
        id: 'choice1',
        options : [{
            optid:'option1'
        }]
      }]
  };

  $scope.addNewChoice = function() {
    var newItemNo = $scope.data.questions.length + 1;
    $scope.data.questions.push({
      'id': 'choice' + newItemNo,
      'options' : []
    });
  };

  $scope.removeChoice = function() {
    var lastItem = $scope.data.questions.length - 1;
    $scope.data.questions.splice(lastItem);
  };

  $scope.OnSave = function() {
    console.log($scope.data);
  };

  $scope.addNewoptions = function(quest) {
        var newItemNo = $scope.data.questions[quest].options.length + 1;
        $scope.data.questions[quest].options.push({
          'optid': 'option' + newItemNo
        });
  };

  $scope.removeOption = function(quest) {
    var lastItem = $scope.data.questions[quest].options.length - 1;
        $scope.data.questions[quest].options.splice(lastItem);

  };

});
</code>```

Body:
I have created Dynamic add/delete form element using angular.

my expectation admin can add question first and admin can add options for that particular question question.

here i have added my code "ADD QUESTION" is working properly but once question added we need to create options for that particular question "ADD OPTIONS" not working properly

i have added both "ADD QUESTION" and "ADD OPTIONS" but when you add 2 or 3 question and remove its not working properly

for example i have added one question and 4 options for that qustion .after that if i click "ADD QUESTION" button question form is coming with 4 options field, here it should come only one option form field .its repeating the first question options

help me out to move forward

var app = angular.module('angularjs-starter', []);
app.controller('MainCtrl', function($scope) {

  $scope.data = {
   name: '',
    email: '',
    questions: [
      {
        id: 'choice1'
      }
    ],
 questionoption: [
      {
        id: 'option1'
      }
    ]
  };

  $scope.addNewChoice = function() {
    var newItemNo = $scope.data.questions.length + 1;
    $scope.data.questions.push({
      'id': 'choice' + newItemNo
    });
  };

  $scope.removeChoice = function() {
    var lastItem = $scope.data.questions.length - 1;
    $scope.data.questions.splice(lastItem);
  };

  $scope.OnSave = function() {
    console.log($scope.data);
  };

   $scope.addNewoptions = function() {
    var newItemNo = $scope.data.questionoption.length + 1;
    $scope.data.questionoption.push({
      'id': 'option' + newItemNo
    });
  };

  $scope.removeOption = function() {
    var lastItem = $scope.data.questionoption.length - 1;
    $scope.data.questionoption.splice(lastItem);
  };

});

fieldset {
  background: #FCFCFC;
  padding: 16px;
  border: 1px solid #D5D5D5;
}
.fields {
  background: #FCFCFC;
  padding: 18px;
  border: 1px solid red;
}

.addfields {
  margin: 10px 0;
}

#choicesDisplay {
  padding: 10px;
  background: rgb(227, 250, 227);
  border: 1px solid rgb(171, 239, 171);
  color: rgb(9, 56, 9);
}

.remove {
  background: #C76868;
  color: #FFF;
  font-weight: bold;
  font-size: 21px;
  border: 0;
  cursor: pointer;
  display: inline-block;
  padding: 4px 9px;
  vertical-align: top;
  line-height: 100%;
}

input[type="text"],
select {
  padding: 5px;
}

  <button class="addfields" ng-click="addNewChoice()">Add question</button>

  name
  <input type="text" ng-model="data.name" name="" placeholder="Add name">

  email
  <input type="text" ng-model="data.email" name="" placeholder="Add emalil">

  <fieldset data-ng-repeat="choice in data.questions">
<button class="addfields" ng-click="addNewoptions()">Add options</button>

    Add Question

    <input type="text" ng-model="choice.name" name="" placeholder="Add Question">

    Question order
    <input type="text" ng-model="choice.order" name="" placeholder="Add Question order">

    <button class="remove" ng-show="$last" ng-click="removeChoice()">-</button>

   Add options

   <input type="text" ng-model="option.options" name="" placeholder="Add options">

   options order
   <input type="text" ng-model="option.order" name="" placeholder="Add Question order">

   <button class="remove" ng-show="$last" ng-click="removeOption()">-</button>

  </fieldset>

  <button type="submit" class="btn btn-primary" ng-click="OnSave()">Submit</button>

    {{ data.questions }}

IF admin added one question(my expecttion result):

{

    "name": "test",
    "email": "as@gmail.com",
    "questions": [{
        "question": "Which of the following is the most important characteristic for a supervisor?",
        "questionorder": "1",
        "options": [{
                "val": "Approachable",
                "key": "options1"
            },
            {
                "val": "Qualified",
                "key": "options3"
            },
            {
                "val": "Honest",
                "key": "options2"
            }
        ]
    }]
}

DEMO

Body:
Please refer this fiddle I have corrected your code working

Html code

    <div ng-app="angularjs-starter" ng-controller="MainCtrl">
  <button class="addfields" ng-click="addNewChoice()">Add question</button>
  <br>
  <label class="control-label col-sm-2">name</label>
  <input type="text" ng-model="data.name" name="" placeholder="Add name">
  <br>
  <br>
  <label class="control-label col-sm-2">email</label>
  <input type="text" ng-model="data.email" name="" placeholder="Add emalil">
  <br>
  <br>
  <fieldset data-ng-repeat="choice in data.questions" ng-init="Index = $index">
<button class="addfields" ng-click="addNewoptions(Index)">Add options</button><br>
    <label class="control-label col-sm-2">Add Question</label>

    <input type="text" ng-model="choice.name" name="" placeholder="Add Question">
    <br>
    <br>

    <label class="control-label col-sm-2">Question order</label>
    <input type="text" ng-model="choice.order" name="" placeholder="Add Question order">

    <button class="remove" ng-show="$last" ng-click="removeChoice()">-</button><br><br>
     <div class="fields" data-ng-repeat="option in choice.options">

      <br>
            <label class="control-label col-sm-2">Add options</label>

            <input type="text" ng-model="option.option" name="" placeholder="Add options">
            <br>
            <br>

            <label class="control-label col-sm-2">options order</label>
            <input type="text" ng-model="option.order" name="" placeholder="Add Question order">

            <button class="remove" ng-show="$last" ng-click="removeOption(Index)">-</button>
          </div>
  </fieldset>
  <br>
  <br>

  <button type="submit" class="btn btn-primary" ng-click="OnSave()">Submit</button>
  <br>
  <br>
  <br>

  <div id="choicesDisplay">
 <!--    {{ data.questions }} -->
  </div>
</div>

Controller

    var app = angular.module('angularjs-starter', []);
app.controller('MainCtrl', function($scope) {

  $scope.data = {
    name: '',
    email: '',
    questions: [
      {
        id: 'choice1',
        options : [{
            optid:'option1'
        }]
      }]
  };

  $scope.addNewChoice = function() {
    var newItemNo = $scope.data.questions.length + 1;
    $scope.data.questions.push({
      'id': 'choice' + newItemNo,
      'options' : []
    });
  };

  $scope.removeChoice = function() {
    var lastItem = $scope.data.questions.length - 1;
    $scope.data.questions.splice(lastItem);
  };

  $scope.OnSave = function() {
    console.log($scope.data);
  };

  $scope.addNewoptions = function(quest) {
        var newItemNo = $scope.data.questions[quest].options.length + 1;
        $scope.data.questions[quest].options.push({
          'optid': 'option' + newItemNo
        });
  };

  $scope.removeOption = function(quest) {
    var lastItem = $scope.data.questions[quest].options.length - 1;
        $scope.data.questions[quest].options.splice(lastItem);

  };

});


问:
Checking the input and output file are not the same in Python
I have a python script that takes in two arguments, the name of the input and output files, i.e. it starts of like

```<code>inputFile=open(sys.argv[1],'r')
outFile=open(sys.argv[2],'w')
</code>```

Then performs whatever operation reading from inputFile and writing to the outFile.

Now a few times through human error I've accidentally given the same argument twice, the result being that my input file is replaced with a blank line. Is there are a straight-forward way to stop this happening?

I thought it might be as simple as adding

```<code>if sys.argv[1]==sys.argv[2]:
        inputFile.close()
        outFile.close()
</code>```

immediately after the first lines above, but this already leaves the file blank.

答:
Simply do :

```<code>import os
if os.path.realpath(sys.argv[1]) != os.path.realpath(sys.argv[2]):
   inputFile=open(sys.argv[1],'r')
   outFile=open(sys.argv[2],'w')
else:
   raise ValueError('Input and output files are the same')
</code>```

This will prevent human mistakes by raising a welcomed error that won't destroy your input file.

os.path.realpath will transform any relative path to an absolute path, so that, even if the strings are different, you can raise the error when absolute paths are identical (thanks @Jean-François Fabre for reminding me this)

Body:
I have a python script that takes in two arguments, the name of the input and output files, i.e. it starts of like

inputFile=open(sys.argv[1],'r')
outFile=open(sys.argv[2],'w')

Then performs whatever operation reading from inputFile and writing to the outFile.

Now a few times through human error I've accidentally given the same argument twice, the result being that my input file is replaced with a blank line. Is there are a straight-forward way to stop this happening?

I thought it might be as simple as adding

if sys.argv[1]==sys.argv[2]:
        inputFile.close()
        outFile.close()

immediately after the first lines above, but this already leaves the file blank.

Body:
Simply do :

import os
if os.path.realpath(sys.argv[1]) != os.path.realpath(sys.argv[2]):
   inputFile=open(sys.argv[1],'r')
   outFile=open(sys.argv[2],'w')
else:
   raise ValueError('Input and output files are the same')

This will prevent human mistakes by raising a welcomed error that won't destroy your input file.

os.path.realpath will transform any relative path to an absolute path, so that, even if the strings are different, you can raise the error when absolute paths are identical (thanks @Jean-François Fabre for reminding me this)


问:
Get random phrases from an array in PHP?
I have this phrases ex: test 1, test 2, test 3, now how to show on load page in random mode?

ex function

```<code>function random()
{
    $array = ['test 1', 'test 2', 'test 3'];

    return $random_array;
}
</code>```

答:
The best and shortest solution in php is this:

```<code>$array = [
    'Sentence 1',
    'Sentence 2',
    'Sentence 3',
    'Sentence 4',
];

echo $array[array_rand($array)];
</code>```

Update: for above answers in as PHP 7.1 is to use random_int function instead of mt_rand since it's faster:

```<code>$array = [
    'Sentence 1',
    'Sentence 2',
    'Sentence 3',
    'Sentence 4',
];

echo $array[random_int(0, (count($array) - 1))];
</code>```

For more information about mt_rand v.s random_int see the link below:
  https://stackoverflow.com/a/28760905/2891689

Body:
I have this phrases ex: test 1, test 2, test 3, now how to show on load page in random mode?

ex function

function random()
{
    $array = ['test 1', 'test 2', 'test 3'];

    return $random_array;
}

Body:
The best and shortest solution in php is this:

$array = [
    'Sentence 1',
    'Sentence 2',
    'Sentence 3',
    'Sentence 4',
];

echo $array[array_rand($array)];

Update: for above answers in as PHP 7.1 is to use random_int function instead of mt_rand since it's faster:

$array = [
    'Sentence 1',
    'Sentence 2',
    'Sentence 3',
    'Sentence 4',
];

echo $array[random_int(0, (count($array) - 1))];

For more information about mt_rand v.s random_int see the link below:
  https://stackoverflow.com/a/28760905/2891689


问: Modifying

答:
May not be the "cleanest" way, but I found out somthing that actually works :

```<code>Style myStyle = (Style)this.Resources["myStyle"];

SetterBase sb = myStyle.Setters.FirstOrDefault(z => (z as Setter).Property == Rectangle.FillProperty);
int iSetterIndex = myStyle.Setters.IndexOf(sb);

myStyle.Setters[iSetterIndex] = new Setter(Rectangle.FillProperty, newScrollThumbBackground);
</code>```

It seems like I can't replace the value of the setter so instead I just find the old Setter index using property.  Then replace the setter at the found index by a new Setter object.

Title: Modifying <Style> from code

Body:
I need to modify a Style in resources from code.  I already know I can access the Setters like that :

 Style st = (Style)this.Resources["myStyle"];
 set.Setters.Etc...

But I need to change the value of a specific Setter in that style.  Is there any way to do it?

Also, how can I retrieve the appropriate setter in the setters list based on the "Property"

thanks

Body:
May not be the "cleanest" way, but I found out somthing that actually works :

Style myStyle = (Style)this.Resources["myStyle"];

SetterBase sb = myStyle.Setters.FirstOrDefault(z => (z as Setter).Property == Rectangle.FillProperty);
int iSetterIndex = myStyle.Setters.IndexOf(sb);

myStyle.Setters[iSetterIndex] = new Setter(Rectangle.FillProperty, newScrollThumbBackground);

It seems like I can't replace the value of the setter so instead I just find the old Setter index using property.  Then replace the setter at the found index by a new Setter object.


问:
Date picker: timezone shift

Problem

If I select a date in a <DateInput>, the datetime is in the user's timezone (e.g. 2017-07-01T00:00:00.000+02:00) but when it's sent to the server, it's transformed to UTC and thus ends up as 2017-06-30T22:00:00.000Z, one day behind.

The underlaying back-end is unaware of the user's timezone and cannot shift the dates back so after stripping the time it ends up with wrong date.

What would solve my problem

Any of these options would work fine:

The datetime is sent with the user's timezone.

The datetime is sent as naive (=without timezone).

The date selected by the user is already treated as UTC.

A date only (2017-07-01) instead of the ISO datetime is sent.

What I tried

I looked at Admin-on-rest's DateInput documentation and haven't found any option to alter the behaviour.

I looked at the related Material-UI's documentation and the only somewhat relevant option appears to be DateTimeFormat but despite a couple of tries I got nowhere.

I checked other answers, e.g Material UI Time Picker UTC but cannot figure out how to apply the suggested solution.

答:
Material UI date and timepickers return the local values. You can write a function in their onChange function to reformat the date to any value.

```<code>  handleTimeInput = (event, time) => {
    this.setState({
      time: time
    })
  }
</code>```

You can then reset the time you send to server by using a simple function like the one below to convert local time to UTC

```<code>export default (date) => {
  return new Date(date.getTime() + date.getTimezoneOffset()*60000)
}
</code>```

(for displaying)

```<code>export default (date) => {
  const tempDate = new Date(date)
  return new Date(tempDate.getTime() - tempDate.getTimezoneOffset()*60000)
}
</code>```

This is the entire component code for my comp.

```<code>class DateTimePicker extends Component {
  constructor(props) {
    super(props);
    this.state = {
      date: null,
      time: null
    };
  }
  handleDateInput = (event, date) => {
    this.setState({
      date: date
    })
  }
  handleTimeInput = (event, time) => {
    this.setState({
      time: time
    })
  }
  componentDidUpdate(prevProps, prevState) {
    const {setSchedule, channel} = this.props
    if (prevState.date !== this.state.date || prevState.time !== this.state.time) {
      if (this.state.date && this.state.time) {
        setSchedule(convertISTtoUTC(concatenateDateAndTime(this.state.date, this.state.time)), channel)
      }
    }
  }
  render() {
    return (
      <div >
          <DatePicker autoOk={true} onChange={this.handleDateInput} />
          <TimePicker autoOk={true} pedantic={true} onChange={this.handleTimeInput} />
      </div>
    )
  }
}
</code>```

With this you have 2 options.

1) you can hook this to redux directly and shoot actions when both are selected.

https://marmelab.com/admin-on-rest/Actions.html

2) Write your own Input component

https://marmelab.com/admin-on-rest/Inputs.html#writing-your-own-input-component

Title: Date picker: timezone shift

Body:
Material UI date and timepickers return the local values. You can write a function in their onChange function to reformat the date to any value.

  handleTimeInput = (event, time) => {
    this.setState({
      time: time
    })
  }

You can then reset the time you send to server by using a simple function like the one below to convert local time to UTC

export default (date) => {
  return new Date(date.getTime() + date.getTimezoneOffset()*60000)
}

(for displaying)

export default (date) => {
  const tempDate = new Date(date)
  return new Date(tempDate.getTime() - tempDate.getTimezoneOffset()*60000)
}

This is the entire component code for my comp.

class DateTimePicker extends Component {
  constructor(props) {
    super(props);
    this.state = {
      date: null,
      time: null
    };
  }
  handleDateInput = (event, date) => {
    this.setState({
      date: date
    })
  }
  handleTimeInput = (event, time) => {
    this.setState({
      time: time
    })
  }
  componentDidUpdate(prevProps, prevState) {
    const {setSchedule, channel} = this.props
    if (prevState.date !== this.state.date || prevState.time !== this.state.time) {
      if (this.state.date && this.state.time) {
        setSchedule(convertISTtoUTC(concatenateDateAndTime(this.state.date, this.state.time)), channel)
      }
    }
  }
  render() {
    return (
      <div >
          <DatePicker autoOk={true} onChange={this.handleDateInput} />
          <TimePicker autoOk={true} pedantic={true} onChange={this.handleTimeInput} />
      </div>
    )
  }
}

With this you have 2 options.

1) you can hook this to redux directly and shoot actions when both are selected.

https://marmelab.com/admin-on-rest/Actions.html

2) Write your own Input component

https://marmelab.com/admin-on-rest/Inputs.html#writing-your-own-input-component


问:
What are the different ways to Change font Style in Android Studio
I am new in android app development. I want to change fonts of my Application.
Just i wanna know different methods for change the font by XML and Java to.
 Want to change the font of :
1.TextView
2.RadioButton
3.EditText
4.CheckBox etc.</p>

答:
You can use various methods to change your font. One of them is:</p>

```<code>  Typeface typeface,typeface2;
  typeface = Typeface.createFromAsset(this.getAssets(),"fonts/Raleway-
  Regular.ttf");
  typeface2 = Typeface.createFromAsset(this.getAssets(),"fonts/Raleway-
  SemiBold.ttf");

  button1.setTypeface(typeface);
  edit_text1.setTypeface(typeface2);
</code>```

Body:
You can use various methods to change your font. One of them is:

  Typeface typeface,typeface2;
  typeface = Typeface.createFromAsset(this.getAssets(),"fonts/Raleway-
  Regular.ttf");
  typeface2 = Typeface.createFromAsset(this.getAssets(),"fonts/Raleway-
  SemiBold.ttf");

  button1.setTypeface(typeface);
  edit_text1.setTypeface(typeface2);


问:
Unable to chown although user exists
I am unable to "chown" to username from UID.

For example:

```<code>123456789 123456789 jdoe
--------------------------------------

chown jdoe:jdoe jdoe
</code>```

I get:

chown:invalid jdoe 'jdoe:jdoe'

but 'jdoe' exists.

答:
this gonna change owner of UID directory to jdoe

```<code>cd ~
cd ..
sudo chown -R jdoe:jdoe UID/
</code>```

Title: Unable to chown although user exists

Body:
I am unable to "chown" to username from UID.

For example:

123456789 123456789 jdoe
--------------------------------------

chown jdoe:jdoe jdoe

I get:

chown:invalid jdoe 'jdoe:jdoe'

but 'jdoe' exists.

Body:
this gonna change owner of UID directory to jdoe

cd ~
cd ..
sudo chown -R jdoe:jdoe UID/


问:
python3 urlopen raises 404 error while openning in the browser
I'm using urllib.request with python 3.4.6 to open https://www.ethz.ch/ (The actual url is longer but the problem is the same), which opens fine with Firefox but throws a 404 error with python.

Here is the code

```<code>from urllib.request import urlopen
connection = urlopen('https://www.ethz.ch/')
</code>```

and it gives the following error message

```<code>Traceback (most recent call last):
  File "./generate_group_meetings_ical.py", line 9, in <module>
    connection = urlopen('https://www.ethz.ch/')
  File "/usr/lib64/python3.4/urllib/request.py", line 161, in urlopen
    return opener.open(url, data, timeout)
  File "/usr/lib64/python3.4/urllib/request.py", line 470, in open
    response = meth(req, response)
  File "/usr/lib64/python3.4/urllib/request.py", line 580, in http_response
    'http', request, response, code, msg, hdrs)
  File "/usr/lib64/python3.4/urllib/request.py", line 508, in error
    return self._call_chain(*args)
  File "/usr/lib64/python3.4/urllib/request.py", line 442, in _call_chain
    result = func(*args)
  File "/usr/lib64/python3.4/urllib/request.py", line 588, in http_error_default
    raise HTTPError(req.full_url, code, msg, hdrs, fp)
urllib.error.HTTPError: HTTP Error 404: Not found UA
</code>```

The code used to work fine though. Another piece of information is that I'm not root on the machine and python3 was upgraded from 3.4.5 to 3.4.6. So the comes either from the web server side or from the python side. I'm not a python nor a web expert so I couldn't figure it out myself.

Hope anybody can help me.

答:
Thanks to Francisco's comment and that post I could make it work with the following code

```<code>from urllib.request import Request, urlopen
req = Request('https://www.ethz.ch/', headers={'User-Agent': 'Mozilla/5.0'})
connection = urlopen(req)
</code>```

I also checked the original version with python 2.7.13 and urllib2 and it worked. Apparently python 3.5 works (answer from Laxmikant) and it was originally working under 3.4.5. So something happened in the upgrade from 3.4.5 to 3.4.6 that caused the error.

Body:
I'm using urllib.request with python 3.4.6 to open https://www.ethz.ch/ (The actual url is longer but the problem is the same), which opens fine with Firefox but throws a 404 error with python.

Here is the code

from urllib.request import urlopen
connection = urlopen('https://www.ethz.ch/')

and it gives the following error message

Traceback (most recent call last):
  File "./generate_group_meetings_ical.py", line 9, in <module>
    connection = urlopen('https://www.ethz.ch/')
  File "/usr/lib64/python3.4/urllib/request.py", line 161, in urlopen
    return opener.open(url, data, timeout)
  File "/usr/lib64/python3.4/urllib/request.py", line 470, in open
    response = meth(req, response)
  File "/usr/lib64/python3.4/urllib/request.py", line 580, in http_response
    'http', request, response, code, msg, hdrs)
  File "/usr/lib64/python3.4/urllib/request.py", line 508, in error
    return self._call_chain(*args)
  File "/usr/lib64/python3.4/urllib/request.py", line 442, in _call_chain
    result = func(*args)
  File "/usr/lib64/python3.4/urllib/request.py", line 588, in http_error_default
    raise HTTPError(req.full_url, code, msg, hdrs, fp)
urllib.error.HTTPError: HTTP Error 404: Not found UA

The code used to work fine though. Another piece of information is that I'm not root on the machine and python3 was upgraded from 3.4.5 to 3.4.6. So the comes either from the web server side or from the python side. I'm not a python nor a web expert so I couldn't figure it out myself.

Hope anybody can help me.

Body:
Thanks to Francisco's comment and that post I could make it work with the following code

from urllib.request import Request, urlopen
req = Request('https://www.ethz.ch/', headers={'User-Agent': 'Mozilla/5.0'})
connection = urlopen(req)

I also checked the original version with python 2.7.13 and urllib2 and it worked. Apparently python 3.5 works (answer from Laxmikant) and it was originally working under 3.4.5. So something happened in the upgrade from 3.4.5 to 3.4.6 that caused the error.


问:
How can I center text (horizontally and vertically) inside a div block?
I have a div set to display:block (90px height and width), and I have some text inside.

I need the text to be aligned in the center both vertically and horizontally.

I have tried text-align:center, but it doesn't do the vertical centering part, so I tried vertical-align:middle, but it didn't work.

Any ideas?

答:
Approach 1

div {
  height: 90px;
  line-height: 90px;
  text-align: center;
  border: 2px dashed #f69c55;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div>
  Hello, World!!
</div></code>```

Approach 2

div {
  height: 200px;
  line-height: 200px;
  text-align: center;
  border: 2px dashed #f69c55;
}
span {
  display: inline-block;
  vertical-align: middle;
  line-height: normal;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div>
  <span>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Haec et tu ita posuisti, et verba vestra sunt. Non enim iam stirpis bonum quaeret, sed animalis. </span>
</div></code>```

Approach 3

div {
  display: table;
  height: 100px;
  width: 100%;
  text-align: center;
  border: 2px dashed #f69c55;
}
span {
  display: table-cell;
  vertical-align: middle;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div>
  <span>Lorem ipsum dolor sit amet, consectetur adipiscing elit.</span>
</div></code>```

Body:
Approach 1

div {
  height: 90px;
  line-height: 90px;
  text-align: center;
  border: 2px dashed #f69c55;
}

<div>
  Hello, World!!
</div>

Approach 2

div {
  height: 200px;
  line-height: 200px;
  text-align: center;
  border: 2px dashed #f69c55;
}
span {
  display: inline-block;
  vertical-align: middle;
  line-height: normal;
}

<div>
  <span>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Haec et tu ita posuisti, et verba vestra sunt. Non enim iam stirpis bonum quaeret, sed animalis. </span>
</div>

Approach 3

div {
  display: table;
  height: 100px;
  width: 100%;
  text-align: center;
  border: 2px dashed #f69c55;
}
span {
  display: table-cell;
  vertical-align: middle;
}

<div>
  <span>Lorem ipsum dolor sit amet, consectetur adipiscing elit.</span>
</div>


问:
Jquery - How do I extract and calculate numeric values from string
I need some assistance with extracting and calculation numeric values from the the strings based on id assigned to span text tags. For example I need to calculate 5% discount and display correct amount in another field.

```<code>  <span id="discount">5% off<span>
    <span id="price">£2.75</span>/per month</span>

$( document ).ready(function() { {
    var discount= "#discount"; // a string
    discount= discount.replace(/\D/g, ''); // a string of only digits, or the empty string
    var discount= parseInt(discount, 10); // now it's a numeric value

    var price= "#price"; // a string
    price= price.replace(/\D/g, ''); // a string of only digits, or the empty string
    var discount= parseInt(price, 10); // now it's a numeric value

    var discountValue = (discount * price) / 100;
    var newPrice= price + discount;
    $("#price").text(newPrice);
})
</code>```

I am not an experet of Jquery and JavaScript thus please understand my limited knowledge and I do appreciate if someone could explain how to achieve expected solution.
Thanks

答:
syntax error . extra curly brace in document.ready

Use jquery selector to get text of span using  $("#discount").text();

$( document ).ready(function() {
    var discount= $("#discount").text(); // a string

   discount= discount.replace(/\D+/g, '');

    // a string of only digits, or the empty string
    var discount= parseInt(discount, 10); // now it's a numeric value

    var price= $("#price").text(); // a string
    price= price.replace(/\D/g, ''); // a string of only digits, or the empty string
    var discount= parseInt(price, 10); // now it's a numeric value

    var discountValue = (discount * price) / 100;
    var newPrice= price + discount;
    $("#price").text(newPrice);
})```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span id="discount">5% off</span>
<span id="price">£2.75</span>/per month</code>```

Body:
I need some assistance with extracting and calculation numeric values from the the strings based on id assigned to span text tags. For example I need to calculate 5% discount and display correct amount in another field.

  5% off
    £2.75/per month

$( document ).ready(function() { {
    var discount= "#discount"; // a string
    discount= discount.replace(/\D/g, ''); // a string of only digits, or the empty string
    var discount= parseInt(discount, 10); // now it's a numeric value

    var price= "#price"; // a string
    price= price.replace(/\D/g, ''); // a string of only digits, or the empty string
    var discount= parseInt(price, 10); // now it's a numeric value

    var discountValue = (discount * price) / 100;
    var newPrice= price + discount;
    $("#price").text(newPrice);
})

I am not an experet of Jquery and JavaScript thus please understand my limited knowledge and I do appreciate if someone could explain how to achieve expected solution.
Thanks

Body:
syntax error . extra curly brace in document.ready

Use jquery selector to get text of span using  $("#discount").text();

$( document ).ready(function() {
    var discount= $("#discount").text(); // a string

   discount= discount.replace(/\D+/g, '');

    // a string of only digits, or the empty string
    var discount= parseInt(discount, 10); // now it's a numeric value

    var price= $("#price").text(); // a string
    price= price.replace(/\D/g, ''); // a string of only digits, or the empty string
    var discount= parseInt(price, 10); // now it's a numeric value

    var discountValue = (discount * price) / 100;
    var newPrice= price + discount;
    $("#price").text(newPrice);
})

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span id="discount">5% off</span>
<span id="price">£2.75</span>/per month


问:
difference between mongoose js virtuals and custom setter
Could someone clarify the difference between Mongoose JS's virtuals and custom setters comparatavely?

I searched on google nothing useful came out. To me it seems they serve to the same purpose, so why to keep them both?

答:
Mongoose supports virtual attributes. Virtual attributes are
  attributes that are convenient to have around but that do not get
  persisted to MongoDB.

http://mongoosejs.com/docs/2.7.x/docs/virtuals.html


问:
For loop not working in python
in outer loop i=156 ,it is not looping for other values of i=1,2,3,4.......I am trying to run this for loop in scrapy python . But first loop is not working

```<code>for i in range(1,157):
     start_urls = ["https://appworld.blackberry.com/cas/producttype/apps?"
          "countryid=100&lang=en&page={}&pagesize={}&"
          "sortby=popular&licensetype=all&callback=_producttype_apps"
          "&_=1499255634459".format(i, page) for page in xrange(1,1001)]
</code>```

The first loop outside the start_urls is not working
The results required is like this for page=1 pagesize should run from 1 to 1000 and when page=2 pagesize should again run from 1 to 1000 and so on till page=156

答:
Try converting the list into a tuple first
Then look for formatter sensitively affects. </p>

Title: For loop not working in python

Body:
in outer loop i=156 ,it is not looping for other values of i=1,2,3,4.......I am trying to run this for loop in scrapy python . But first loop is not working

for i in range(1,157):
     start_urls = ["https://appworld.blackberry.com/cas/producttype/apps?"
          "countryid=100&lang=en&page={}&pagesize={}&"
          "sortby=popular&licensetype=all&callback=_producttype_apps"
          "&_=1499255634459".format(i, page) for page in xrange(1,1001)]

The first loop outside the start_urls is not working
The results required is like this for page=1 pagesize should run from 1 to 1000 and when page=2 pagesize should again run from 1 to 1000 and so on till page=156


问:
Is there a way to trigger a JavaScript onclick event on an element that has pointer-events set to none?
I have an element that has pointer events set to none, this is so hover styles for child elements don't show.

However when this element is clicked on I want to do something with JavaScript. Using an onclick event in JavaScript does not seem to work because pointer-events is set to none.

Is there a way around this so that I can have an element with no pointer events that can still trigger a JavaScript event?

```<code>[data-drawer="open"] {
  .site-drawer {
    transform: translateX(0);
    transition: all .2s ease;
  }

  .site-container {
    transform: translateX(-27.5rem);
    // Disabling pointer events disables styles hover styles on below elements
    // But also disables clicking on container to remove it.
    pointer-events: none;
    transition: all .2s ease;
    &:after {
      position: fixed;
      top: 0;
      right: 0;
      bottom: 0;
      left: 0;
      background: rgba(0,0,0,.75);
      content: "";
    }
  }
}
</code>```

JavaScript:

```<code>  this.siteContainer.addEventListener('click', (e) => {
    console.log('site container clicked');
    if(document.body.hasAttribute('data-drawer')) {
      document.body.removeAttribute('data-drawer');
    }
  });
</code>```

Cheers

答:
You can use this work around. Set pointer-events: none to the element that has the hover effects, And add a wrapper div to the elements that still needs to be triggered on click.

$(".cant-click-this").on("click", function(ev) {
  console.log("You cant trigger the element, and it has no hover effects.");
});
$(".click-me-instead").on("click", function(ev) {
  console.log("You can trigger click through the wrapper.");
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.cant-click-this {
  pointer-events: none;
}

.cant-click-this:hover {
  color: red;
}</code>```

  <button class="cant-click-this"> Try to click me</button>
Hovering is futile.

```

Body:
I have an element that has pointer events set to none, this is so hover styles for child elements don't show.

However when this element is clicked on I want to do something with JavaScript. Using an onclick event in JavaScript does not seem to work because pointer-events is set to none.

Is there a way around this so that I can have an element with no pointer events that can still trigger a JavaScript event?

[data-drawer="open"] {
  .site-drawer {
    transform: translateX(0);
    transition: all .2s ease;
  }

  .site-container {
    transform: translateX(-27.5rem);
    // Disabling pointer events disables styles hover styles on below elements
    // But also disables clicking on container to remove it.
    pointer-events: none;
    transition: all .2s ease;
    &:after {
      position: fixed;
      top: 0;
      right: 0;
      bottom: 0;
      left: 0;
      background: rgba(0,0,0,.75);
      content: "";
    }
  }
}

JavaScript:

  this.siteContainer.addEventListener('click', (e) => {
    console.log('site container clicked');
    if(document.body.hasAttribute('data-drawer')) {
      document.body.removeAttribute('data-drawer');
    }
  });

Cheers

Body:
You can use this work around. Set pointer-events: none to the element that has the hover effects, And add a wrapper div to the elements that still needs to be triggered on click.

$(".cant-click-this").on("click", function(ev) {
  console.log("You cant trigger the element, and it has no hover effects.");
});
$(".click-me-instead").on("click", function(ev) {
  console.log("You can trigger click through the wrapper.");
});

.cant-click-this {
  pointer-events: none;
}

.cant-click-this:hover {
  color: red;
}

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

<div class="click-me-instead">
  <button class="cant-click-this"> Try to click me</button> <br>Hovering is futile.
</div>


问:
Website is not secure. Can it be fixed without https?
I have made a website for a small local company and on that website, there's a log-in-page so the staff can edit the content. The problem is that Google Chrome says the log-in-page isn't secure. I have tried searching for solutions, but everybody just says that I just make the website https. Are there other ways to do it? The company doesn't have the budget to pay for https.</p>

答:
Have a look at these guys. => https://letsencrypt.org/

Let’s Encrypt is a free, automated, and open certificate authority (CA), run for the public’s benefit. It is a service provided by the Internet Security Research Group (ISRG).

We give people the digital certificates they need in order to enable HTTPS (SSL/TLS) for websites, for free, in the most user-friendly way we can. We do this because we want to create a more secure and privacy-respecting Web.


问:
Why is the body height=0 on a newly created Jhipster project?
I just created my first jhipster application and followed the instructions on how to set up my IDE (eclipse).

After that, I ran the gradle bootRun task (in eclipse), and everything went fine.

When I visited the localhost address, the page was blank. Investigating the issue in firefox (f12), it showed that the body had a height of 0.

After trying to manually stretch the html body by setting its height manually to 100vt in the index.html file, another investigation via f12 showed, that the new settings was applied (the height was 100vt now), but the page was still blank.

What could be the issue? I already confirmed, that all needed files exist, so it cannot be a file not found issue

Interestingly, the page's name is displayed in the tab. As the name is defined in the index.html's header, the file must be correctly deployed, but there must be some kind of problem in the generated part.

EDIT

running yarn run webpack:build

```<code>yarn run v0.23.2
$ yarn run cleanup && yarn run webpack:build:vendor && yarn run webpack:build:dev
yarn run v0.23.2
$ rimraf build/{aot,www}
The command "rimraf" is either spelled incorrectly or could not be found
error Command failed with exit code 1.
info Visit https://yarnpkg.com/en/docs/cli/run for documentation about this command.
error Command failed with exit code 1.
info Visit https://yarnpkg.com/en/docs/cli/run for documentation about this command.
</code>```

EDIT 2

As someone mentioned in a comment, I may have to run yarn install, but this gives me the following error, which I do not understand at all...

```<code>error C:\CUBE\workspace\cube\node_modules\generator-jhipster: Command failed.
Exit code: 1
Command: C:\WINDOWS\system32\cmd.exe
Arguments: /d /s /c tabtab install --name jhipster --auto
Directory: C:\CUBE\workspace\cube\node_modules\generator-jhipster
Output:
Fri, 30 Jun 2017 14:40:09 GMT tabtab:installer Installing completion script to fish directory
fs.js:641
  return binding.open(pathModule._makeLong(path), stringToFlags(flags), mode);
                 ^
Error: ENOENT: no such file or directory, open 'C:\CUBE\workspace\cube\node_modules\tabtab\scripts\C:\Program Files\Git\usr\bin\bash.sh'
    at Error (native)
    at Object.fs.openSync (fs.js:641:18)
    at fs.readFileSync (fs.js:509:33)
    at Complete.script (C:\CUBE\workspace\cube\node_modules\tabtab\src\complete.js:373:14)
    at Installer.writeTo (C:\CUBE\workspace\cube\node_modules\tabtab\src\installer.js:91:34)
    at Installer.handle (C:\CUBE\workspace\cube\node_modules\tabtab\src\installer.js:80:21)
    at Commands.install (C:\CUBE\workspace\cube\node_modules\tabtab\src\commands\index.js:75:22)
    at Object.<anonymous> (C:\CUBE\workspace\cube\node_modules\tabtab\src\cli.js:33:16)
    at Module._compile (module.js:570:32)
    at Object.Module._extensions..js (module.js:579:10)
info Visit https://yarnpkg.com/en/docs/cli/install for documentation about this command.
</code>```

答:
I finally found the solution:

when generating the app with the git bash, there seems to be a faulty generation schedule on windows.

I re-generated the app with the windows cmd and everything worked as expected...

Body:
I just created my first jhipster application and followed the instructions on how to set up my IDE (eclipse).

After that, I ran the gradle bootRun task (in eclipse), and everything went fine.

When I visited the localhost address, the page was blank. Investigating the issue in firefox (f12), it showed that the body had a height of 0.

After trying to manually stretch the html body by setting its height manually to 100vt in the index.html file, another investigation via f12 showed, that the new settings was applied (the height was 100vt now), but the page was still blank.

What could be the issue? I already confirmed, that all needed files exist, so it cannot be a file not found issue

Interestingly, the page's name is displayed in the tab. As the name is defined in the index.html's header, the file must be correctly deployed, but there must be some kind of problem in the generated part.

EDIT

running yarn run webpack:build

yarn run v0.23.2
$ yarn run cleanup && yarn run webpack:build:vendor && yarn run webpack:build:dev
yarn run v0.23.2
$ rimraf build/{aot,www}
The command "rimraf" is either spelled incorrectly or could not be found
error Command failed with exit code 1.
info Visit https://yarnpkg.com/en/docs/cli/run for documentation about this command.
error Command failed with exit code 1.
info Visit https://yarnpkg.com/en/docs/cli/run for documentation about this command.

EDIT 2

As someone mentioned in a comment, I may have to run yarn install, but this gives me the following error, which I do not understand at all...

error C:\CUBE\workspace\cube\node_modules\generator-jhipster: Command failed.
Exit code: 1
Command: C:\WINDOWS\system32\cmd.exe
Arguments: /d /s /c tabtab install --name jhipster --auto
Directory: C:\CUBE\workspace\cube\node_modules\generator-jhipster
Output:
Fri, 30 Jun 2017 14:40:09 GMT tabtab:installer Installing completion script to fish directory
fs.js:641
  return binding.open(pathModule._makeLong(path), stringToFlags(flags), mode);
                 ^
Error: ENOENT: no such file or directory, open 'C:\CUBE\workspace\cube\node_modules\tabtab\scripts\C:\Program Files\Git\usr\bin\bash.sh'
    at Error (native)
    at Object.fs.openSync (fs.js:641:18)
    at fs.readFileSync (fs.js:509:33)
    at Complete.script (C:\CUBE\workspace\cube\node_modules\tabtab\src\complete.js:373:14)
    at Installer.writeTo (C:\CUBE\workspace\cube\node_modules\tabtab\src\installer.js:91:34)
    at Installer.handle (C:\CUBE\workspace\cube\node_modules\tabtab\src\installer.js:80:21)
    at Commands.install (C:\CUBE\workspace\cube\node_modules\tabtab\src\commands\index.js:75:22)
    at Object.<anonymous> (C:\CUBE\workspace\cube\node_modules\tabtab\src\cli.js:33:16)
    at Module._compile (module.js:570:32)
    at Object.Module._extensions..js (module.js:579:10)
info Visit https://yarnpkg.com/en/docs/cli/install for documentation about this command.


问:
Swap rows with columns (transposition) of a matrix in javascript
For instance I have a matrix like this:

```<code>|1 2 3|
|4 5 6|
|7 8 9|
</code>```

and I need it to convert into a matrix like this:

```<code>|1 4 7|
|2 5 8|
|3 6 9|
</code>```

What is the best and optimal way to achieve this goal?

答:
Just like in any other language:

```<code>int[][] copy = new int[columns][rows];
for (int i = 0; i < rows; ++i) {
    for (int j = 0; j < columns; ++j) {
        copy[j][i] = original[i][j];
    }
}
</code>```

You just have to construct the 2D array differently in JS. Like this:

function transpose(original) {
    var copy = [];
    for (var i = 0; i < original.length; ++i) {
        for (var j = 0; j < original[i].length; ++j) {
            // skip undefined values to preserve sparse array
            if (original[i][j] === undefined) continue;
            // create row if it doesn't exist yet
            if (copy[j] === undefined) copy[j] = [];
            // swap the x and y coords for the copy
            copy[j][i] = original[i][j];
        }
    }
    return copy;
}

console.log(transpose([
    [1,2,3],
    [4,5,6],
    [7,8,9]
]));```

Body:
For instance I have a matrix like this:

|1 2 3|
|4 5 6|
|7 8 9|

and I need it to convert into a matrix like this:

|1 4 7|
|2 5 8|
|3 6 9|

What is the best and optimal way to achieve this goal?

Body:
Just like in any other language:

int[][] copy = new int[columns][rows];
for (int i = 0; i < rows; ++i) {
    for (int j = 0; j < columns; ++j) {
        copy[j][i] = original[i][j];
    }
}

You just have to construct the 2D array differently in JS. Like this:

function transpose(original) {
    var copy = [];
    for (var i = 0; i < original.length; ++i) {
        for (var j = 0; j < original[i].length; ++j) {
            // skip undefined values to preserve sparse array
            if (original[i][j] === undefined) continue;
            // create row if it doesn't exist yet
            if (copy[j] === undefined) copy[j] = [];
            // swap the x and y coords for the copy
            copy[j][i] = original[i][j];
        }
    }
    return copy;
}

console.log(transpose([
    [1,2,3],
    [4,5,6],
    [7,8,9]
]));


问:
What is the correct way of parsing this json? Using ArduinoJson
I can't get the correct way to parse this JSON using ArduinoJson library

Here is the resulting json I need to parse.

```<code>{
"Error": false,
"Message": "Success",
"Sensor": [
    {
        "id": 10,
        "mac_address": "aabbccddeeff",
        "status": "ON"
    }
  ]
}
</code>```

May target value to get is the value of "status"

I tried to get some value and println it, but I got nothing?

Codes I tried so far.

```<code>  StaticJsonBuffer<100> jsonBuffer;
  HTTPClient http;
  http.begin(path);
  int httpCode = http.GET();
  String payload = http.getString();
  JsonObject& root = jsonBuffer.parseObject(payload);
  String state = root["Sensor"];
  Serial.println(payload);
  Serial.println(state);    //Print request response payload
</code>```

答:
Sensor is a list with a single object that has your desired property status.

```<code>String state = root["Sensor"][0]["status"];
</code>```

Body:
I can't get the correct way to parse this JSON using ArduinoJson library

Here is the resulting json I need to parse.

{
"Error": false,
"Message": "Success",
"Sensor": [
    {
        "id": 10,
        "mac_address": "aabbccddeeff",
        "status": "ON"
    }
  ]
}

May target value to get is the value of "status"

I tried to get some value and println it, but I got nothing?

Codes I tried so far.

  StaticJsonBuffer<100> jsonBuffer;
  HTTPClient http;
  http.begin(path);
  int httpCode = http.GET();
  String payload = http.getString();
  JsonObject& root = jsonBuffer.parseObject(payload);
  String state = root["Sensor"];
  Serial.println(payload);
  Serial.println(state);    //Print request response payload

Body:
Sensor is a list with a single object that has your desired property status.

String state = root["Sensor"][0]["status"];


答:
The input file is becoming blank because open(filename, 'w') overwrites a file with whatever needs to be placed in it.  'w' is useful for file creation and then writing to that file.  I'd suggest trying open(filename, 'a') for appending a pre-existing file.  I can't quite remember if this creates a file if it's not already existing, but it sounds like you have 2 existing files already, so append should be what you need.

If you decide to go the if sys.argv[1] == sys.argv[2] method, try placing str() around each item you're comparing, just to be certain it's comparing them properly.

Title: Checking the input and output file are not the same in Python

Body:
I have a python script that takes in two arguments, the name of the input and output files, i.e. it starts of like

inputFile=open(sys.argv[1],'r')
outFile=open(sys.argv[2],'w')

Then performs whatever operation reading from inputFile and writing to the outFile.

Now a few times through human error I've accidentally given the same argument twice, the result being that my input file is replaced with a blank line. Is there are a straight-forward way to stop this happening?

I thought it might be as simple as adding

if sys.argv[1]==sys.argv[2]:
        inputFile.close()
        outFile.close()

immediately after the first lines above, but this already leaves the file blank.


问:
How to send and retrive values through calling Intent in android?
I want to send calling contact number and contact id through Intent and retrive using BroadCast reciver.Is it possible, if possible then how?</p>

答:
After search and R&D I realise we can't do this thing.
I solve this problem using Globle class which contain contactNumber and contactId.
So initialize this static field and use when broadcast reciver hit.</p>


问:
Excel: SUMIF column A = x and (y or z)
Here is an example of the data I am using.

```<code>0 |      A      |    B
1 | Information |   Time
2 | ----------- | ---------
3 |   x y abc   |    3
4 |   x z abc   |    4
5 |   y z abc   |    5
</code>```

I would expect this to return the value 7.

I understand SUMIF(B:B,A:A,"x") and using SUMIF for multiple criteria but I am struggling to figure out how to integrate the ability for an and/or SUMIF.

DATA TABLE

```<code>50e flute dolley tripped twice          |   0.29
dolly tripped paser flute               |   0.21
No 5 tripeed. Waiting for sparky.       |   0.18
No 2 tripped - waiting for sparky.      |   0.14
No 2 dolly tripped - waiting for sparky |   0.09
Dolly tripped, waiting for sparky       |   0.08
No 2 dolly - waiting for sparky         |   0.08
50e flute dolly                         |   0.07
dolly tripped 50e flute                 |   0.06
no 2 dolley tripped                     |   0.06
50e flute dolley (side 1) tripped       |   0.06
No 2 - waiting for sparky               |   0.06
</code>```

I want 5 different functions for the 5 different reel dollies. So for number 5, I want to ensure I am only counting the no 5 dolly and not the 50e flute dolly. This is a dataset entered external so I want to be able to cover criteria that includes wrongly spelled words and multiple names for a particular reel dolly.

答:
I try to find any exact formula, but unable to find the same, we have some other trick by which you can do the same.

```<code>=(SUM(SUMIFS(D2:D11,A2:A11,"South", C2:C11,"Meat"),SUMIFS(D2:D11,A2:A11,"South", C2:C11,"Beverages")))
</code>```

or

```<code>=(SUMIFS(D2:D11,A2:A11,"South", C2:C11,"Meat")+SUMIFS(D2:D11,A2:A11,"South", C2:C11,"Beverages"))
</code>```

Hopefully this will help

Title: Excel: SUMIF column A = x and (y or z)

Body:
Here is an example of the data I am using.

0 |      A      |    B
1 | Information |   Time
2 | ----------- | ---------
3 |   x y abc   |    3
4 |   x z abc   |    4
5 |   y z abc   |    5

I would expect this to return the value 7.

I understand SUMIF(B:B,A:A,"x") and using SUMIF for multiple criteria but I am struggling to figure out how to integrate the ability for an and/or SUMIF.

DATA TABLE

50e flute dolley tripped twice          |   0.29
dolly tripped paser flute               |   0.21
No 5 tripeed. Waiting for sparky.       |   0.18
No 2 tripped - waiting for sparky.      |   0.14
No 2 dolly tripped - waiting for sparky |   0.09
Dolly tripped, waiting for sparky       |   0.08
No 2 dolly - waiting for sparky         |   0.08
50e flute dolly                         |   0.07
dolly tripped 50e flute                 |   0.06
no 2 dolley tripped                     |   0.06
50e flute dolley (side 1) tripped       |   0.06
No 2 - waiting for sparky               |   0.06

I want 5 different functions for the 5 different reel dollies. So for number 5, I want to ensure I am only counting the no 5 dolly and not the 50e flute dolly. This is a dataset entered external so I want to be able to cover criteria that includes wrongly spelled words and multiple names for a particular reel dolly.

Body:
I try to find any exact formula, but unable to find the same, we have some other trick by which you can do the same.

=(SUM(SUMIFS(D2:D11,A2:A11,"South", C2:C11,"Meat"),SUMIFS(D2:D11,A2:A11,"South", C2:C11,"Beverages")))

or

=(SUMIFS(D2:D11,A2:A11,"South", C2:C11,"Meat")+SUMIFS(D2:D11,A2:A11,"South", C2:C11,"Beverages"))

Hopefully this will help


答:
I would really suggest to solve this in the business logic, not with jquery in the frontend.

```<code>$(function(){
    var pattern = /[^0-9\.]/g;
    var discount = parseFloat($('#discount').html().replace(pattern, ""));
    var price = praseFloat($('#price').html().replace(pattern, ""));
    var result = price - price * (discount/100);
    console.log(result);
});
</code>```

update:

without jquery:

```<code>(function(d){
    var pattern = /[^0-9\.]/g;
    var discount = parseFloat(d.querySelector('#discount').innerHTML.replace(pattern, ""));
    var price = praseFloat(d.querySelector('#price').innerHTML.replace(pattern, ""));
    var result = price - price * (discount/100);
    console.log(result);
}(document);
</code>```

Why use a the self-executing anonymous function? To keep the global scope clean and make garbage collection of those vars possible.

Title: Jquery - How do I extract and calculate numeric values from string

Body:
I would really suggest to solve this in the business logic, not with jquery in the frontend.

$(function(){
    var pattern = /[^0-9\.]/g;
    var discount = parseFloat($('#discount').html().replace(pattern, ""));
    var price = praseFloat($('#price').html().replace(pattern, ""));
    var result = price - price * (discount/100);
    console.log(result);
});

update:

without jquery:

(function(d){
    var pattern = /[^0-9\.]/g;
    var discount = parseFloat(d.querySelector('#discount').innerHTML.replace(pattern, ""));
    var price = praseFloat(d.querySelector('#price').innerHTML.replace(pattern, ""));
    var result = price - price * (discount/100);
    console.log(result);
}(document);

Why use a the self-executing anonymous function? To keep the global scope clean and make garbage collection of those vars possible.


问:
How can I best parse this comma delimited text file?
I am trying to figure out the best way to parse this comma delimited text file. Here is an excerpt:

```<code>bldgA, fred, lunch
bldgA, sally, supper
bldgB, bob, parking lot
bldgB, frank, rooftop
...
</code>```

What I am trying to do is read "bldgA" and then I want the person (2nd column), "fred" for example. But I don't want to parse the file looking for "fred" because fred may not be there next time whereas bldgA always will be. I want to read the text file, see that I am on bldgA, and read the next item in my list which is fred. After that I want to test if it is fred, sally, etc.and print out the third column. I know this might be easier with a database but seems to be a bit of overhead for a small text file just so I can name columns. Before I resorted to Access or something small, I thought I'd try Stack Overflow. Here is what I have:

```<code>string BuildingFile = Server.MapPath("buildings.txt");
StreamReader FileStreamReader;

FileStreamReader = File.OpenText(BuildingFile);

while (FileStreamReader.Peek() != -1)
{
    string[] words;
    words = FileStreamReader.ReadLine().Split(',');

    foreach (string word in words)
    {
        if (word == "bldgA")
        {
            //but since word is only on "bldgA"
            //how can I get the next item in the list which
            //is on the same line?

            //print out the name of the person and then the duty
        }
        if (word == "bldgB")
        {
            //same as A
        }
    }

}
FileStreamReader.Close();
</code>```

My final output would be

"You are in bldgA and your name is fred and your duty is lunch"

答:
In pseudo-code:</p>

```<code>#!/usr/bin/env python
import csv

with open('buildings.txt') as csvfile:
    for building, name, duty in csv.reader(csvfile):
        print("You are in %(building)s"
              " and your name is %(name)s"
              " and your duty is %(duty)s" % vars())
</code>```

OwnerDisplayName: johnny

Body:
I am trying to figure out the best way to parse this comma delimited text file. Here is an excerpt:

bldgA, fred, lunch
bldgA, sally, supper
bldgB, bob, parking lot
bldgB, frank, rooftop
...

What I am trying to do is read "bldgA" and then I want the person (2nd column), "fred" for example. But I don't want to parse the file looking for "fred" because fred may not be there next time whereas bldgA always will be. I want to read the text file, see that I am on bldgA, and read the next item in my list which is fred. After that I want to test if it is fred, sally, etc.and print out the third column. I know this might be easier with a database but seems to be a bit of overhead for a small text file just so I can name columns. Before I resorted to Access or something small, I thought I'd try Stack Overflow. Here is what I have:

string BuildingFile = Server.MapPath("buildings.txt");
StreamReader FileStreamReader;

FileStreamReader = File.OpenText(BuildingFile);

while (FileStreamReader.Peek() != -1)
{
    string[] words;
    words = FileStreamReader.ReadLine().Split(',');

    foreach (string word in words)
    {
        if (word == "bldgA")
        {
            //but since word is only on "bldgA"
            //how can I get the next item in the list which
            //is on the same line?

            //print out the name of the person and then the duty
        }
        if (word == "bldgB")
        {
            //same as A
        }
    }

}
FileStreamReader.Close();

My final output would be

"You are in bldgA and your name is fred and your duty is lunch"

Body:
In pseudo-code:

#!/usr/bin/env python
import csv

with open('buildings.txt') as csvfile:
    for building, name, duty in csv.reader(csvfile):
        print("You are in %(building)s"
              " and your name is %(name)s"
              " and your duty is %(duty)s" % vars())

OwnerDisplayName: J.F. Sebastian

LastEditorDisplayName: J.F. Sebastian


问:
Looking for a new language that supports both interpreted and native compilation modes
I currently program in Perl, Python, C#, C, C++, Java, and a few other languages, and I'm looking for a new language to use as a primary when doing personal projects.

My current criteria are:

can  be run as an interpreted language (i.e., run without having to wait to compile it);

can be compiled to native code;

are strongly typed (even if optionally);

support macros/templating/code morphing/wtf you want to call it;

has a decent number of libraries for it, or easily accessible to it;

Ideas?  Suggestions?

答:
I would suggest that Haskell suits your criteria.

Can be run as an interpreted language? Yes, via GHCI.

Can be compiled to native code? Yes.

Is strongly typed? Very much so. Perhaps even the most strongly typed language today, with the exception of some theorem provers like Agda.

Support macros/templating/morphing? If you use template haskell. This is an optional extension of the language however, so most libraries don't use macros. I haven't used template haskell myself so i can't comment on if it's any good.

Has decent library support? The standard library is not bad. There is also Hackage, an open repository of Haskell libraries a bit in the style of CPAN.

Additionally, it sounds like you already know a lot of imperative/object oriented languages. IMHO if you learn another one of those langs. it will probably be a slightly different permutation of features you've already seen somewhere else. Adding another programming paradigm like functional programming to your toolbox will probably be a better learning experience. Though I guess whether that's an advantage or not depends on if you want to learn new things or be productive quickly.