问:
Android Instant Apps: Migration of existing multidex app to base/feature module?
I'm migrating my existing multi-dex app into an Instant app and converted my app into the recommended project structure.

There were a bunch of compilation issues related which were successfully resolved however while trying to run the install-able "application" module, I'm running into the following error as stated below in the stack trace.

I'm suspecting this is because my now baseFeature module (prior multi-dex app) is not compatible with the instant app architecture.

Any cues on what's the best way to handle this? If anyone can point to how would an existing multidex app port to the new instant app architecture, it would be great :)

Stack Trace:

```<code>Error converting bytecode to dex:
Cause: InvokeDynamic not supported
com.android.dx.cf.iface.ParseException: InvokeDynamic not supported
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
    at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
    at java.util.concurrent.ForkJoinTask.getThrowableException(ForkJoinTask.java:593)
    at java.util.concurrent.ForkJoinTask.reportException(ForkJoinTask.java:677)
    at java.util.concurrent.ForkJoinTask.join(ForkJoinTask.java:720)
    at com.android.ide.common.internal.WaitableExecutor.waitForTasksWithQuickFail(WaitableExecutor.java:146)
    at com.android.builder.dexing.DexArchiveBuilder.processOutputs(DexArchiveBuilder.java:110)
    at com.android.builder.dexing.DexArchiveBuilder.convert(DexArchiveBuilder.java:91)
    at com.android.build.gradle.internal.transforms.DexArchiveBuilderTransformCallable.lambda$cacheMissAction$0(DexArchiveBuilderTransformCallable.java:236)
    at com.android.builder.utils.FileCache.lambda$createFile$1(FileCache.java:260)
    at com.android.builder.utils.FileCache.lambda$null$5(FileCache.java:443)
    at com.android.builder.utils.SynchronizedFile.doActionWithSingleProcessLocking(SynchronizedFile.java:291)
    at com.android.builder.utils.SynchronizedFile.write(SynchronizedFile.java:234)
    at com.android.builder.utils.FileCache.lambda$queryCacheEntry$6(FileCache.java:415)
    at com.android.builder.utils.SynchronizedFile.doActionWithSingleProcessLocking(SynchronizedFile.java:291)
    at com.android.builder.utils.SynchronizedFile.read(SynchronizedFile.java:217)
    at com.android.builder.utils.FileCache.queryCacheEntry(FileCache.java:391)
    at com.android.builder.utils.FileCache.createFile(FileCache.java:273)
    at com.android.build.gradle.internal.transforms.DexArchiveBuilderTransformCallable.getFromCacheAndCreateIfMissing(DexArchiveBuilderTransformCallable.java:185)
    at com.android.build.gradle.internal.transforms.DexArchiveBuilderTransformCallable.call(DexArchiveBuilderTransformCallable.java:147)
    at com.android.build.gradle.internal.transforms.DexArchiveBuilderTransformCallable.call(DexArchiveBuilderTransformCallable.java:53)
    at java.util.concurrent.ForkJoinTask$AdaptedCallable.exec(ForkJoinTask.java:1424)
    at java.util.concurrent.ForkJoinTask.doExec(ForkJoinTask.java:289)
    at java.util.concurrent.ForkJoinPool$WorkQueue.runTask(ForkJoinPool.java:1056)
    at java.util.concurrent.ForkJoinPool.runWorker(ForkJoinPool.java:1692)
    at java.util.concurrent.ForkJoinWorkerThread.run(ForkJoinWorkerThread.java:157)
Caused by: com.android.dx.cf.iface.ParseException: InvokeDynamic not supported
    at com.android.dx.cf.cst.ConstantPoolParser.determineOffsets(ConstantPoolParser.java:226)
    at com.android.dx.cf.cst.ConstantPoolParser.parse(ConstantPoolParser.java:132)
    at com.android.dx.cf.cst.ConstantPoolParser.parseIfNecessary(ConstantPoolParser.java:124)
    at com.android.dx.cf.cst.ConstantPoolParser.getPool(ConstantPoolParser.java:115)
    at com.android.dx.cf.direct.DirectClassFile.parse0(DirectClassFile.java:491)
    at com.android.dx.cf.direct.DirectClassFile.parse(DirectClassFile.java:406)
    at com.android.dx.cf.direct.DirectClassFile.parseToInterfacesIfNecessary(DirectClassFile.java:388)
    at com.android.dx.cf.direct.DirectClassFile.getMagic(DirectClassFile.java:251)
    at com.android.builder.dexing.DexArchiveBuilderCallable.parseClass(DexArchiveBuilderCallable.java:86)
    at com.android.builder.dexing.DexArchiveBuilderCallable.call(DexArchiveBuilderCallable.java:70)
    at com.android.builder.dexing.DexArchiveBuilderCallable.call(DexArchiveBuilderCallable.java:43)
    ... 5 more
...while preparsing cst 0032 at offset 000000f1
...while parsing RangeDialogFragment.class

Execution failed for task ':installapp:transformClassesWithDexBuilderForDebug'.
    com.android.build.api.transform.TransformException:  java.lang.RuntimeException: java.lang.RuntimeException:  java.util.concurrent.ExecutionException:  java.util.concurrent.ExecutionException:  com.android.builder.utils.FileCache$FileCreatorException:
    com.android.builder.dexing.DexArchiveBuilder$DexBuilderException: Unable to convert input to dex archive.
</code>```

答:
Feature modules does not support multidex at the moment, so each feature module should use a single dex.

There is no generic solution to this issue, but I can give a few suggestions.

Try to move your UI code from your base feature module to another feature module. Android support libraries have the biggest impact on method count so moving support libraries from your base-feature to ui-feature module should help.

Play Services is the other major library that impact the method count. If you can, do not add the whole play services sdk but instead use subsets of it.

Use Apk Analyzer or DexCount to pinpoint libraries that use the highest amount of methods and try to move them to separate feature modules.

Proguard. Minification should be able to remove unused methods and help you fit the base module in a single dex. However, Proguard is quite problematic with instantapps at the moment. You will need to create extra proguard rules for each module.

Body:
I'm migrating my existing multi-dex app into an Instant app and converted my app into the recommended project structure.

There were a bunch of compilation issues related which were successfully resolved however while trying to run the install-able "application" module, I'm running into the following error as stated below in the stack trace.

I'm suspecting this is because my now baseFeature module (prior multi-dex app) is not compatible with the instant app architecture.

Any cues on what's the best way to handle this? If anyone can point to how would an existing multidex app port to the new instant app architecture, it would be great :)

Stack Trace:

Error converting bytecode to dex:
Cause: InvokeDynamic not supported
com.android.dx.cf.iface.ParseException: InvokeDynamic not supported
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
    at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
    at java.util.concurrent.ForkJoinTask.getThrowableException(ForkJoinTask.java:593)
    at java.util.concurrent.ForkJoinTask.reportException(ForkJoinTask.java:677)
    at java.util.concurrent.ForkJoinTask.join(ForkJoinTask.java:720)
    at com.android.ide.common.internal.WaitableExecutor.waitForTasksWithQuickFail(WaitableExecutor.java:146)
    at com.android.builder.dexing.DexArchiveBuilder.processOutputs(DexArchiveBuilder.java:110)
    at com.android.builder.dexing.DexArchiveBuilder.convert(DexArchiveBuilder.java:91)
    at com.android.build.gradle.internal.transforms.DexArchiveBuilderTransformCallable.lambda$cacheMissAction$0(DexArchiveBuilderTransformCallable.java:236)
    at com.android.builder.utils.FileCache.lambda$createFile$1(FileCache.java:260)
    at com.android.builder.utils.FileCache.lambda$null$5(FileCache.java:443)
    at com.android.builder.utils.SynchronizedFile.doActionWithSingleProcessLocking(SynchronizedFile.java:291)
    at com.android.builder.utils.SynchronizedFile.write(SynchronizedFile.java:234)
    at com.android.builder.utils.FileCache.lambda$queryCacheEntry$6(FileCache.java:415)
    at com.android.builder.utils.SynchronizedFile.doActionWithSingleProcessLocking(SynchronizedFile.java:291)
    at com.android.builder.utils.SynchronizedFile.read(SynchronizedFile.java:217)
    at com.android.builder.utils.FileCache.queryCacheEntry(FileCache.java:391)
    at com.android.builder.utils.FileCache.createFile(FileCache.java:273)
    at com.android.build.gradle.internal.transforms.DexArchiveBuilderTransformCallable.getFromCacheAndCreateIfMissing(DexArchiveBuilderTransformCallable.java:185)
    at com.android.build.gradle.internal.transforms.DexArchiveBuilderTransformCallable.call(DexArchiveBuilderTransformCallable.java:147)
    at com.android.build.gradle.internal.transforms.DexArchiveBuilderTransformCallable.call(DexArchiveBuilderTransformCallable.java:53)
    at java.util.concurrent.ForkJoinTask$AdaptedCallable.exec(ForkJoinTask.java:1424)
    at java.util.concurrent.ForkJoinTask.doExec(ForkJoinTask.java:289)
    at java.util.concurrent.ForkJoinPool$WorkQueue.runTask(ForkJoinPool.java:1056)
    at java.util.concurrent.ForkJoinPool.runWorker(ForkJoinPool.java:1692)
    at java.util.concurrent.ForkJoinWorkerThread.run(ForkJoinWorkerThread.java:157)
Caused by: com.android.dx.cf.iface.ParseException: InvokeDynamic not supported
    at com.android.dx.cf.cst.ConstantPoolParser.determineOffsets(ConstantPoolParser.java:226)
    at com.android.dx.cf.cst.ConstantPoolParser.parse(ConstantPoolParser.java:132)
    at com.android.dx.cf.cst.ConstantPoolParser.parseIfNecessary(ConstantPoolParser.java:124)
    at com.android.dx.cf.cst.ConstantPoolParser.getPool(ConstantPoolParser.java:115)
    at com.android.dx.cf.direct.DirectClassFile.parse0(DirectClassFile.java:491)
    at com.android.dx.cf.direct.DirectClassFile.parse(DirectClassFile.java:406)
    at com.android.dx.cf.direct.DirectClassFile.parseToInterfacesIfNecessary(DirectClassFile.java:388)
    at com.android.dx.cf.direct.DirectClassFile.getMagic(DirectClassFile.java:251)
    at com.android.builder.dexing.DexArchiveBuilderCallable.parseClass(DexArchiveBuilderCallable.java:86)
    at com.android.builder.dexing.DexArchiveBuilderCallable.call(DexArchiveBuilderCallable.java:70)
    at com.android.builder.dexing.DexArchiveBuilderCallable.call(DexArchiveBuilderCallable.java:43)
    ... 5 more
...while preparsing cst 0032 at offset 000000f1
...while parsing RangeDialogFragment.class

Execution failed for task ':installapp:transformClassesWithDexBuilderForDebug'.
    com.android.build.api.transform.TransformException:  java.lang.RuntimeException: java.lang.RuntimeException:  java.util.concurrent.ExecutionException:  java.util.concurrent.ExecutionException:  com.android.builder.utils.FileCache$FileCreatorException:
    com.android.builder.dexing.DexArchiveBuilder$DexBuilderException: Unable to convert input to dex archive.


来源: stackexchange

问:
How to make zip command line exit when trying to zip a file that doesn't exist
I'm trying to zip several file into one archive.
e.g in my working directory there's 2.txt but no 1.txt:

```<code>$ zip -r 1.zip 1.txt 2.txt
zip warning: name not matched: 1.txt
adding: 2.txt (stored 0%)
$ echo $?
0
</code>```

Is there any way for me to force zip to exit if one of the files doesn't exist, instead of just printing a warning like it currently does?

Thanks a lot in advance

答:
From the zip(1) man page:

```<code>   -MM
   --must-match
          All input patterns must match at least one file  and  all  input
          files  found  must  be readable.
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I'm trying to zip several file into one archive.
e.g in my working directory there's 2.txt but no 1.txt:

$ zip -r 1.zip 1.txt 2.txt
zip warning: name not matched: 1.txt
adding: 2.txt (stored 0%)
$ echo $?
0

Is there any way for me to force zip to exit if one of the files doesn't exist, instead of just printing a warning like it currently does?

Thanks a lot in advance

Body:
From the zip(1) man page:

   -MM
   --must-match
          All input patterns must match at least one file  and  all  input
          files  found  must  be readable.


问:
C# Parse XML Response to Array
I'm working with a third party system that returns the following xml response

```<code>{<origenxml type="data">
<data>
<item>
<id><![CDATA[PIN/4590/67]]></id>
<filename><![CDATA[CS.STAR]]></filename>
<group>
<id>MAIN</id>
<dictionary id="CS.ST.BOXNO">
<desc><![CDATA[boxes]]></desc>
<value ln="0"></value>
<raw-value ln="0"></raw-value>
<value ln="1"><![CDATA[121880 ]]></value>
<raw-value ln="1"><![CDATA[B-FILE394**BCBF*BC*121880*]]></raw-value>
<value ln="2"><![CDATA[121881 ]]></value>
<raw-value ln="2"><![CDATA[B-FILE394**BCBF*BC*121881*]]></raw-value>
<value ln="3"><![CDATA[121882 ]]></value>
<raw-value ln="3"><![CDATA[B-FILE394**BCBF*BC*121882*]]></raw-value>
<value ln="4"><![CDATA[940288 ]]></value>
<raw-value ln="4"><![CDATA[B-FILE80**BCBF*BC*940288*]]></raw-value>
<value ln="5"><![CDATA[170415 ]]></value>
<raw-value ln="5"><![CDATA[ALPHA**BC*BC*170415*]]></raw-value>
</raw-value>
</dictionary>
</group>
</item>
</data>
</origenxml>}
</code>```

Each line under Boxes, represents an object where the value is the Id and the raw-value is the data ( so line 5 - ID = 170415 and the Value = ALPHA**BC*BC*170415*) but i really can't figure out the best way to parse the xml. I have no control over the response xml, so i can't anything helpful like extra node names

答:
First thing, I want to make sure this is really the XML, because it's malformed. There's a floating end tag for the </raw-value> right before the </dictionary>. Assuming that is a mistake then the solution is easy with Linq over XML.

You'll need to add the following using statements:

```<code>using System.IO;
using System.Xml.Linq;
</code>```

I created this sample in a Console application, but you should be able to easily adapt it. The first step is to create an XDocument object from your XML. I'm pulling the text from a constant string value.

```<code>static XDocument CreateDocument()
{
    using (var reader = new StringReader(testData)) {
        return XDocument.Load(reader);
    }
}
</code>```

The rest is simply to create a query and enumerate it.

```<code>var doc = CreateDocument();

var results = from value in doc.Descendants("value")
                join rawValue in doc.Descendants("raw-value")
                on value.Attribute("ln").Value equals rawValue.Attribute("ln").Value
                select new { Value = value.Attribute("ln").Value, RawValue = rawValue.Value };

foreach (var result in results) {
    Console.WriteLine($"{result.Value} => {result.RawValue}");
}
</code>```

Title: C# Parse XML Response to Array

Body:
I'm working with a third party system that returns the following xml response

{<origenxml type="data">
<data>
<item>
<id><![CDATA[PIN/4590/67]]></id>
<filename><![CDATA[CS.STAR]]></filename>
<group>
<id>MAIN</id>
<dictionary id="CS.ST.BOXNO">
<desc><![CDATA[boxes]]></desc>
<value ln="0"></value>
<raw-value ln="0"></raw-value>
<value ln="1"><![CDATA[121880 ]]></value>
<raw-value ln="1"><![CDATA[B-FILE394**BCBF*BC*121880*]]></raw-value>
<value ln="2"><![CDATA[121881 ]]></value>
<raw-value ln="2"><![CDATA[B-FILE394**BCBF*BC*121881*]]></raw-value>
<value ln="3"><![CDATA[121882 ]]></value>
<raw-value ln="3"><![CDATA[B-FILE394**BCBF*BC*121882*]]></raw-value>
<value ln="4"><![CDATA[940288 ]]></value>
<raw-value ln="4"><![CDATA[B-FILE80**BCBF*BC*940288*]]></raw-value>
<value ln="5"><![CDATA[170415 ]]></value>
<raw-value ln="5"><![CDATA[ALPHA**BC*BC*170415*]]></raw-value>
</raw-value>
</dictionary>
</group>
</item>
</data>
</origenxml>}

Each line under Boxes, represents an object where the value is the Id and the raw-value is the data ( so line 5 - ID = 170415 and the Value = ALPHA**BC*BC*170415*) but i really can't figure out the best way to parse the xml. I have no control over the response xml, so i can't anything helpful like extra node names

Body:
First thing, I want to make sure this is really the XML, because it's malformed. There's a floating end tag for the </raw-value> right before the </dictionary>. Assuming that is a mistake then the solution is easy with Linq over XML.

You'll need to add the following using statements:

using System.IO;
using System.Xml.Linq;

I created this sample in a Console application, but you should be able to easily adapt it. The first step is to create an XDocument object from your XML. I'm pulling the text from a constant string value.

static XDocument CreateDocument()
{
    using (var reader = new StringReader(testData)) {
        return XDocument.Load(reader);
    }
}

The rest is simply to create a query and enumerate it.

var doc = CreateDocument();

var results = from value in doc.Descendants("value")
                join rawValue in doc.Descendants("raw-value")
                on value.Attribute("ln").Value equals rawValue.Attribute("ln").Value
                select new { Value = value.Attribute("ln").Value, RawValue = rawValue.Value };

foreach (var result in results) {
    Console.WriteLine($"{result.Value} => {result.RawValue}");
}


问:
Nuget connection attempt failed "Unable to load the service index for source"
While trying to connect to Nuget, I'm getting the error below, and then I am unable to connect:

[nuget.org] Unable to load the service index for source
https://api.nuget.org/v3/index.json.
An error occurred while sending the request.
Unable to connect to the remote server
A connection attempt failed because the connected party did not properly respond after a period of time, or established connection
failed because connected host has failed to respond 68.232.34.200:443

I am able to access https://api.nuget.org/v3/index.json on my browser.

答: The error can be caused by just temporary network issue, and disappear, if try again.</p>

ContentLicense: CC BY-SA 4.0


问:
Why "C:\Program Files" used as default. Is there any violations or degradation in performance if we change it?
Why does Microsoft recommend "C:\Program Files" for default installation destination? Are there any specific reason for that? And if I change the location is that going to effect the performance of the system and the application?</p>

答: Another thing to consider is that often in Enterprises, security is setup on the machine so that a typical user can only install to the C:\Program Files directory.</p>

OwnerDisplayName: Maharajan

LastEditorDisplayName: bdukes

ContentLicense: CC BY-SA 2.5

OwnerDisplayName: EBGreen


问:
How to make mysql LIKE search for exactly single words only
I have a query like this:

```<code>SELECT * FROM mytable where description like %STRING%
</code>```

The problem is: When I search for JAVAit returns me even the records with JAVAscript.

But, JAVA != JavaScript, right ? How can I work around it ?

答:
MySQL's LIKE operator isn't really suitable to detect an exact single word inside a string.  But REGEXP, which supports regular expressions, can handle this.  Consider the following query:

```<code>SELECT * FROM mytable WHERE description REGEXP '[[:<:]]Java[[:>:]]';
</code>```

This corresponds to matching the pattern \bJava\b, i.e. the word Java by itself.

Demo

Edit:

If you are trying to execute this query using Laravel, then whereRaw should come in handy:

```<code>$results = DB::table('mytable')
            ->whereRaw('description REGEXP ?', ['[[:<:]]Java[[:>:]]'])
            ->get();
</code>```

Body:
I have a query like this:

SELECT * FROM mytable where description like %STRING%

The problem is: When I search for JAVAit returns me even the records with JAVAscript.

But, JAVA != JavaScript, right ? How can I work around it ?

Body:
MySQL's LIKE operator isn't really suitable to detect an exact single word inside a string.  But REGEXP, which supports regular expressions, can handle this.  Consider the following query:

SELECT * FROM mytable WHERE description REGEXP '[[:<:]]Java[[:>:]]';

This corresponds to matching the pattern \bJava\b, i.e. the word Java by itself.

Demo

Edit:

If you are trying to execute this query using Laravel, then whereRaw should come in handy:

$results = DB::table('mytable')
            ->whereRaw('description REGEXP ?', ['[[:<:]]Java[[:>:]]'])
            ->get();


问:
Python split on brackets with regular expressions
If I have a string "4[ab]" and I want to split this string such that I get an array ["4", "ab"], how would I use a regular expression in python for this?

I've used the following regular expressions with no luck:

```<code>"\[\["
"\]\["
"[\[\]]"
"[\]\[]"
</code>```

From what I understand with python syntax you have to escape characters like square brackets because it will compute the values inside the brackets as the regular expression.

What else is required?

Edit, sorry for the delay:

Here's the code though I doubt it's anything special:

```<code>import re
re.split("[\[\]]","4[ab]")
</code>```

This returns the correct output I'm looking for but does not work for

```<code>"4[ab]".split("[\[\]]")
</code>```

答:
```<code>In [16]: import re

In [17]: a = "4[ab]"

In [18]: re.findall("(\d)\[(\w+)]", a)[0]
Out[18]: ('4', 'ab')
</code>```

You can refer to the documentation which reads that:

To match a literal ']' inside a set, precede it with a backslash, or
  place it at the beginning of the set.

Body:
If I have a string "4[ab]" and I want to split this string such that I get an array ["4", "ab"], how would I use a regular expression in python for this?

I've used the following regular expressions with no luck:

"\[\["
"\]\["
"[\[\]]"
"[\]\[]"

From what I understand with python syntax you have to escape characters like square brackets because it will compute the values inside the brackets as the regular expression.

What else is required?

Edit, sorry for the delay:

Here's the code though I doubt it's anything special:

import re
re.split("[\[\]]","4[ab]")

This returns the correct output I'm looking for but does not work for

"4[ab]".split("[\[\]]")

Body:
In [16]: import re

In [17]: a = "4[ab]"

In [18]: re.findall("(\d)\[(\w+)]", a)[0]
Out[18]: ('4', 'ab')

You can refer to the documentation which reads that:

To match a literal ']' inside a set, precede it with a backslash, or
  place it at the beginning of the set.


问:
Converting Binary to Decimal in python (without built in binary function)
Alrighty, first post here, so please forgive and ignore if the question is not workable;

Background:
I'm in computer science 160.  I haven't taken any computer related classes since high school, so joining this class was a big shift for me. It all seemed very advanced.  We have been working in Python and each week we are prompted to write a program.

I have been working with this problem for over a week and am having a hard time even starting.

The prompt is to read an integer containing only 1's and 0's,
process the binary number digit by digit and report the decimal equivalent.  Now, I have gotten some tips from a classmate and it sent me at least in a direction.

Set up a couple of counters;
using the % operator to check the remainder of the number divided by 2, and slicing off the last number (to the right) to move on to and process the next digit.

I am having an incredibly hard time wrapping my head around what formula to use on the binary digits themselves which will convert the number to decimal.

```<code>setbitval = 0
counter = 0

user = int(input("enter a binary value. "))

if user % 2 == 1:
        user = (user/10) - .1
        setbitval += 1
</code>```

This is all I've got so far.. My thinking is getting in the way.  I've searched and searched, even through these forums.

Any information or thoughts are extremely appreciated,

T

Edit: okay guys, everyone's help has been extremely useful but I'm having a problem checking if the user input is not a binary number.

```<code>for i in reversed(bits):
decimal += 2**counter * int(i)

counter += 1
</code>```

This is the formula someone here gave me and I've been trying different iterations of "for i in bits:  if i in bits: != 0 or 1" and also "if i in bits: >= 1 or <=0".

Any thoughts?

答:
you can use this code:</p>

```<code>binary= raw_input("Binary: ")
d= int(binary, 2)
print d
</code>```

Body:
Alrighty, first post here, so please forgive and ignore if the question is not workable;

Background:
I'm in computer science 160.  I haven't taken any computer related classes since high school, so joining this class was a big shift for me. It all seemed very advanced.  We have been working in Python and each week we are prompted to write a program.

I have been working with this problem for over a week and am having a hard time even starting.

The prompt is to read an integer containing only 1's and 0's,
process the binary number digit by digit and report the decimal equivalent.  Now, I have gotten some tips from a classmate and it sent me at least in a direction.

Set up a couple of counters;
using the % operator to check the remainder of the number divided by 2, and slicing off the last number (to the right) to move on to and process the next digit.

I am having an incredibly hard time wrapping my head around what formula to use on the binary digits themselves which will convert the number to decimal.

setbitval = 0
counter = 0

user = int(input("enter a binary value. "))

if user % 2 == 1:
        user = (user/10) - .1
        setbitval += 1

This is all I've got so far.. My thinking is getting in the way.  I've searched and searched, even through these forums.

Any information or thoughts are extremely appreciated,

T

Edit: okay guys, everyone's help has been extremely useful but I'm having a problem checking if the user input is not a binary number.

for i in reversed(bits):
decimal += 2**counter * int(i)

counter += 1

This is the formula someone here gave me and I've been trying different iterations of "for i in bits:  if i in bits: != 0 or 1" and also "if i in bits: >= 1 or <=0".

Any thoughts?

Body:
you can use this code:

binary= raw_input("Binary: ")
d= int(binary, 2)
print d


问:
Python end function after another function returns result
I may be approaching this all wrong but still this is where I'm at.  I have very large log files I'm trying to search, up to 30gb in some cases.  I'm writing a script to pull info and have been playing with multi process to speed it up a bit.  right now I'm testing running two functions at the same time to search from the top and bottom to get results, which seems to work.  I'm wondering if it's possible to stop one function one a result from the other.  Such as if the top function finds a result they both stop.  This way I can build it out as needed.</p>

```<code>from file_read_backwards import FileReadBackwards
from multiprocessing import Process
import sys

z = "log.log"

#!/usr/bin/env python
rocket = 0

def top():
    target = "test"
    with open(z) as src:
        found= None
        for line in src:
            if len(line) == 0: break #happens at end of file, then stop loop
            if target in line:
                found= line
                break
    print(found)

def bottom():
    target = "text"
    with FileReadBackwards(z) as src:
        found= None
        for line in src:
            if len(line) == 0: break #happens at end of file, then stop loop
            if target in line:
                found= line
                break
    print(found)

if __name__=='__main__':
     p1 = Process(target = top)
     p1.start()
     p2 = Process(target = bottom)
     p2.start()
</code>```

答:
Here's a proof-of-concept of the approach I mentioned in the comments:

```<code>import os
import random
import sys
from multiprocessing import Process, Value

def search(proc_no, file_name, seek_to, max_size, find, flag):
    stop_at = seek_to + max_size

    with open(file_name) as f:
        if seek_to:
            f.seek(seek_to - 1)
            prev_char = f.read(1)
            if prev_char != '\n':
                # Landed in the middle of a line. Skip back one (or
                # maybe more) lines so this line isn't excluded. Start
                # by seeking back 256 bytes, then 512 if necessary, etc.
                exponent = 8
                pos = seek_to
                while pos >= seek_to:
                    pos = f.seek(max(0, pos - (2 ** exponent)))
                    f.readline()
                    pos = f.tell()
                    exponent += 1

        while True:
            if flag.value:
                break
            line = f.readline()
            if not line:
                break  # EOF
            data = line.strip()
            if data == find:
                flag.value = proc_no
                print(data)
                break
            if f.tell() > stop_at:
                break

if __name__ == '__main__':
    # list.txt contains lines with the numbers 1 to 1000001
    file_name = 'list.txt'
    info = os.stat(file_name)
    file_size = info.st_size

    if len(sys.argv) == 1:
        # Pick a random value from list.txt
        num_lines = 1000001
        choices = list(range(1, num_lines + 1))
        choices.append('XXX')
        find = str(random.choice(choices))
    else:
        find = sys.argv[1]

    num_procs = 4
    chunk_size, remainder = divmod(file_size, num_procs)
    max_size = chunk_size + remainder
    flag = Value('i', 0)
    procs = []

    print(f'Using {num_procs} processes to look for {find} in {file_name}')

    for i in range(num_procs):
        seek_to = i * chunk_size
        proc = Process(target=search, args=(i + 1, file_name, seek_to, max_size, find, flag))
        procs.append(proc)

    for proc in procs:
        proc.start()

    for proc in procs:
        proc.join()

    if flag.value:
        print(find, 'found by proc', flag.value)
    else:
        print(find, 'not found')
</code>```

After reading various posts[1] about reading files with multiprocessing and multithreading, it seems that neither is a great approach due to potential disk thrashing and serialized reads. So here's a different, simpler approach that is way faster (at least for the file with a million lines I was trying it out on):

```<code>import mmap
import sys

def search_file(file_name, text, encoding='utf-8'):
    text = text.encode(encoding)
    with open(file_name) as f:
        with mmap.mmap(f.fileno(), 0, flags=mmap.ACCESS_READ, prot=mmap.PROT_READ) as m:
            index = m.find(text)
            if index > -1:
                # Found a match; now find beginning of line that
                # contains match so we can grab the whole line.
                while index > 0:
                    index -= 1
                    if m[index] == 10:
                        index += 1
                        break
                else:
                    index = 0
                m.seek(index)
                line = m.readline()
                return line.decode(encoding)

if __name__ == '__main__':
    file_name, search_string = sys.argv[1:]
    line = search_file(file_name, search_string)
    sys.stdout.write(line if line is not None else f'Not found in {file_name}: {search_string}\n')
</code>```

I'm curious how this would perform with a 30GB log file.

[1] Including this one

Body:
I may be approaching this all wrong but still this is where I'm at.  I have very large log files I'm trying to search, up to 30gb in some cases.  I'm writing a script to pull info and have been playing with multi process to speed it up a bit.  right now I'm testing running two functions at the same time to search from the top and bottom to get results, which seems to work.  I'm wondering if it's possible to stop one function one a result from the other.  Such as if the top function finds a result they both stop.  This way I can build it out as needed.

from file_read_backwards import FileReadBackwards
from multiprocessing import Process
import sys

z = "log.log"

#!/usr/bin/env python
rocket = 0

def top():
    target = "test"
    with open(z) as src:
        found= None
        for line in src:
            if len(line) == 0: break #happens at end of file, then stop loop
            if target in line:
                found= line
                break
    print(found)

def bottom():
    target = "text"
    with FileReadBackwards(z) as src:
        found= None
        for line in src:
            if len(line) == 0: break #happens at end of file, then stop loop
            if target in line:
                found= line
                break
    print(found)

if __name__=='__main__':
     p1 = Process(target = top)
     p1.start()
     p2 = Process(target = bottom)
     p2.start()

Body:
Here's a proof-of-concept of the approach I mentioned in the comments:

import os
import random
import sys
from multiprocessing import Process, Value

def search(proc_no, file_name, seek_to, max_size, find, flag):
    stop_at = seek_to + max_size

    with open(file_name) as f:
        if seek_to:
            f.seek(seek_to - 1)
            prev_char = f.read(1)
            if prev_char != '\n':
                # Landed in the middle of a line. Skip back one (or
                # maybe more) lines so this line isn't excluded. Start
                # by seeking back 256 bytes, then 512 if necessary, etc.
                exponent = 8
                pos = seek_to
                while pos >= seek_to:
                    pos = f.seek(max(0, pos - (2 ** exponent)))
                    f.readline()
                    pos = f.tell()
                    exponent += 1

        while True:
            if flag.value:
                break
            line = f.readline()
            if not line:
                break  # EOF
            data = line.strip()
            if data == find:
                flag.value = proc_no
                print(data)
                break
            if f.tell() > stop_at:
                break

if __name__ == '__main__':
    # list.txt contains lines with the numbers 1 to 1000001
    file_name = 'list.txt'
    info = os.stat(file_name)
    file_size = info.st_size

    if len(sys.argv) == 1:
        # Pick a random value from list.txt
        num_lines = 1000001
        choices = list(range(1, num_lines + 1))
        choices.append('XXX')
        find = str(random.choice(choices))
    else:
        find = sys.argv[1]

    num_procs = 4
    chunk_size, remainder = divmod(file_size, num_procs)
    max_size = chunk_size + remainder
    flag = Value('i', 0)
    procs = []

    print(f'Using {num_procs} processes to look for {find} in {file_name}')

    for i in range(num_procs):
        seek_to = i * chunk_size
        proc = Process(target=search, args=(i + 1, file_name, seek_to, max_size, find, flag))
        procs.append(proc)

    for proc in procs:
        proc.start()

    for proc in procs:
        proc.join()

    if flag.value:
        print(find, 'found by proc', flag.value)
    else:
        print(find, 'not found')

After reading various posts[1] about reading files with multiprocessing and multithreading, it seems that neither is a great approach due to potential disk thrashing and serialized reads. So here's a different, simpler approach that is way faster (at least for the file with a million lines I was trying it out on):

import mmap
import sys

def search_file(file_name, text, encoding='utf-8'):
    text = text.encode(encoding)
    with open(file_name) as f:
        with mmap.mmap(f.fileno(), 0, flags=mmap.ACCESS_READ, prot=mmap.PROT_READ) as m:
            index = m.find(text)
            if index > -1:
                # Found a match; now find beginning of line that
                # contains match so we can grab the whole line.
                while index > 0:
                    index -= 1
                    if m[index] == 10:
                        index += 1
                        break
                else:
                    index = 0
                m.seek(index)
                line = m.readline()
                return line.decode(encoding)

if __name__ == '__main__':
    file_name, search_string = sys.argv[1:]
    line = search_file(file_name, search_string)
    sys.stdout.write(line if line is not None else f'Not found in {file_name}: {search_string}\n')

I'm curious how this would perform with a 30GB log file.

[1] Including this one


问:
How to relate a function to a specific netCDF file based on timestamp
I have 73 netCDF files each representing 5 day intervals of a calendar year and have several variables. Each file has 120 layers representing hourly intervals.

I have read them all into R and named them appropriately using the ncdf4 package like so:

```<code>filenames <- list.files(path=getwd())

for(i in filenames) {
  ncin <- nc_open(i)
  ds<-paste(i)
  assign(ds, ncin)
  print(i)
  }
</code>```

I also have a data frame of locations in the same projection as the netCDF files (lat-lon) however these locations irregularly span the entire calendar year as well. A sample of the data looks like this:

```<code>>head(df)
> Lon      Lat            datetime
2 -3.179046 58.65417 2016-09-30 17:25:38
3 -3.180403 58.65483 2016-09-30 17:29:43
4 -3.187734 58.66102 2016-09-30 21:22:51
5 -3.190197 58.66409 2016-09-30 22:02:47
6 -3.182058 58.67433 2016-10-01 06:16:08
7 -3.181318 58.67475 2016-10-01 06:20:31
</code>```

What I am trying to do is to match the data-frame to the correct netCDF file and layer based on it's datetime stamp i.e. if it's between day 1 and 5 of the year it would be netCDF file 1 etc.. then I want to interpolate the variable data from the netCDF file onto the location data with associated datetime stamp of the data frame. So at the given time and place provided by the data-frame, what is the value of variable V at the same date and time in the netCDF file. I can do the first part using loop functions but it's grossly inefficient and time consuming to code:

```<code>function(dataframe){
d <- dataframe[i,]
if(between(d$datetime, 2017-01-01 00:00:00, 2017-01-05 23:59:59){ncfile <- file1} else if (between(d$datetime, 2017-01-06 00:00:00, 2017-01-010 23:59:59))
     {ncfile <- file2}}
</code>```

And so on... Having never worked with netCDF files before I'm unsure as to the best method. Any suggestions?

################# UPDATE

I read the netCDF files in using

```<code>filenames <- list.files(path=getwd())
x <- lapply(filenames, nc_open)
</code>```

extract dates from the file which are sequentially named:

```<code>PFOW_Climatology2_0001_1993-01-01.nc
PFOW_Climatology2_0002_1993-01-06.nc
</code>```

up to

```<code>PFOW_Climatology2_0073_1993-12-27.nc
</code>```

by using

```<code>fd <- as.Date(substr(filenames, 24, 36))
</code>```

I then create a reference column for the dataframe by find9ing the interval within which each data point corresponds in fd like so:

```<code>i <- findInterval(dd, fd)
df$file <- i
</code>```

答:
It is very difficult to give a good answer without you providing more information, and ideally some example data.

Your "appropriate naming" is highly inappropriate. You really should not need  assign in daily life. Just make a list.

```<code>library(ncdf4)
x <- lapply(filenames, nc_open)
</code>```

But since you need to extract values by location, it is perhaps better to make a list of RasterBrick objects:

```<code>library(raster)
x <- lapply(filenames, brick)
</code>```

But I would not do that either.

I would first match the file names with df$datetime. As you do not tell us what the file names look like, I cannot tell you how to do that. But you won't need a loop. Extract the dates from the filenames, create an appropriate date (and time?) object and do something like

```<code>fd <- as.Date(subtr(filenames, 4, 12))
dd <- as.Date(df$datetime)
i <- which(dd > fd[-length(fd)] & dd < fd[-1]) + 1

df$file <- filenames[i]
df$id <- 1:nrow(df)
</code>```

Now you can loop over the filenames and extract the values:

```<code>ff <- unique(df$file)
vv <- sapply(ff, function(f) {
         v <- extract(brick(f), df[df$file == f , c('lon', 'lat')])
         data.frame(file=f, xy, v)
      })
</code>```

vv should be a data.frame with values for each case, for its corresponding 5-day interval. From there select (or interpolate) the time you want from the 120 values.

I assume that you want to do temporal interpolation. For (also) spatial interpolation use method = 'bilinear' in extract

Again, this may not work, as I do not have example data. But something along these lines will work.

Body:
I have 73 netCDF files each representing 5 day intervals of a calendar year and have several variables. Each file has 120 layers representing hourly intervals.

I have read them all into R and named them appropriately using the ncdf4 package like so:

filenames <- list.files(path=getwd())

for(i in filenames) {
  ncin <- nc_open(i)
  ds<-paste(i)
  assign(ds, ncin)
  print(i)
  }

I also have a data frame of locations in the same projection as the netCDF files (lat-lon) however these locations irregularly span the entire calendar year as well. A sample of the data looks like this:

>head(df)
> Lon      Lat            datetime
2 -3.179046 58.65417 2016-09-30 17:25:38
3 -3.180403 58.65483 2016-09-30 17:29:43
4 -3.187734 58.66102 2016-09-30 21:22:51
5 -3.190197 58.66409 2016-09-30 22:02:47
6 -3.182058 58.67433 2016-10-01 06:16:08
7 -3.181318 58.67475 2016-10-01 06:20:31

What I am trying to do is to match the data-frame to the correct netCDF file and layer based on it's datetime stamp i.e. if it's between day 1 and 5 of the year it would be netCDF file 1 etc.. then I want to interpolate the variable data from the netCDF file onto the location data with associated datetime stamp of the data frame. So at the given time and place provided by the data-frame, what is the value of variable V at the same date and time in the netCDF file. I can do the first part using loop functions but it's grossly inefficient and time consuming to code:

function(dataframe){
d <- dataframe[i,]
if(between(d$datetime, 2017-01-01 00:00:00, 2017-01-05 23:59:59){ncfile <- file1} else if (between(d$datetime, 2017-01-06 00:00:00, 2017-01-010 23:59:59))
     {ncfile <- file2}}

And so on... Having never worked with netCDF files before I'm unsure as to the best method. Any suggestions?

################# UPDATE

I read the netCDF files in using

filenames <- list.files(path=getwd())
x <- lapply(filenames, nc_open)

extract dates from the file which are sequentially named:

PFOW_Climatology2_0001_1993-01-01.nc
PFOW_Climatology2_0002_1993-01-06.nc

up to

PFOW_Climatology2_0073_1993-12-27.nc

by using

fd <- as.Date(substr(filenames, 24, 36))

I then create a reference column for the dataframe by find9ing the interval within which each data point corresponds in fd like so:

i <- findInterval(dd, fd)
df$file <- i

Body:
It is very difficult to give a good answer without you providing more information, and ideally some example data.

Your "appropriate naming" is highly inappropriate. You really should not need  assign in daily life. Just make a list.

library(ncdf4)
x <- lapply(filenames, nc_open)

But since you need to extract values by location, it is perhaps better to make a list of RasterBrick objects:

library(raster)
x <- lapply(filenames, brick)

But I would not do that either.

I would first match the file names with df$datetime. As you do not tell us what the file names look like, I cannot tell you how to do that. But you won't need a loop. Extract the dates from the filenames, create an appropriate date (and time?) object and do something like

fd <- as.Date(subtr(filenames, 4, 12))
dd <- as.Date(df$datetime)
i <- which(dd > fd[-length(fd)] & dd < fd[-1]) + 1

df$file <- filenames[i]
df$id <- 1:nrow(df)

Now you can loop over the filenames and extract the values:

ff <- unique(df$file)
vv <- sapply(ff, function(f) {
         v <- extract(brick(f), df[df$file == f , c('lon', 'lat')])
         data.frame(file=f, xy, v)
      })

vv should be a data.frame with values for each case, for its corresponding 5-day interval. From there select (or interpolate) the time you want from the 120 values.

I assume that you want to do temporal interpolation. For (also) spatial interpolation use method = 'bilinear' in extract

Again, this may not work, as I do not have example data. But something along these lines will work.


问:
Adding a new node to my linked list stack updates all my old nodes to the new node
When I insert a string into my stack, it adds it but also changes all the previous elements as well.

```<code>void push(linkedList *ll,char *item) {
node *newNode = malloc(sizeof(node));
if (ll->size == 0) {
    newNode->value = item;
    newNode->next = NULL;
    ll->head = newNode;
    ll->tail = newNode;
    ll->size++;
}
else {
    newNode->value = item;
    newNode->next = ll->head;
    ll->head = newNode;
    ll->size++;
}
}

int main() {
linkedList* stack = init();
int scan = 1;
char * p = malloc(sizeof(char) * 5);
while (scan = 1) {
    scanf("%1s", p);
    if (*p >= '0' && *p <= '9') {
        push(stack, p);
        print(stack);
    }
}

WINPAUSE;
}
</code>```

The output looks something like this:

insert 5

5

insert 7

7 --> 7

insert 8

8 --> 8 --> 8

答:
You are adding the same pointer every time.  You allocated that memory once, and continually replace its contents.  Since each node in the list holds the same pointer value, traversing the list will give you back the most recently input data, including if the data was not even in the valid range.

The most appropriate solution (of many options) is probably to do one of these things:

copy the data by allocating new memory for it when you push an item

store the data as a char value instead of a pointer, since you're only holding one character at a time (if this is appropriate for your task)

Body:
When I insert a string into my stack, it adds it but also changes all the previous elements as well.

void push(linkedList *ll,char *item) {
node *newNode = malloc(sizeof(node));
if (ll->size == 0) {
    newNode->value = item;
    newNode->next = NULL;
    ll->head = newNode;
    ll->tail = newNode;
    ll->size++;
}
else {
    newNode->value = item;
    newNode->next = ll->head;
    ll->head = newNode;
    ll->size++;
}
}

int main() {
linkedList* stack = init();
int scan = 1;
char * p = malloc(sizeof(char) * 5);
while (scan = 1) {
    scanf("%1s", p);
    if (*p >= '0' && *p <= '9') {
        push(stack, p);
        print(stack);
    }
}

WINPAUSE;
}

The output looks something like this:

insert 5

5

insert 7

7 --> 7

insert 8

8 --> 8 --> 8


问:
How to check "hasRole" in Java Code with Spring Security?
How to check user authority or permission in Java Code ? For example - I want to show or hide button for user depending on role. There are annotations like:

```<code>@PreAuthorize("hasRole('ROLE_USER')")
</code>```

How to make it in Java code? Something like :

```<code>if(somethingHere.hasRole("ROLE_MANAGER")) {
   layout.addComponent(new Button("Edit users"));
}
</code>```

答:
Most answers are missing some points:

Role and authority are not the same thing in Spring. See here for more details.

Role names are equal to rolePrefix + authority.

The default role prefix is ROLE_, however, it is configurable. See here.

Therefore, a proper role check needs to respect the role prefix if it is configured.

Unfortunately, the role prefix customization in Spring is a bit hacky, in many places the default prefix, ROLE_ is hardcoded, but in addition to that, a bean of type GrantedAuthorityDefaults is checked in the Spring context, and if it exists, the custom role prefix it has is respected.

Bringing all this information together, a better role checker implementation would be something like:

```<code>@Component
public class RoleChecker {

    @Autowired(required = false)
    private GrantedAuthorityDefaults grantedAuthorityDefaults;

    public boolean hasRole(String role) {
        String rolePrefix = grantedAuthorityDefaults != null ? grantedAuthorityDefaults.getRolePrefix() : "ROLE_";
        return Optional.ofNullable(SecurityContextHolder.getContext().getAuthentication())
                .map(Authentication::getAuthorities)
                .map(Collection::stream)
                .orElse(Stream.empty())
                .map(GrantedAuthority::getAuthority)
                .map(authority -> rolePrefix + authority)
                .anyMatch(role::equals);
    }
}
</code>```

Body:
How to check user authority or permission in Java Code ? For example - I want to show or hide button for user depending on role. There are annotations like:

@PreAuthorize("hasRole('ROLE_USER')")

How to make it in Java code? Something like :

if(somethingHere.hasRole("ROLE_MANAGER")) {
   layout.addComponent(new Button("Edit users"));
}

Body:
Most answers are missing some points:

Role and authority are not the same thing in Spring. See here for more details.

Role names are equal to rolePrefix + authority.

The default role prefix is ROLE_, however, it is configurable. See here.

Therefore, a proper role check needs to respect the role prefix if it is configured.

Unfortunately, the role prefix customization in Spring is a bit hacky, in many places the default prefix, ROLE_ is hardcoded, but in addition to that, a bean of type GrantedAuthorityDefaults is checked in the Spring context, and if it exists, the custom role prefix it has is respected.

Bringing all this information together, a better role checker implementation would be something like:

@Component
public class RoleChecker {

    @Autowired(required = false)
    private GrantedAuthorityDefaults grantedAuthorityDefaults;

    public boolean hasRole(String role) {
        String rolePrefix = grantedAuthorityDefaults != null ? grantedAuthorityDefaults.getRolePrefix() : "ROLE_";
        return Optional.ofNullable(SecurityContextHolder.getContext().getAuthentication())
                .map(Authentication::getAuthorities)
                .map(Collection::stream)
                .orElse(Stream.empty())
                .map(GrantedAuthority::getAuthority)
                .map(authority -> rolePrefix + authority)
                .anyMatch(role::equals);
    }
}


问:
MySQL: Need assistance for schema- how to deal with lists?
I have a form for inputting information about a football player, with a field to enter in all of the teams that the player has been on.  The idea is that records of these players will be used to generate an index of teams, and individual team pages.  The team pages would then display records of all players who have once been on the team at some point.

That's how it works in abstract.  I'm not exactly sure how to handle the field; I'm thinking of having the teams be comma separated when the user inputs them.  However, I'm more concerned about how to handle the backend, in the database itself.

If each player has multiple teams associated with him, how should I store the teams attribute in the db table for players?  At the moment, since the form is about a single player, the main table I'm working with is the players table.  Each row of this table is about a single player and his stats, including an attribute that is a list of teams he has been on.  I think I may need an additional table for teams.  Each row on this secondary table wouldn't consist of much, just an id, and then a list of players.  But then, how would I then handle that list of players?

Any suggestions as to how to deal with this situation?  Is there a better solution?

答: You are describing a many-to-many relationship. You need a "player" table, a "team" table, and a "player_team" assoc table. The assoc table would have both a player_id and a team_id.  You can then load players associated with a given team by doing a join on the assoc table.</p>


问:
assign value to struct variables in C
I have a problem assigning values to variable in struct. My code is shown below.

```<code>typedef struct _neuron
{
    double value[100];
    int id;
}NEURON;

int main() {
  NEURON node;
  int i;
  for(i = 0; i < 100; i++){
    node.value[i] = 10;
    printf("the value is %d\n",node.value[i]);
  }
}
</code>```

The values I assigned to struct variables are 10, but I am getting 0 instead of 10. Does anyone know where the problem is?

答:
You're using the wrong format specifier to printf.

The %d format specifier expects an int argument, but you're passing in a double.  Using the wrong format specifier invokes undefined behavior.

For a double, use the %f format specifier.

```<code>printf("the value is %f\n",node.value[i]);
</code>```

Title: assign value to struct variables in C

Body:
I have a problem assigning values to variable in struct. My code is shown below.

typedef struct _neuron
{
    double value[100];
    int id;
}NEURON;

int main() {
  NEURON node;
  int i;
  for(i = 0; i < 100; i++){
    node.value[i] = 10;
    printf("the value is %d\n",node.value[i]);
  }
}

The values I assigned to struct variables are 10, but I am getting 0 instead of 10. Does anyone know where the problem is?

Body:
You're using the wrong format specifier to printf.

The %d format specifier expects an int argument, but you're passing in a double.  Using the wrong format specifier invokes undefined behavior.

For a double, use the %f format specifier.

printf("the value is %f\n",node.value[i]);


问:
How do I convert a large JSON file to a Pandas Dataframe or a regular CSV file?
I've tried json_normalize, and this seems to work; however, it does not print my desired output.

```<code>import requests
import json
from pandas.io.json import json_normalize
import pandas as pd

url = "https://www.qnt.io/api/results?pID=gifgif&mID=54a309ae1c61be23aba0da62&key=54a309ac1c61be23aba0da3f"

aResponse = requests.get(url)

y = json.loads(aResponse.content)
json_test = json.dumps(y, indent = 4, sort_keys=True)
print(json_test)
csv = json_normalize(y['results'])
print(csv)
</code>```

Displaying the output of this code is difficult and extremely confusing; therefore, I think its in both of our best interests that I leave it out. If that is a useful piece of information, I can add it.

The json.dumps portion simply orgranizes my json file so that it is easily viewable. Unfortunately, I can't post the entire json file because Stack isn't a huge fan of my formatting. Here is a small snippet:

```<code>{
"query_parameters": {
    "limit": 10,
    "mID": "54a309ae1c61be23aba0da62",
    "skip": 0,
    "sort": 1
},
"results": [
    {
        "cID": "5314ab42d34b6c5b402aead4",
        "content": "BE9kUwvLfsAmI",
        "content_data": {
            "added_with_admin": false,
            "dateAdded": 1393863490.072894,
            "embedLink": "http://media3.giphy.com/media/BE9kUwvLfsAmI/giphy.gif",
            "still_image": "http://media.giphy.com/media/BE9kUwvLfsAmI/200_s.gif",
            "tags": [
                "adam levine",
                "embarassed",
                "the voice",
                "confession"
            ]
        },
        "content_type": "gif",
        "index": 269,
        "parameters": {
            "mu": 35.92818823777915,
            "sigma": 1.88084276812386
        },
        "rank": 0
    },
</code>```

There is about 10 more of these (ranging all the way up to 6119; however, I'm trying to get just part of this working). I want my output to be ordered as such: rank, tags, embedLink, mu, sigma, index. Here is an example of my desired output:

```<code>0, adam levine, embarassed, the voice, confession, http://media3.giphy.com/media/BE9kUwvLfsAmI/giphy.gif, 35.92818823777915, 1.88084276812386, 269
</code>```

I would like to have it as a csv file; however, I think creating a dataframe using Pandas could also be quite useful. I think my problem occurs because I have such a large, embedded json file, and it's hard for the computer to organize this large data-set. Any advice would be appreciated!

答:
First, you can use requests.json() instead of requests.text to get the response content as JSON.

```<code>import requests
import pandas as pd
from pprint import pprint

url = "https://www.qnt.io/api/results?pID=gifgif&mID=54a309ae1c61be23aba0da62&key=54a309ac1c61be23aba0da3f"

response = requests.get(url)
results = response.json()["results"]

# pprint(results)

[{'cID': '5314ab42d34b6c5b402aead4',
  'content': 'BE9kUwvLfsAmI',
  'content_data': {'added_with_admin': False,
                   'dateAdded': 1393863490.072894,
                   'embedLink': 'http://media3.giphy.com/media/BE9kUwvLfsAmI/giphy.gif',
                   'still_image': 'http://media.giphy.com/media/BE9kUwvLfsAmI/200_s.gif',
                   'tags': ['adam levine',
                            'embarassed',
                            'the voice',
                            'confession']},
  'content_type': 'gif',
  'index': 269,
  'parameters': {'mu': 35.92818823777915, 'sigma': 1.88084276812386},
  'rank': 0},
 {'cID': '5314ab4dd34b6c5b402aeb97',
  ...
</code>```

Then you can load the dict with pd.DataFrame.from_dict:

```<code>df = pd.DataFrame.from_dict(results)

# print(df.head(2))

                        cID        content  \
0  5314ab42d34b6c5b402aead4  BE9kUwvLfsAmI
1  5314ab4dd34b6c5b402aeb97  NZhO1SEuFmhj2

                                        content_data content_type  index  \
0  {'embedLink': 'http://media3.giphy.com/media/B...          gif    269
1  {'embedLink': 'http://media1.giphy.com/media/N...          gif    464

                                          parameters  rank
0  {'mu': 35.92818823777915, 'sigma': 1.880842768...     0
1  {'mu': 35.70238333972232, 'sigma': 1.568292935...     1
</code>```

And then use .apply(pd.Series) to further expand the columns in dict:

```<code>df = pd.concat([df.drop(["content_data"], axis=1), df["content_data"].apply(pd.Series)], axis=1)
df = pd.concat([df.drop(["parameters"], axis=1), df["parameters"].apply(pd.Series)], axis=1)

# print(df.head(2))
                        cID        content content_type  index  rank  \
0  5314ab42d34b6c5b402aead4  BE9kUwvLfsAmI          gif    269     0
1  5314ab4dd34b6c5b402aeb97  NZhO1SEuFmhj2          gif    464     1

   added_with_admin     dateAdded  \
0             False  1.393863e+09
1             False  1.393864e+09

                                           embedLink  \
0  http://media3.giphy.com/media/BE9kUwvLfsAmI/gi...
1  http://media1.giphy.com/media/NZhO1SEuFmhj2/gi...

                                         still_image  \
0  http://media.giphy.com/media/BE9kUwvLfsAmI/200...
1  http://media.giphy.com/media/NZhO1SEuFmhj2/200...

                                                tags         mu     sigma
0   [adam levine, embarassed, the voice, confession]  35.928188  1.880843
1  [ryan gosling, facepalm, embarrassed, confession]  35.702383  1.568293
</code>```

And convert the tags from list to string:

```<code>df["tags"] = df["tags"].apply(lambda x: ", ".join(x))

# print(df.head(2)["tags"])

0     adam levine, embarassed, the voice, confession
1    ryan gosling, facepalm, embarrassed, confession
</code>```

And get the columns you want finally:

```<code>df = df[["rank", "tags", "embedLink", "mu", "sigma", "index"]]

# print(df.head(2))

   rank                                             tags  \
0     0   adam levine, embarassed, the voice, confession
1     1  ryan gosling, facepalm, embarrassed, confession

                                           embedLink         mu     sigma  \
0  http://media3.giphy.com/media/BE9kUwvLfsAmI/gi...  35.928188  1.880843
1  http://media1.giphy.com/media/NZhO1SEuFmhj2/gi...  35.702383  1.568293

   index
0    269
1    464
</code>```

Body:
I've tried json_normalize, and this seems to work; however, it does not print my desired output.

import requests
import json
from pandas.io.json import json_normalize
import pandas as pd

url = "https://www.qnt.io/api/results?pID=gifgif&mID=54a309ae1c61be23aba0da62&key=54a309ac1c61be23aba0da3f"

aResponse = requests.get(url)

y = json.loads(aResponse.content)
json_test = json.dumps(y, indent = 4, sort_keys=True)
print(json_test)
csv = json_normalize(y['results'])
print(csv)

Displaying the output of this code is difficult and extremely confusing; therefore, I think its in both of our best interests that I leave it out. If that is a useful piece of information, I can add it.

The json.dumps portion simply orgranizes my json file so that it is easily viewable. Unfortunately, I can't post the entire json file because Stack isn't a huge fan of my formatting. Here is a small snippet:

{
"query_parameters": {
    "limit": 10,
    "mID": "54a309ae1c61be23aba0da62",
    "skip": 0,
    "sort": 1
},
"results": [
    {
        "cID": "5314ab42d34b6c5b402aead4",
        "content": "BE9kUwvLfsAmI",
        "content_data": {
            "added_with_admin": false,
            "dateAdded": 1393863490.072894,
            "embedLink": "http://media3.giphy.com/media/BE9kUwvLfsAmI/giphy.gif",
            "still_image": "http://media.giphy.com/media/BE9kUwvLfsAmI/200_s.gif",
            "tags": [
                "adam levine",
                "embarassed",
                "the voice",
                "confession"
            ]
        },
        "content_type": "gif",
        "index": 269,
        "parameters": {
            "mu": 35.92818823777915,
            "sigma": 1.88084276812386
        },
        "rank": 0
    },

There is about 10 more of these (ranging all the way up to 6119; however, I'm trying to get just part of this working). I want my output to be ordered as such: rank, tags, embedLink, mu, sigma, index. Here is an example of my desired output:

0, adam levine, embarassed, the voice, confession, http://media3.giphy.com/media/BE9kUwvLfsAmI/giphy.gif, 35.92818823777915, 1.88084276812386, 269

I would like to have it as a csv file; however, I think creating a dataframe using Pandas could also be quite useful. I think my problem occurs because I have such a large, embedded json file, and it's hard for the computer to organize this large data-set. Any advice would be appreciated!

Body:
First, you can use requests.json() instead of requests.text to get the response content as JSON.

import requests
import pandas as pd
from pprint import pprint

url = "https://www.qnt.io/api/results?pID=gifgif&mID=54a309ae1c61be23aba0da62&key=54a309ac1c61be23aba0da3f"

response = requests.get(url)
results = response.json()["results"]

# pprint(results)

[{'cID': '5314ab42d34b6c5b402aead4',
  'content': 'BE9kUwvLfsAmI',
  'content_data': {'added_with_admin': False,
                   'dateAdded': 1393863490.072894,
                   'embedLink': 'http://media3.giphy.com/media/BE9kUwvLfsAmI/giphy.gif',
                   'still_image': 'http://media.giphy.com/media/BE9kUwvLfsAmI/200_s.gif',
                   'tags': ['adam levine',
                            'embarassed',
                            'the voice',
                            'confession']},
  'content_type': 'gif',
  'index': 269,
  'parameters': {'mu': 35.92818823777915, 'sigma': 1.88084276812386},
  'rank': 0},
 {'cID': '5314ab4dd34b6c5b402aeb97',
  ...

Then you can load the dict with pd.DataFrame.from_dict:

df = pd.DataFrame.from_dict(results)

# print(df.head(2))

                        cID        content  \
0  5314ab42d34b6c5b402aead4  BE9kUwvLfsAmI
1  5314ab4dd34b6c5b402aeb97  NZhO1SEuFmhj2

                                        content_data content_type  index  \
0  {'embedLink': 'http://media3.giphy.com/media/B...          gif    269
1  {'embedLink': 'http://media1.giphy.com/media/N...          gif    464

                                          parameters  rank
0  {'mu': 35.92818823777915, 'sigma': 1.880842768...     0
1  {'mu': 35.70238333972232, 'sigma': 1.568292935...     1

And then use .apply(pd.Series) to further expand the columns in dict:

df = pd.concat([df.drop(["content_data"], axis=1), df["content_data"].apply(pd.Series)], axis=1)
df = pd.concat([df.drop(["parameters"], axis=1), df["parameters"].apply(pd.Series)], axis=1)

# print(df.head(2))
                        cID        content content_type  index  rank  \
0  5314ab42d34b6c5b402aead4  BE9kUwvLfsAmI          gif    269     0
1  5314ab4dd34b6c5b402aeb97  NZhO1SEuFmhj2          gif    464     1

   added_with_admin     dateAdded  \
0             False  1.393863e+09
1             False  1.393864e+09

                                           embedLink  \
0  http://media3.giphy.com/media/BE9kUwvLfsAmI/gi...
1  http://media1.giphy.com/media/NZhO1SEuFmhj2/gi...

                                         still_image  \
0  http://media.giphy.com/media/BE9kUwvLfsAmI/200...
1  http://media.giphy.com/media/NZhO1SEuFmhj2/200...

                                                tags         mu     sigma
0   [adam levine, embarassed, the voice, confession]  35.928188  1.880843
1  [ryan gosling, facepalm, embarrassed, confession]  35.702383  1.568293

And convert the tags from list to string:

df["tags"] = df["tags"].apply(lambda x: ", ".join(x))

# print(df.head(2)["tags"])

0     adam levine, embarassed, the voice, confession
1    ryan gosling, facepalm, embarrassed, confession

And get the columns you want finally:

df = df[["rank", "tags", "embedLink", "mu", "sigma", "index"]]

# print(df.head(2))

   rank                                             tags  \
0     0   adam levine, embarassed, the voice, confession
1     1  ryan gosling, facepalm, embarrassed, confession

                                           embedLink         mu     sigma  \
0  http://media3.giphy.com/media/BE9kUwvLfsAmI/gi...  35.928188  1.880843
1  http://media1.giphy.com/media/NZhO1SEuFmhj2/gi...  35.702383  1.568293

   index
0    269
1    464


问:
Possibility of adding libraries to android architecture
I got some doubts regarding the Android OS.

My question is, there are certain libraries and framework specified in the Android Architecture. So is there any possibility to add any other libraries based on my requirements? If yes, how do you do it?

答:
For add new libraries to your application just right click on the application and select the Properties and in that select JavaBuildPath from left side of the panel in that 4 tabs are available ,select the libraries tab from that and selct addJars from right side of the panel .

First you  copy and paste the library whatever you want and paste it in assets folder of the application.And then add that jar file to your application from assets using above process


答: It's because newNode->value = item, which stores in your nodes always a pointer to the same memory location p reserved outside your push and overwritten with new content again and again. To overcome this, write newNode->value = strdup(item) in order to copy the content. Don't forget to free it later on. If strdup is not available, you can easily replace it with newNode->value = malloc(strlen(item)+1);strcpy(newNode->value, item).

Title: Adding a new node to my linked list stack updates all my old nodes to the new node


问:
Make flex children inline-block
I would like to have the flex children rendered inline-block so that border-bottom is under the li's width instead of the container's width.

Apparently flex children can't be set as inline-block?

Is there a workaround to this problem?

.menu {
  display: flex;
  flex-flow: column;
  list-style: none;
  padding: 0;
}
.menu > li {
  display: inline-block;
  margin-bottom: 1rem;
  border-bottom: 3px solid black;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><ul class="menu">
  <li>Tab 1</li>
  <li>Tab 2</li>
  <li>Tab 3</li>
</ul></code>```

https://codepen.io/joshuajazleung/pen/EbwZmJ

答:
Add align-items: flex-start to the container:

.menu {
  display: flex;
  flex-flow: column;
  align-items: flex-start; /* NEW */
  list-style: none;
  padding: 0;
}
.menu > li {
  margin-bottom: 1rem;
  border-bottom: 3px solid black;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><ul class="menu">
  <li>Tab 1</li>
  <li>Tab 2</li>
  <li>Tab 3</li>
</ul></code>```

OR... switch from display: flex to display: inline-flex.

.menu {
  display: inline-flex;
  flex-flow: column;
  list-style: none;
  padding: 0;
}
.menu > li {
  margin-bottom: 1rem;
  border-bottom: 3px solid black;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><ul class="menu">
  <li>Tab 1</li>
  <li>Tab 2</li>
  <li>Tab 3</li>
</ul></code>```

More details here: Make flex items take content width, not width of parent container

Title: Make flex children inline-block

Body:
I would like to have the flex children rendered inline-block so that border-bottom is under the li's width instead of the container's width.

Apparently flex children can't be set as inline-block?

Is there a workaround to this problem?

.menu {
  display: flex;
  flex-flow: column;
  list-style: none;
  padding: 0;
}
.menu > li {
  display: inline-block;
  margin-bottom: 1rem;
  border-bottom: 3px solid black;
}

Tab 1

Tab 2

Tab 3

https://codepen.io/joshuajazleung/pen/EbwZmJ

Body:
Add align-items: flex-start to the container:

.menu {
  display: flex;
  flex-flow: column;
  align-items: flex-start; /* NEW */
  list-style: none;
  padding: 0;
}
.menu > li {
  margin-bottom: 1rem;
  border-bottom: 3px solid black;
}

<ul class="menu">
  <li>Tab 1</li>
  <li>Tab 2</li>
  <li>Tab 3</li>
</ul>

OR... switch from display: flex to display: inline-flex.

.menu {
  display: inline-flex;
  flex-flow: column;
  list-style: none;
  padding: 0;
}
.menu > li {
  margin-bottom: 1rem;
  border-bottom: 3px solid black;
}

<ul class="menu">
  <li>Tab 1</li>
  <li>Tab 2</li>
  <li>Tab 3</li>
</ul>

More details here: Make flex items take content width, not width of parent container


问:
Project Euler 1:Find the sum of all the multiples of 3 or 5 below 1000, works for 10 numbers but doesn't work for 1000

If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23. Find the sum of all the multiples of 3 or 5 below 1000.

So I decided to try and solve some problems on Euler site to improve with programming. While trying to solve the first problem I wrote a quick code to count the sum and it worked for 10 numbers, but for 1000 it shows me the answer: 166833 which is wrong and I can't really find an issue here. If someone could give me a hint to improve my algorythm so it would work.

```<code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Multiplies_of_3_and_5
{
  class Program
  {
    static void Main(string[] args)
    {
        int[] array = new int[7000];

        for (int j = 0; j<array.Length ;j++)
        {
            array[j] = j + 1;
        }

        int n = 1;
        int z = 1;
        int numbers = 0;

        for (int i = 0; i<999; i++)
        {
            if (array[i] == 3 * n )
            {
                n++;
                numbers += array[i];
            }

            else if (array[i] == 5 * z)
            {
                z++;
                numbers += array[i];
            }
        }
        Console.WriteLine(string.Join(" ", numbers));
        Console.ReadLine();
      }
   }
}
</code>```

答:
When reaching 15, n will increase but z won't. Therefore the second branch ("is divideable by 5") won't trigger anymore.

You can either use flags for both and then use those flags to increase numbers, n and z or use modulo as suggested.

Body:
If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23. Find the sum of all the multiples of 3 or 5 below 1000.

So I decided to try and solve some problems on Euler site to improve with programming. While trying to solve the first problem I wrote a quick code to count the sum and it worked for 10 numbers, but for 1000 it shows me the answer: 166833 which is wrong and I can't really find an issue here. If someone could give me a hint to improve my algorythm so it would work.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Multiplies_of_3_and_5
{
  class Program
  {
    static void Main(string[] args)
    {
        int[] array = new int[7000];

        for (int j = 0; j<array.Length ;j++)
        {
            array[j] = j + 1;
        }

        int n = 1;
        int z = 1;
        int numbers = 0;

        for (int i = 0; i<999; i++)
        {
            if (array[i] == 3 * n )
            {
                n++;
                numbers += array[i];
            }

            else if (array[i] == 5 * z)
            {
                z++;
                numbers += array[i];
            }
        }
        Console.WriteLine(string.Join(" ", numbers));
        Console.ReadLine();
      }
   }
}


问:
Calculating aggregate sums of non-exclusive values in Python dictionary
I've got a Python dictionary, and in my first key-value pair I have a list of varying strings (varying number and varying actual string).

```<code>my_dict = [{"var1":['a','b'],
           "var2": 34},
          {"var1":['a','c'],
           "var2": 2},
          {"var1":['c','d','e'],
           "var2": 17},
          {"var1":['b','e'],
           "var2": 29},
          {"var1":['a','d','e'],
           "var2": 10},
          {"var1":['b','d'],
           "var2": 21}]
</code>```

I want to work out the average and sum for each of the different values in the var1 key value pair. So for example, for the value 'a', the sum would be 34 (1st item) + 2 (2nd item) + 10 (5th item) = 46, and for b it would be 34 (1st) + 29 (4th) + 21 (6th) = 74. I'd like a row for each value in a dataframe.

I've tried Counter from collections but that doesn't fit the bill.

答:
Here is the sum code.  I will leave it to you to do the average code.

```<code>for item in my_dict:
    for thing in item['var1']:
        if thing not in results:
            results[thing] = 0
        results[thing] = results[thing] + item['var2']
</code>```

results  {'a': 46, 'b': 84, 'c': 19, 'd': 48, 'e': 56}

Body:
I've got a Python dictionary, and in my first key-value pair I have a list of varying strings (varying number and varying actual string).

my_dict = [{"var1":['a','b'],
           "var2": 34},
          {"var1":['a','c'],
           "var2": 2},
          {"var1":['c','d','e'],
           "var2": 17},
          {"var1":['b','e'],
           "var2": 29},
          {"var1":['a','d','e'],
           "var2": 10},
          {"var1":['b','d'],
           "var2": 21}]

I want to work out the average and sum for each of the different values in the var1 key value pair. So for example, for the value 'a', the sum would be 34 (1st item) + 2 (2nd item) + 10 (5th item) = 46, and for b it would be 34 (1st) + 29 (4th) + 21 (6th) = 74. I'd like a row for each value in a dataframe.

I've tried Counter from collections but that doesn't fit the bill.

Body:
Here is the sum code.  I will leave it to you to do the average code.

for item in my_dict:
    for thing in item['var1']:
        if thing not in results:
            results[thing] = 0
        results[thing] = results[thing] + item['var2']

results  {'a': 46, 'b': 84, 'c': 19, 'd': 48, 'e': 56}


问:
Is it possible to populate HTML table from a remote database in Android?
I am trying to get data from a remote database and show it on ANDROID using the HTML table. I am pretty lost. Please help me with this suggest me if it is possible.

Thanks in advance.

答:
Yes, that is possible, there is a default table for android that you can use:

```<code><TableLayout
    android:layout_width="138dp"
    android:layout_height="495dp"
    tools:layout_editor_absoluteX="8dp"
    tools:layout_editor_absoluteY="8dp">

    <TableRow
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

    <TableRow
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

    <TableRow
        android:layout_width="match_parent"
        android:layout_height="match_parent" />
</TableLayout>
</code>```

This shows 3 rows with 1 column

Body:
Yes, that is possible, there is a default table for android that you can use:

<TableLayout
    android:layout_width="138dp"
    android:layout_height="495dp"
    tools:layout_editor_absoluteX="8dp"
    tools:layout_editor_absoluteY="8dp">

    <TableRow
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

    <TableRow
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

    <TableRow
        android:layout_width="match_parent"
        android:layout_height="match_parent" />
</TableLayout>

This shows 3 rows with 1 column


问:
WCF REST service not returning DataContract object
I have a simple WCF service defined by the following ServiceContract:

```<code>[ServiceContract]
public interface IInventoryService
{
  [OperationContract]
  Item GetItemFromBarcode(string barcode);

  [OperationContract]
  string Test(string testString);
}
</code>```

With Item defined like this:

```<code>[DataContract]
public class Item
{
  [DataMember]
  public virtual int Id { get; set; }

  <Snip>
}
</code>```

And the actual service implemented thusly:

```<code>public class InventoryService : IInventoryService
{
  [WebGet(UriTemplate = "/Barcode/{barcode}/Item", ResponseFormat = WebMessageFormat.Json)]
  public Item GetItemFromBarcode(string barcode)
  {
     var item = (from b in repository.Query<ItemBarcode>()
             where b.BarcodeData == barcode
             select b.Item).FirstOrDefault();
     return item;

  }

  [WebGet(UriTemplate = "/Test/{testString}",ResponseFormat=WebMessageFormat.Xml)]
  public string Test(string testString)
  {
     return testString;
  }
}
</code>```

With the following in the app.config for the program hosting the service:

```<code><system.serviceModel>
  <behaviors>
     <serviceBehaviors>
        <behavior>
           <serviceMetadata httpGetEnabled="true"/>
        </behavior>
     </serviceBehaviors>
     <endpointBehaviors>
        <behavior name="RESTFriendly">
           <webHttp />
        </behavior>
     </endpointBehaviors>
  </behaviors>
  <services>
     <service name="InventoryService">
        <endpoint address="/Inventory" behaviorConfiguration="RESTFriendly" binding="webHttpBinding" contract="IInventoryService"/>
        <host>
           <baseAddresses>
              <add baseAddress="http://localhost:8080/"/>
           </baseAddresses>
        </host>
     </service>
  </services>
</system.serviceModel>
</code>```

Now that the code dump is out of the way, the issue: I can invoke the Test method just fine with curl or Fiddler, it returns a serialized string. However, invoking the method that returns an object returns nothing. Curl spits back curl: (56) Failure when receiving data from the peer and Fiddler responds ReadResponse() failed: The server did not return a response for this request.

From what I read, this should Just Work (tm). Is there something obvious I'm missing?

答: So, it seems you can't have DataMember of an interface type, like the IList<ItemBarcode>. There go my hopes of using my NHibernate model objects as DTOs.

Body:
I have a simple WCF service defined by the following ServiceContract:

[ServiceContract]
public interface IInventoryService
{
  [OperationContract]
  Item GetItemFromBarcode(string barcode);

  [OperationContract]
  string Test(string testString);
}

With Item defined like this:

[DataContract]
public class Item
{
  [DataMember]
  public virtual int Id { get; set; }

  <Snip>
}

And the actual service implemented thusly:

public class InventoryService : IInventoryService
{
  [WebGet(UriTemplate = "/Barcode/{barcode}/Item", ResponseFormat = WebMessageFormat.Json)]
  public Item GetItemFromBarcode(string barcode)
  {
     var item = (from b in repository.Query<ItemBarcode>()
             where b.BarcodeData == barcode
             select b.Item).FirstOrDefault();
     return item;

  }

  [WebGet(UriTemplate = "/Test/{testString}",ResponseFormat=WebMessageFormat.Xml)]
  public string Test(string testString)
  {
     return testString;
  }
}

With the following in the app.config for the program hosting the service:

<system.serviceModel>
  <behaviors>
     <serviceBehaviors>
        <behavior>
           <serviceMetadata httpGetEnabled="true"/>
        </behavior>
     </serviceBehaviors>
     <endpointBehaviors>
        <behavior name="RESTFriendly">
           <webHttp />
        </behavior>
     </endpointBehaviors>
  </behaviors>
  <services>
     <service name="InventoryService">
        <endpoint address="/Inventory" behaviorConfiguration="RESTFriendly" binding="webHttpBinding" contract="IInventoryService"/>
        <host>
           <baseAddresses>
              <add baseAddress="http://localhost:8080/"/>
           </baseAddresses>
        </host>
     </service>
  </services>
</system.serviceModel>

Now that the code dump is out of the way, the issue: I can invoke the Test method just fine with curl or Fiddler, it returns a serialized string. However, invoking the method that returns an object returns nothing. Curl spits back curl: (56) Failure when receiving data from the peer and Fiddler responds ReadResponse() failed: The server did not return a response for this request.

From what I read, this should Just Work (tm). Is there something obvious I'm missing?


问:
If I reassigned OUT in Perl 6, how can I change it back to stdout?

A very simple question, but I can't easily find an answer.

I want all say in a block to go to a file. But then I want my output to return to STDOUT. How to do that?

my $fh_foo = open "foo.txt", :w;
$*OUT = $fh_foo;
say "Hello, foo! Printing to foo.txt";

$*OUT = ????;
say "This should be printed on the screen";
```

答:
The simple answer is to only change it lexically

my $fh-foo = open "foo.txt", :w;
{
  my $*OUT = $fh-foo;
  say "Hello, foo! Printing to foo.txt";
}

say "This should be printed on the screen";
```

<pre class="lang-perl6 prettyprint-override"><code>my $fh-foo = open "foo.txt", :w;

with $fh-foo -> $*OUT {
  say "Hello, foo! Printing to foo.txt";
}

say "This should be printed on the screen";
</code>```

If you have to work around someone else's code you could reopen it the same way it was opened in the first place.

my $fh-foo = open "foo.txt", :w;
$*OUT = $fh-foo;
say "Hello, foo! Printing to foo.txt";

$*OUT = IO::Handle.new( path => IO::Special.new('<STDOUT>') ).open();

say "This should be printed on the screen";
```

Body:
The simple answer is to only change it lexically

my $fh-foo = open "foo.txt", :w;
{
  my $*OUT = $fh-foo;
  say "Hello, foo! Printing to foo.txt";
}

say "This should be printed on the screen";

my $fh-foo = open "foo.txt", :w;

with $fh-foo -> $*OUT {
  say "Hello, foo! Printing to foo.txt";
}

say "This should be printed on the screen";

If you have to work around someone else's code you could reopen it the same way it was opened in the first place.

my $fh-foo = open "foo.txt", :w;
$*OUT = $fh-foo;
say "Hello, foo! Printing to foo.txt";

$*OUT = IO::Handle.new( path => IO::Special.new('<STDOUT>') ).open();

say "This should be printed on the screen";


问:
create or update python dictionary entry
Perhaps I've been spoiled by Brand X programming languages, but is there a better pythonic idiom for the following?

```<code>thing_dict = {}

def find_or_create_thing(key):
    if (thing_dict.has_key(key)):
        thing = thing_dict[key]
    else:
        thing = create_new_thing(key)
        thing_dict[key] = thing
    return thing
</code>```

It seems like something like this could be done in one or two lines.  I considered using a Conditional Expression, but Python's odd syntax simply didn't lend itself to legibility.

I also considered a try: ... except KeyError:, but that was just about as much text and probably considerably more execution overhead.

P.S. I know that asking programming style questions on S.O. is problematic, but I'll take my chances...

答:
Using in is more Pythonic

```<code>thing_dict = {}

def find_or_create_thing(key):
    if not key in thing_dict:
        thing_dict[key] = create_new_thing(key)
    return thing_dict[key]
</code>```

If you absolutely need the function on two lines:

```<code>thing_dict = {}

def find_or_create_thing(key):
    if not key in thing_dict: thing_dict[key] = create_new_thing(key)
    return thing_dict[key]
</code>```

Body:
Perhaps I've been spoiled by Brand X programming languages, but is there a better pythonic idiom for the following?

thing_dict = {}

def find_or_create_thing(key):
    if (thing_dict.has_key(key)):
        thing = thing_dict[key]
    else:
        thing = create_new_thing(key)
        thing_dict[key] = thing
    return thing

It seems like something like this could be done in one or two lines.  I considered using a Conditional Expression, but Python's odd syntax simply didn't lend itself to legibility.

I also considered a try: ... except KeyError:, but that was just about as much text and probably considerably more execution overhead.

P.S. I know that asking programming style questions on S.O. is problematic, but I'll take my chances...

Body:
Using in is more Pythonic

thing_dict = {}

def find_or_create_thing(key):
    if not key in thing_dict:
        thing_dict[key] = create_new_thing(key)
    return thing_dict[key]

If you absolutely need the function on two lines:

thing_dict = {}

def find_or_create_thing(key):
    if not key in thing_dict: thing_dict[key] = create_new_thing(key)
    return thing_dict[key]


问:
How do I output a result of an each statement to a variable?
I have this code that prints each character of a string twice:

```<code>r = "12345"
r.split("").each do |ch|
  puts "#{ch}#{ch}"
end
</code>```

I get this output:

```<code>11
22
33
44
55
</code>```

I want to store the output "1122334455" in a variable. How do I rewrite the code to do this?

Body:
I have this code that prints each character of a string twice:

r = "12345"
r.split("").each do |ch|
  puts "#{ch}#{ch}"
end

I get this output:

11
22
33
44
55

I want to store the output "1122334455" in a variable. How do I rewrite the code to do this?

Body:
One way to do this:

r.gsub(/(.)/,'\1\1') #=> "1122334455"


问:
video file transfer empty reponse readystate 0, status 0 and statusText error
I have a problem with a large file transfer using jquery ajax function and php by post method:

I have the javascript function:

```<code>function multimedia_update(){

if( contador_peticiones > 0 ){return;}

contador_peticiones++;

var formData = new FormData($('#sky-form')[0]);

$.ajax({
    xhr: function()
      {
        var xhr = new window.XMLHttpRequest();
        //Upload progress
        xhr.upload.addEventListener("progress", function(evt){
          if (evt.lengthComputable) {
            var percentComplete = ((evt.loaded / evt.total)*100)-2;
            //Do something with upload progress
            $("#progreso").css('width', percentComplete+'%');
            $("#progreso").html(percentComplete+'%');
          }
        }, false);

        xhr.addEventListener("error", onError, false);
        //Download progress
        xhr.addEventListener("progress", function(evt){
          if (evt.lengthComputable) {
            var percentComplete = ((evt.loaded / evt.total)*100)-2;
            //Do something with download progress
            $("#progreso").css('width', percentComplete+'%');
            $("#progreso").html(percentComplete+'%');
          }
        }, false);
        return xhr;
      },
    type:"POST",
    dataType:"JSONP",
    url:"drivers/multimedia-update.php",
    data:formData,
    //necesario para subir archivos via ajax
    cache: false,
    contentType: false,
    processData: false,
    timeout: 3600000,
    beforeSend: function(){
        $('.alert-info').fadeIn();
    },
    success: function(datos){
        var obj = jQuery.parseJSON( datos );
        switch( parseInt(datos[0].respuesta_final) ){
            case -1:
                alert('Error al guardar');
            break;
            case 0:
                alert('Hubo un problema al guardar alguna información, por favor notificar.');
            break;
            case 1:
                alert('Éxito al guardar.');
            break;
        }
        contador_peticiones = 0;
        multimedia_grid();
    },
    error: function(jqXHR, status, error) {
        mi_respuesta = jqXHR;
        console.log(jqXHR);
        console.log("espacio");
        console.log(status);
        console.log("espacio");
        //console.log(error);
        //alert("error en la petición 124");
    }
})
.done(function(){
    contador_peticiones = 0;
});

return false;

}
</code>```

In PHP the code to upload file by a ftp client (SubirArchivo function):

```<code>if(isset ($_FILES['file2']['name']) ){
  if( $_FILES['file2']['name'] != '' ){
     $nombre_archivo_video = clean($_FILES["file2"]["name"]);
     $nombre_archivo_video = substr(md5(uniqid(rand())),0,4).'_'.$nombre_archivo_video;
     $directorio = '/video/repository/';
     $respuesta2 = SubirArchivo($nombre_archivo_video, $_FILES["file2"]["tmp_name"], $directorio);
  }
}
</code>```

The form:

```<code><form action="" id="sky-form" class="sky-form" enctype="multipart/form-data">
    <fieldset>
      <div class="row">
        <section>
         <p>Video</p>
         <p>Archivo en formato mp4</p>
         <label for="file" class="input input-file">
          <div class="button">
            <input id="file-4" type="file" class="file" name="file2" accept="video/mp4" onchange="this.parentNode.nextSibling.nextSibling.value = this.value" />Browse
          </div>
          <input type="text" placeholder="Video" readonly="" />
         </label>
        </section>
      </div>
    </fieldset>
</form>
</code>```

My php.ini config:

```<code>max_execution_time = 0
max_input_time = -1
memory_limit = 512M
post_max_size = 368M
upload_max_filesize = 368M
</code>```

The problem is that it not works with files larger to 80M, smaller it works fine, so I don't know exactly what is the bug.

I would like it to work with at least the limit of 300M.

I have been serach about my problem. I now add more information. When the error occurs, in console I print the XHR response that throws me: readystate 0, status 0 and statusText error. And I have tried to implement the following answers: link1, link2 But I still have the same problem. I'm still looking for...

Update:

Well then following the topic, I keep doing tests and now it turns out that it is not a problem of the file size. Apparently the file has a problem or error, however I still do not know exactly why. I was reading this problem when trying to load a docx file or an image with extension not supported by the GD.

答: Well I do not know if this is really an answer. But after a while I could corroborate that the error could be presented in shared servers, which supposedly give you the freedom to configure the file transfer parameters but they do not work. Specifically, the problem happened to me in the godaddy service and one that is called dissenynet. The problem was finally solved when the company hired a dedicated server (in my case, IBM cloud), I had to mount my own LAMP server and be able to configure the necessary variables. I can currently upload files up to 500 MB without problems. As an additional note, this type of conflicts can cause errors such as "HTTP error" in wordpress since the transfer is not handled correctly. Apparently the "special" services for wordpress have already solved this part since it is common that thanks to the freedoms that wordpress gives you, this type of error has been presented for a long time. I hope this will help.</p>

Body:
I have a problem with a large file transfer using jquery ajax function and php by post method:

I have the javascript function:

function multimedia_update(){

if( contador_peticiones > 0 ){return;}

contador_peticiones++;

var formData = new FormData($('#sky-form')[0]);

$.ajax({
    xhr: function()
      {
        var xhr = new window.XMLHttpRequest();
        //Upload progress
        xhr.upload.addEventListener("progress", function(evt){
          if (evt.lengthComputable) {
            var percentComplete = ((evt.loaded / evt.total)*100)-2;
            //Do something with upload progress
            $("#progreso").css('width', percentComplete+'%');
            $("#progreso").html(percentComplete+'%');
          }
        }, false);

        xhr.addEventListener("error", onError, false);
        //Download progress
        xhr.addEventListener("progress", function(evt){
          if (evt.lengthComputable) {
            var percentComplete = ((evt.loaded / evt.total)*100)-2;
            //Do something with download progress
            $("#progreso").css('width', percentComplete+'%');
            $("#progreso").html(percentComplete+'%');
          }
        }, false);
        return xhr;
      },
    type:"POST",
    dataType:"JSONP",
    url:"drivers/multimedia-update.php",
    data:formData,
    //necesario para subir archivos via ajax
    cache: false,
    contentType: false,
    processData: false,
    timeout: 3600000,
    beforeSend: function(){
        $('.alert-info').fadeIn();
    },
    success: function(datos){
        var obj = jQuery.parseJSON( datos );
        switch( parseInt(datos[0].respuesta_final) ){
            case -1:
                alert('Error al guardar');
            break;
            case 0:
                alert('Hubo un problema al guardar alguna información, por favor notificar.');
            break;
            case 1:
                alert('Éxito al guardar.');
            break;
        }
        contador_peticiones = 0;
        multimedia_grid();
    },
    error: function(jqXHR, status, error) {
        mi_respuesta = jqXHR;
        console.log(jqXHR);
        console.log("espacio");
        console.log(status);
        console.log("espacio");
        //console.log(error);
        //alert("error en la petición 124");
    }
})
.done(function(){
    contador_peticiones = 0;
});

return false;

}

In PHP the code to upload file by a ftp client (SubirArchivo function):

if(isset ($_FILES['file2']['name']) ){
  if( $_FILES['file2']['name'] != '' ){
     $nombre_archivo_video = clean($_FILES["file2"]["name"]);
     $nombre_archivo_video = substr(md5(uniqid(rand())),0,4).'_'.$nombre_archivo_video;
     $directorio = '/video/repository/';
     $respuesta2 = SubirArchivo($nombre_archivo_video, $_FILES["file2"]["tmp_name"], $directorio);
  }
}

The form:

<form action="" id="sky-form" class="sky-form" enctype="multipart/form-data">
    <fieldset>

Video

Archivo en formato mp4

            <input id="file-4" type="file" class="file" name="file2" accept="video/mp4" onchange="this.parentNode.nextSibling.nextSibling.value = this.value" />Browse

          <input type="text" placeholder="Video" readonly="" />

    </fieldset>
</form>

My php.ini config:

max_execution_time = 0
max_input_time = -1
memory_limit = 512M
post_max_size = 368M
upload_max_filesize = 368M

The problem is that it not works with files larger to 80M, smaller it works fine, so I don't know exactly what is the bug.

I would like it to work with at least the limit of 300M.

I have been serach about my problem. I now add more information. When the error occurs, in console I print the XHR response that throws me: readystate 0, status 0 and statusText error. And I have tried to implement the following answers: link1, link2 But I still have the same problem. I'm still looking for...

Update:

Well then following the topic, I keep doing tests and now it turns out that it is not a problem of the file size. Apparently the file has a problem or error, however I still do not know exactly why. I was reading this problem when trying to load a docx file or an image with extension not supported by the GD.


问:
Extract all values from data in JSON
I have a json response with multiple movie titles in "data". Is there a way to quickly extract them? I need an array with just movie titles.

```<code>{
  "page": "2",
  "per_page": 10,
  "total": 13,
  "total_pages": 2,
  "data": [{
    "Poster": "N/A",
    "Title": "They Call Me Spiderman",
    "Type": "movie",
    "Year": 2016,
    "imdbID": "tt5861236"
  }, {
    "Poster": "N/A",
    "Title": "The Death of Spiderman",
    "Type": "movie",
    "Year": 2015,
    "imdbID": "tt5921428"
  }, {
    "Poster": "https://images-na.ssl-images-amazon.com/images/M/MV5BZDlmMGQwYmItNTNmOS00OTNkLTkxNTYtNDM3ZWVlMWUyZDIzXkEyXkFqcGdeQXVyMTA5Mzk5Mw@@._V1_SX300.jpg",
    "Title": "Spiderman in Cannes",
    "Type": "movie",
    "Year": 2016,
    "imdbID": "tt5978586"
  }]
}
</code>```

答:
using Newtonsoft.Json.Linq might do the simplest work for you.

```<code>using Newtonsoft.Json.Linq;

List<string> movieTitles = (JObject.Parse(json)["data"]).
                   Cast<JToken>().Select(x => x["Title"].ToString()).ToList();
</code>```

Title: Extract all values from data in JSON

Body:
I have a json response with multiple movie titles in "data". Is there a way to quickly extract them? I need an array with just movie titles.

{
  "page": "2",
  "per_page": 10,
  "total": 13,
  "total_pages": 2,
  "data": [{
    "Poster": "N/A",
    "Title": "They Call Me Spiderman",
    "Type": "movie",
    "Year": 2016,
    "imdbID": "tt5861236"
  }, {
    "Poster": "N/A",
    "Title": "The Death of Spiderman",
    "Type": "movie",
    "Year": 2015,
    "imdbID": "tt5921428"
  }, {
    "Poster": "https://images-na.ssl-images-amazon.com/images/M/MV5BZDlmMGQwYmItNTNmOS00OTNkLTkxNTYtNDM3ZWVlMWUyZDIzXkEyXkFqcGdeQXVyMTA5Mzk5Mw@@._V1_SX300.jpg",
    "Title": "Spiderman in Cannes",
    "Type": "movie",
    "Year": 2016,
    "imdbID": "tt5978586"
  }]
}

Body:
using Newtonsoft.Json.Linq might do the simplest work for you.

using Newtonsoft.Json.Linq;

List<string> movieTitles = (JObject.Parse(json)["data"]).
                   Cast<JToken>().Select(x => x["Title"].ToString()).ToList();