问:
Sound Play / Stop / Pause
I'm developing a sound JavaScript library. I can play sound with below code.

```<code>var soundPlayer = null;

function playSound(){

soundPlayer = new Audio(soundName).play();

}
</code>```

How can I stop and pause this audio? When I try like this:

```<code>soundPlayer.pause();
</code>```

Or

```<code>soundPlayer.stop();
</code>```

But I get this error:

```<code>Uncaught TypeError: soundPlayer.stop is not a function
</code>```

How can I do that?

答:
If you change that:

```<code>soundPlayer = new Audio(soundName).play();
</code>```

To that:

```<code>soundPlayer = new Audio(soundName);
soundPlayer.play();
</code>```

Your pause will be working. The problem is that you assigned "play" function to soundPlayer. SoundPlayer isnt an Audio object now.

Instead of stop() use:

```<code>soundPlayer.pause();
soundPlayer.currentTime = 0;
</code>```

It works the same I guess.

Title: Sound Play / Stop / Pause

Body:
I'm developing a sound JavaScript library. I can play sound with below code.

var soundPlayer = null;

function playSound(){

soundPlayer = new Audio(soundName).play();

}

How can I stop and pause this audio? When I try like this:

soundPlayer.pause();

Or

soundPlayer.stop();

But I get this error:

Uncaught TypeError: soundPlayer.stop is not a function

How can I do that?

Body:
If you change that:

soundPlayer = new Audio(soundName).play();

To that:

soundPlayer = new Audio(soundName);
soundPlayer.play();

Your pause will be working. The problem is that you assigned "play" function to soundPlayer. SoundPlayer isnt an Audio object now.

Instead of stop() use:

soundPlayer.pause();
soundPlayer.currentTime = 0;

It works the same I guess.


来源: stackexchange

问:
How to get the coordinates of QR code using ZXing?
I can get the value of the QR code using ZXing library but I also need the coordinates of the corner points of the QR code. How can I access those coordinates. </p>

答:
I don't know exactly which corner coordinates you want to extract.
But I'm quite sure you can calculate them from the result points got from the
Result.getResultPoints() method.

Example: With the following image (200x200 pixels) and code snippet

```<code>BufferedImage image = ImageIO.read(new File("QRCode-1.png"));
BinaryBitmap binaryBitmap = new BinaryBitmap(new HybridBinarizer(
        new BufferedImageLuminanceSource(image)));
Reader reader = new QRCodeReader();
Result result = reader.decode(binaryBitmap);
System.out.println("text: " + result.getText());
ResultPoint[] resultPoints = result.getResultPoints();
System.out.println("resultPoints:");
for (int i = 0; i < resultPoints.length; i++) {
    ResultPoint resultPoint = resultPoints[i];
    System.out.print("  [" + i + "]:");
    System.out.print(" x = " + resultPoint.getX());
    System.out.print(", y = " + resultPoint.getY());
    if (resultPoint instanceof FinderPattern)
        System.out.print(", estimatedModuleSize = "
                + ((FinderPattern) resultPoint).getEstimatedModuleSize());
    System.out.println();
}
</code>```

I get this output:

```<code>text: Hello World!
resultPoints:
  [0]: x = 36.5, y = 162.5, estimatedModuleSize = 9.0
  [1]: x = 36.5, y = 36.5, estimatedModuleSize = 9.0
  [2]: x = 162.5, y = 36.5, estimatedModuleSize = 9.0
</code>```

x and y are the center coordinates of the square finder patterns.
Knowing that the QRCode finder patterns have size of 7x7 modules,
you can easily calculate the corner coordinates.

ContentLicense: CC BY-SA 3.0

Body:
I don't know exactly which corner coordinates you want to extract.
But I'm quite sure you can calculate them from the result points got from the
Result.getResultPoints() method.

Example: With the following image (200x200 pixels) and code snippet

BufferedImage image = ImageIO.read(new File("QRCode-1.png"));
BinaryBitmap binaryBitmap = new BinaryBitmap(new HybridBinarizer(
        new BufferedImageLuminanceSource(image)));
Reader reader = new QRCodeReader();
Result result = reader.decode(binaryBitmap);
System.out.println("text: " + result.getText());
ResultPoint[] resultPoints = result.getResultPoints();
System.out.println("resultPoints:");
for (int i = 0; i < resultPoints.length; i++) {
    ResultPoint resultPoint = resultPoints[i];
    System.out.print("  [" + i + "]:");
    System.out.print(" x = " + resultPoint.getX());
    System.out.print(", y = " + resultPoint.getY());
    if (resultPoint instanceof FinderPattern)
        System.out.print(", estimatedModuleSize = "
                + ((FinderPattern) resultPoint).getEstimatedModuleSize());
    System.out.println();
}

I get this output:

text: Hello World!
resultPoints:
  [0]: x = 36.5, y = 162.5, estimatedModuleSize = 9.0
  [1]: x = 36.5, y = 36.5, estimatedModuleSize = 9.0
  [2]: x = 162.5, y = 36.5, estimatedModuleSize = 9.0

x and y are the center coordinates of the square finder patterns.
Knowing that the QRCode finder patterns have size of 7x7 modules,
you can easily calculate the corner coordinates.


问:
Removing unwanted table cell borders with CSS
I have a peculiar and frustrating problem. For the simple markup:

1	2	3

a	b>	c

x	y	z

```

I apply different background-color values to the thead, tr, and tr odd elements. The problem is that in most browsers, every cell has an unwanted border which is not the color of any of the table rows. Only in Firefox 3.5 does the table have no borders in any cell.

I'd just like to know how to remove these borders in the other major browsers so that the only thing you see in the table are the alternating row colors.

答:
to remove the border , juste using css like this : </p>

```<code>td {
 border-style : hidden!important;
}
</code>```

Body:
I have a peculiar and frustrating problem. For the simple markup:

1	2	3

a	b>	c

x	y	z

I apply different background-color values to the thead, tr, and tr odd elements. The problem is that in most browsers, every cell has an unwanted border which is not the color of any of the table rows. Only in Firefox 3.5 does the table have no borders in any cell.

I'd just like to know how to remove these borders in the other major browsers so that the only thing you see in the table are the alternating row colors.

Body:
to remove the border , juste using css like this :

td {
 border-style : hidden!important;
}


问:
splash screen not work with navigation drawer
navigation drawer is working perfect but when i added splash screen to my project it not work

splasScreen

manifest

答:
```<code>package com.nulledapps.website2app;

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

public class SplashScreen extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_splash_screen);
        Thread mythraed = new Thread(){
            @Override
            public void run() {
                try {
                    sleep(3000);
                    Intent intent = new Intent(getApplicationContext(),MainActivity.class);
                    startActivity(intent);
                    finish();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        };
        mythraed.start();
    }
}
</code>```


问:
How do I select distinct values from multiple mysql columns and put them in one PHP array?
I have a table for songs, where each song can have up to 3 different genres. So in my table, for each song I have column genre1, genre2, and genre3. I'm trying to display all the genres available in a list.

Here's a random example set:

```<code>genre1    genre2    genre3
metal     jazz
metal     country   pop
oldies    metal
rap
jazz      hip-hop   choir
choir     metal     jazz
</code>```

I want the list, done in php, to display in alphabetical order the available distinct genres to choose from. So it should list this:

Choir

Country

Hip-hop

Jazz

Metal

Oldies

Pop

Rap

All help is appreciated. Perhaps I'm not going about this the smartest way, but I couldn't think of a better way.

答:
So the separate columns don't make a difference? If that is the case you can use a UNION

```<code>SELECT genre1 AS g FROM t UNION SELECT genre2 AS g FROM t UNION SELECT genre3 AS g FROM t
</code>```

If you have a WHERE clause, then you will need to copy it 3 times, or use an intermediate temporary table

Good luck!

table:

```<code>mysql> SELECT genre1, genre2, genre3 FROM music;
+--------+---------+--------+
| genre1 | genre2  | genre3 |
+--------+---------+--------+
| metal  | jazz    |        |
| metal  | country | pop    |
| oldies | metal   |        |
| rap    |         |        |
| jazz   | hip-hop | choir  |
| choir  | metal   | jazz   |
+--------+---------+--------+
6 rows in set (0.00 sec)
</code>```

grouping:

```<code>mysql> SELECT genre1 AS g FROM music UNION ALL
          SELECT genre2 AS g FROM music UNION ALL
          SELECT genre3 AS g FROM music
+---------+
| g       |
+---------+
| metal   |
| metal   |
| oldies  |
| rap     |
| jazz    |
| choir   |
| jazz    |
| country |
| metal   |
|         |
| hip-hop |
| metal   |
|         |
| pop     |
|         |
|         |
| choir   |
| jazz    |
+---------+
18 rows in set (0.00 sec)
</code>```

count:

```<code>mysql> SELECT g, COUNT(*) AS c FROM
             (SELECT genre1 AS g FROM music UNION ALL
              SELECT genre2 AS g FROM music UNION ALL
              SELECT genre3 AS g FROM music)
       AS tg GROUP BY g;
+---------+---+
| g       | c |
+---------+---+
|         | 4 |
| choir   | 2 |
| country | 1 |
| hip-hop | 1 |
| jazz    | 3 |
| metal   | 4 |
| oldies  | 1 |
| pop     | 1 |
| rap     | 1 |
+---------+---+
9 rows in set (0.01 sec)
</code>```

Body:
I have a table for songs, where each song can have up to 3 different genres. So in my table, for each song I have column genre1, genre2, and genre3. I'm trying to display all the genres available in a list.

Here's a random example set:

genre1    genre2    genre3
metal     jazz
metal     country   pop
oldies    metal
rap
jazz      hip-hop   choir
choir     metal     jazz

I want the list, done in php, to display in alphabetical order the available distinct genres to choose from. So it should list this:

Choir

Country

Hip-hop

Jazz

Metal

Oldies

Pop

Rap

All help is appreciated. Perhaps I'm not going about this the smartest way, but I couldn't think of a better way.

Body:
So the separate columns don't make a difference? If that is the case you can use a UNION

SELECT genre1 AS g FROM t UNION SELECT genre2 AS g FROM t UNION SELECT genre3 AS g FROM t

If you have a WHERE clause, then you will need to copy it 3 times, or use an intermediate temporary table

Good luck!

table:

mysql> SELECT genre1, genre2, genre3 FROM music;
+--------+---------+--------+
| genre1 | genre2  | genre3 |
+--------+---------+--------+
| metal  | jazz    |        |
| metal  | country | pop    |
| oldies | metal   |        |
| rap    |         |        |
| jazz   | hip-hop | choir  |
| choir  | metal   | jazz   |
+--------+---------+--------+
6 rows in set (0.00 sec)

grouping:

mysql> SELECT genre1 AS g FROM music UNION ALL
          SELECT genre2 AS g FROM music UNION ALL
          SELECT genre3 AS g FROM music
+---------+
| g       |
+---------+
| metal   |
| metal   |
| oldies  |
| rap     |
| jazz    |
| choir   |
| jazz    |
| country |
| metal   |
|         |
| hip-hop |
| metal   |
|         |
| pop     |
|         |
|         |
| choir   |
| jazz    |
+---------+
18 rows in set (0.00 sec)

count:

mysql> SELECT g, COUNT(*) AS c FROM
             (SELECT genre1 AS g FROM music UNION ALL
              SELECT genre2 AS g FROM music UNION ALL
              SELECT genre3 AS g FROM music)
       AS tg GROUP BY g;
+---------+---+
| g       | c |
+---------+---+
|         | 4 |
| choir   | 2 |
| country | 1 |
| hip-hop | 1 |
| jazz    | 3 |
| metal   | 4 |
| oldies  | 1 |
| pop     | 1 |
| rap     | 1 |
+---------+---+
9 rows in set (0.01 sec)

ContentLicense: CC BY-SA 2.5


问:
.net Regex to capture groups plus everything else
I am trying to create a .net regex that will capture the whole string into different groups. Capturing the groups is easy but capturing the rest is beyond me.

The [BBCode] markers could happen anywhere in the string, or be the only thing, or not be present at all. There also maybe [ brackets ] in the string.

Having group names would be a bonus.

```<code>class Program
{
    static void Main(string[] args)
    {
        string input = "thinking [ of using ] BBCode format [A=16] and [E=2] here [V=8] and so on";
        string regexString = @"((\[A=[0-9]+\])|(\[E=[0-9]+\])|(\[V=[0-9]+\]))";
        MatchCollection matches = Regex.Matches(input, regexString);

        foreach (Match match in matches)
        {
            Console.WriteLine(match.Value);
        }
   }
}
</code>```

The result I am after is (one group per line)

thinking [ of using ] BBCode format

[A=16]

and

[E=2]

here

[V=8]

and so on

答:
The regex itself is actually rather simple:

```<code>var input = "thinking [ of using ] BBCode format [A=16] and [E=2] here [V=8] and so on";

var pattern = @"^(?:(.*?)(\[[AEV]=\d+\]))*(.*?)$";

var match = Regex.Match(input, pattern);
</code>```

The issue however is that you usually cannot capture variable count of groups. .NET supports this though, but you need to go through the groups and their captures to actually get all the parts you need. The full code would look like this:

```<code>var input = "thinking [ of using ] BBCode format [A=16] and [E=2] here [V=8] and so on";

var pattern = @"^(?:(.*?)(\[[AEV]=\d+\]))*(.*?)$";

var match = Regex.Match(input, pattern);

var captures =
    match
        .Groups
        .OfType<Group>()
        .Skip(1) // first Group is the whole Match itself
        .SelectMany(g => g.Captures.OfType<Capture>())
        .OrderBy(c => c.Index); // order the captures by index to get them in appearance order, not in group order

foreach (var capture in captures)
{
    System.Console.WriteLine(capture.Value);
}
</code>```

This can be easily extended to support group names (does not seem very valuable though) or other tags.

Body:
I am trying to create a .net regex that will capture the whole string into different groups. Capturing the groups is easy but capturing the rest is beyond me.

The [BBCode] markers could happen anywhere in the string, or be the only thing, or not be present at all. There also maybe [ brackets ] in the string.

Having group names would be a bonus.

class Program
{
    static void Main(string[] args)
    {
        string input = "thinking [ of using ] BBCode format [A=16] and [E=2] here [V=8] and so on";
        string regexString = @"((\[A=[0-9]+\])|(\[E=[0-9]+\])|(\[V=[0-9]+\]))";
        MatchCollection matches = Regex.Matches(input, regexString);

        foreach (Match match in matches)
        {
            Console.WriteLine(match.Value);
        }
   }
}

The result I am after is (one group per line)

thinking [ of using ] BBCode format

[A=16]

and

[E=2]

here

[V=8]

and so on

Body:
The regex itself is actually rather simple:

var input = "thinking [ of using ] BBCode format [A=16] and [E=2] here [V=8] and so on";

var pattern = @"^(?:(.*?)(\[[AEV]=\d+\]))*(.*?)$";

var match = Regex.Match(input, pattern);

The issue however is that you usually cannot capture variable count of groups. .NET supports this though, but you need to go through the groups and their captures to actually get all the parts you need. The full code would look like this:

var input = "thinking [ of using ] BBCode format [A=16] and [E=2] here [V=8] and so on";

var pattern = @"^(?:(.*?)(\[[AEV]=\d+\]))*(.*?)$";

var match = Regex.Match(input, pattern);

var captures =
    match
        .Groups
        .OfType<Group>()
        .Skip(1) // first Group is the whole Match itself
        .SelectMany(g => g.Captures.OfType<Capture>())
        .OrderBy(c => c.Index); // order the captures by index to get them in appearance order, not in group order

foreach (var capture in captures)
{
    System.Console.WriteLine(capture.Value);
}

This can be easily extended to support group names (does not seem very valuable though) or other tags.


问:
How can I tell jackson to ignore a property for which I don't have control over the source code?
Long story short, one of my entities has a GeometryCollection that throws an exception when you call "getBoundary" (the why of this is another book, for now let's say this is the way it works).

Is there a way I can tell Jackson not to include that specific getter? I know I can use @JacksonIgnore when I do own/control the code. But this is not case, jackson ends reaching this point through continuous serialization of the parent objects. I saw a filtering option in jackson documentation. Is that a plausible solution?

Thanks!

答:
Annotation based approach is better. But sometimes manual operation is needed. For this purpose you can use without method of ObjectWriter.

ObjectMapper mapper   = new ObjectMapper().configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false)
ObjectWriter writer   = mapper.writer().withoutAttribute("property1").withoutAttribute("property2");
String       jsonText = writer.writeValueAsString(sourceObject);
```


问:
How to set  to default property given 's property already define in css
My web pages have a lot of  without class and their property were set in css as below:

```<code>a{
text-decoration:none;
color:black;
}

a:hover, a:active{
color:green;
}
</code>```

And now I have  tags that with class="tnc" and I want it to have the default property which is blue color text with underline and when active it change to red color text.

I tried this but not work:

```<code>a.tnc{
color: initial;
text-decoration: initial;
}

a.tnc:hover, a.tnc:active{
color: initial;
}
</code>```

Any help is appreciated. :)

a:hover, a:active{
 color:green;
}

a.tnc{
 color: initial !important;
 text-decoration: initial;
}

a.tnc:hover, a.tnc:active{
 color: initial;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code>I agree with the terms and conditions</code>```

答:
Try this:</p>

```<code>a.tnc{
color: initial !important;
text-decoration: initial !important;
}

a.tnc:hover, a.tnc:active{
color: initial !important;
}
</code>```

Title: How to set <a class="class"> to default property given <a>'s property already define in css

Body:
My web pages have a lot of  without class and their property were set in css as below:

a{
text-decoration:none;
color:black;
}

a:hover, a:active{
color:green;
}

And now I have  tags that with class="tnc" and I want it to have the default property which is blue color text with underline and when active it change to red color text.

I tried this but not work:

a.tnc{
color: initial;
text-decoration: initial;
}

a.tnc:hover, a.tnc:active{
color: initial;
}

Any help is appreciated. :)

a:hover, a:active{
 color:green;
}

a.tnc{
 color: initial !important;
 text-decoration: initial;
}

a.tnc:hover, a.tnc:active{
 color: initial;
}

I agree with the terms and conditions

Body:
Try this:

a.tnc{
color: initial !important;
text-decoration: initial !important;
}

a.tnc:hover, a.tnc:active{
color: initial !important;
}


问:
python 3 error: float is required
I didn't understand why I'm getting an error for this line of code:

test_data:  array, sqft_living : a column.

In the line I'm adding a new column 'log_sqft_living' which should contain log'sqft_living'

```<code>test_data['log_sqft_living'] = log(test_data['sqft_living'][i] for i in range(len(test_data)))
</code>```

After looking for similar message, I found answers that it should be a number that's why we have to format using float(x) but when I used it the error became argument should be a number of a string. Can someone explain to me why those errors occur?

When I try log(test_data['sqft_living'][1] (for a single number) I don't get an error.

Thank you

答:
You are applying the log function to a generator, but it only will accept a single value. Change the line to a list comprehension (to make it an explicit list) and move the log inside the comprehension so that you are applying it to each element:

```<code>test_data['log_sqft_living'] = [ log(test_data['sqft_living'][i]) for i in range(len(test_data)) ]
</code>```

Title: python 3 error: float is required

Body:
I didn't understand why I'm getting an error for this line of code:

test_data:  array, sqft_living : a column.

In the line I'm adding a new column 'log_sqft_living' which should contain log'sqft_living'

test_data['log_sqft_living'] = log(test_data['sqft_living'][i] for i in range(len(test_data)))

After looking for similar message, I found answers that it should be a number that's why we have to format using float(x) but when I used it the error became argument should be a number of a string. Can someone explain to me why those errors occur?

When I try log(test_data['sqft_living'][1] (for a single number) I don't get an error.

Thank you

Body:
You are applying the log function to a generator, but it only will accept a single value. Change the line to a list comprehension (to make it an explicit list) and move the log inside the comprehension so that you are applying it to each element:

test_data['log_sqft_living'] = [ log(test_data['sqft_living'][i]) for i in range(len(test_data)) ]


问:
How to turn off Ripple Animation on Tabs [Android]?
How do I turn Off Ripple Animation only for the Tabs ? I have tried to change this in the Config File

```<code> activator : "highlight"
</code>```

But that sets no highlight to all buttons.

I want to turn off Ripple Animation  just for Tabs ?

EDIT 1:

I wanted to remove the effect for the ion-tabs

```<code><ion-tabs>
 <ion-tab [root]="tab1Root" tabIcon="people"></ion-tab>
 <ion-tab [root]="tab2Root" tabIcon="paper"></ion-tab>
 <ion-tab [root]="tab3Root" tabIcon="settings"></ion-tab>
</ion-tabs>
</code>```

答:
You can do it as shown below inside the app.module.ts file.

Globally

app.module.ts

```<code> IonicModule.forRoot(MyApp, {
    platforms: {
      android: {
        activator: 'none'
     }
  }
}
</code>```

Only for ion-tab:

You have to deal with CSS hack here on page component.No framework-level support for this.

.html

```<code><ion-tabs>
 <ion-tab [root]="tab1Root" tabIcon="people" class="disable-ripple"></ion-tab>
 <ion-tab [root]="tab2Root" tabIcon="paper" class="disable-ripple"></ion-tab>
 <ion-tab [root]="tab3Root" tabIcon="settings" class="disable-ripple"></ion-tab>
</ion-tabs>
</code>```

.scss

```<code>.ios,
.md,
.wp {
    .disable-ripple ion-tab-effect {
       display: none;
    }
}
</code>```

Body:
How do I turn Off Ripple Animation only for the Tabs ? I have tried to change this in the Config File

 activator : "highlight"

But that sets no highlight to all buttons.

I want to turn off Ripple Animation  just for Tabs ?

EDIT 1:

I wanted to remove the effect for the ion-tabs

<ion-tabs>
 <ion-tab [root]="tab1Root" tabIcon="people"></ion-tab>
 <ion-tab [root]="tab2Root" tabIcon="paper"></ion-tab>
 <ion-tab [root]="tab3Root" tabIcon="settings"></ion-tab>
</ion-tabs>

Body:
You can do it as shown below inside the app.module.ts file.

Globally

app.module.ts

 IonicModule.forRoot(MyApp, {
    platforms: {
      android: {
        activator: 'none'
     }
  }
}

Only for ion-tab:

You have to deal with CSS hack here on page component.No framework-level support for this.

.html

<ion-tabs>
 <ion-tab [root]="tab1Root" tabIcon="people" class="disable-ripple"></ion-tab>
 <ion-tab [root]="tab2Root" tabIcon="paper" class="disable-ripple"></ion-tab>
 <ion-tab [root]="tab3Root" tabIcon="settings" class="disable-ripple"></ion-tab>
</ion-tabs>

.scss

.ios,
.md,
.wp {
    .disable-ripple ion-tab-effect {
       display: none;
    }
}


问:
bootstrap error ios simulator
I tried to launch my project, but i got this error while compiling it on the simulator.WorkOut is the name of my project.

Couldn't register com.AE557593PG.WorkOut with the bootstrap server. Error: unknown error code.

答: Try making sure the app isn't running on the simulator already. Worst case scenario, quit and restart both Simulator and Xcode. That's always fixed this for me. </p>

Title: bootstrap error ios simulator


问:
inline assembler in gives c2400 in vs 2015
try to implement a basic operating system but this asm stuff is messing with my head i am using vs2015

the code that gives error

```<code>inline cpu_flags DisableInterrupts()

{
cpu_flags fl;

_asm volatile ("pushfl; popl %0; cli" : "=g" (fl));

return fl;
}
</code>```

it gives error like this

Error    C2400   inline assembler syntax error in 'opcode'; found 'data type'

after removing volatile also no luck

```<code>inline cpu_flags DisableInterrupts()
 {

 cpu_flags fl;

_asm ("pushfl; popl %0; cli" : "=g" (fl));

return fl;`
}
</code>```

it gives

Error   C2400   inline assembler syntax error in 'opcode'; found '('

thank you

答:
There are many different compilers in the world, and they all work a bit differently.

The syntax you are using in your question comes from gcc made by gnu.

However, you say you are trying to use it with Visual Studio which is made by Microsoft.  Visual Studio uses a very different syntax for inline asm than gcc.

I'm not going to try to teach you everything about Visual Studio's inline asm.  See their docs.

Body:
try to implement a basic operating system but this asm stuff is messing with my head i am using vs2015

the code that gives error

inline cpu_flags DisableInterrupts()

{
cpu_flags fl;

_asm volatile ("pushfl; popl %0; cli" : "=g" (fl));

return fl;
}

it gives error like this

Error    C2400   inline assembler syntax error in 'opcode'; found 'data type'

after removing volatile also no luck

inline cpu_flags DisableInterrupts()
 {

 cpu_flags fl;

_asm ("pushfl; popl %0; cli" : "=g" (fl));

return fl;`
}

it gives

Error   C2400   inline assembler syntax error in 'opcode'; found '('

thank you


答:
<expression> for <variable> in <data set> - is list comprehension,
you can read more about list comprehension here: http://treyhunner.com/2015/12/python-list-comprehensions-now-in-color/

What this means, it that it produces a list structure - while the function log expects to get a number. math.log(x[, base])

You can maybe restructure your statement like this:
test_data['log_sqft_living'] = [log(test_data['sqft_living'][i]) for i in range(len(test_data))]

Note: test_data['log_sqft_living'] will contain a list with this example

As you provided no info about the context and what you want to achieve I can't provide a better solution

Title: python 3 error: float is required


问:
Prevent MatLab nesting variables when saving/loading?
I have a variable called sources that contains eight numbers:

```<code>sources =

    0.6028
    0.7112
    0.2217
    0.1174
    0.2967
    0.3188
    0.4242
    0.5079
</code>```

I save it using save('sources.mat', 'sources'); and then load it again using sources = load('sources.mat');

However it is no longer just an array of eight numbers, the sources variable is now:

```<code>sources =

    sources: [8x1 double]
</code>```

Is there any way to get rid of this nesting when saving/loading? It's hassle having to always retrieve the nested variables after loading them. When I use sources = load('sources.mat'); I would like to get back

```<code>sources =

    0.6028
    0.7112
    0.2217
    0.1174
    0.2967
    0.3188
    0.4242
    0.5079
</code>```

Can this be done?

答:
in the simplest scenario as the one you show us, you can create an inline function that extracts your data:

```<code>loadAndExtract = @(varname) arrayfun(@(x) x.(varname), load(varname));
</code>```

now you can just load your data as a matrix:

```<code>sources = loadAndExtract('sources.mat'); % load and extract data
</code>```

The drawback of this approach is that you are forced to match name of the file and name of the variable. If this is a problem for you you can make the function slightly more complex:

```<code>loadAndExtract = @(dataName,varname) arrayfun(@(x) x.(varname), load(dataName));
</code>```

now if you load your data with a specific name:

```<code>save('mySources','sources');
</code>```

you can still load it by specifying the name of the variable and name of the file.

```<code>sources = loadAndExtract('mySources','sources');
</code>```

In principle you can write the function to extract multiple data from the same file, but then the inline function gets more and more complex and I would suggest to write is as a separate function.

Body:
I have a variable called sources that contains eight numbers:

sources =

    0.6028
    0.7112
    0.2217
    0.1174
    0.2967
    0.3188
    0.4242
    0.5079

I save it using save('sources.mat', 'sources'); and then load it again using sources = load('sources.mat');

However it is no longer just an array of eight numbers, the sources variable is now:

sources =

    sources: [8x1 double]

Is there any way to get rid of this nesting when saving/loading? It's hassle having to always retrieve the nested variables after loading them. When I use sources = load('sources.mat'); I would like to get back

sources =

    0.6028
    0.7112
    0.2217
    0.1174
    0.2967
    0.3188
    0.4242
    0.5079

Can this be done?

Body:
in the simplest scenario as the one you show us, you can create an inline function that extracts your data:

loadAndExtract = @(varname) arrayfun(@(x) x.(varname), load(varname));

now you can just load your data as a matrix:

sources = loadAndExtract('sources.mat'); % load and extract data

The drawback of this approach is that you are forced to match name of the file and name of the variable. If this is a problem for you you can make the function slightly more complex:

loadAndExtract = @(dataName,varname) arrayfun(@(x) x.(varname), load(dataName));

now if you load your data with a specific name:

save('mySources','sources');

you can still load it by specifying the name of the variable and name of the file.

sources = loadAndExtract('mySources','sources');

In principle you can write the function to extract multiple data from the same file, but then the inline function gets more and more complex and I would suggest to write is as a separate function.


问:
Tesserocr did not recognize text
I want to ask for suggestion on how to solve the problem of tesserocr did not recognize certain line from an image.

This is the image. source is from Simple Digit Recognition OCR in OpenCV-Python

The code

```<code>from PIL import Image
from tesserocr import PyTessBaseAPI, RIL

image = Image.open('test3.png')
with PyTessBaseAPI() as api:
    api.SetImage(image)
    boxes = api.GetComponentImages(RIL.TEXTLINE, True)
    print 'Found {} textline image components.'.format(len(boxes))
    for i, (im, box, _, _) in enumerate(boxes):
        api.SetRectangle(box['x'], box['y'], box['w'], box['h'])
        ocrResult = api.GetUTF8Text()
        conf = api.MeanTextConf()
        result = (u"Box[{0}]: x={x}, y={y}, w={w}, h={h}, "
            "confidence: {1}, text: {2}").format(i, conf, ocrResult, **box)

    print result
</code>```

The result is like this

```<code>Found 5 textline image components.
Box[0]: x=10, y=5, w=582, h=29, confidence: 81, text: 9821480865132823066470938

Box[1]: x=9, y=55, w=581, h=30, confidence: 91, text: 4460955058223172535940812

Box[2]: x=10, y=106, w=575, h=30, confidence: 90, text: 8481117450284102701938521

Box[3]: x=12, y=157, w=580, h=30, confidence: 0, text:
Box[4]: x=11, y=208, w=581, h=30, confidence: 89, text: 6442881097566593344612847
</code>```

It did not recognize the number in box 3. What should I add or modify the script so the box 3 will show the proper result?

Thank you for your help.

答:
Have come out below code with correct OCR result but without x,y,w,h and confidence info.

```<code>import tesserocr
from PIL import Image

print tesserocr.tesseract_version()  # print tesseract-ocr version

image = Image.open('SO_5TextLines.png')

lines = tesserocr.image_to_text(image)  # print ocr text from image
for line in lines.split("\r"):
    print line
</code>```

Output:

```<code>tesseract 3.05.00
 leptonica-1.74.1
  libjpeg 8d : libpng 1.6.27 : libtiff 4.0.6 : zlib 1.2.8 : libopenjp2 2.1.2

9821480865132823066470938
4460955058223172535940812
8481117450284102701938521
1055596446229489549303819
6442881097566593344612847
</code>```

Have run your code in OSX Sierra and got the same result with line 4 missed. It looks like the problem is caused in api.SetRectangle(), you may modify your code to print boxes to further check. The sample code is just based on the sample text image you provided, it needs to test with more images to verify if it fits all.

Hope this works for you.

Title: Tesserocr did not recognize text

Body:
I want to ask for suggestion on how to solve the problem of tesserocr did not recognize certain line from an image.

This is the image. source is from Simple Digit Recognition OCR in OpenCV-Python

The code

from PIL import Image
from tesserocr import PyTessBaseAPI, RIL

image = Image.open('test3.png')
with PyTessBaseAPI() as api:
    api.SetImage(image)
    boxes = api.GetComponentImages(RIL.TEXTLINE, True)
    print 'Found {} textline image components.'.format(len(boxes))
    for i, (im, box, _, _) in enumerate(boxes):
        api.SetRectangle(box['x'], box['y'], box['w'], box['h'])
        ocrResult = api.GetUTF8Text()
        conf = api.MeanTextConf()
        result = (u"Box[{0}]: x={x}, y={y}, w={w}, h={h}, "
            "confidence: {1}, text: {2}").format(i, conf, ocrResult, **box)

    print result

The result is like this

Found 5 textline image components.
Box[0]: x=10, y=5, w=582, h=29, confidence: 81, text: 9821480865132823066470938

Box[1]: x=9, y=55, w=581, h=30, confidence: 91, text: 4460955058223172535940812

Box[2]: x=10, y=106, w=575, h=30, confidence: 90, text: 8481117450284102701938521

Box[3]: x=12, y=157, w=580, h=30, confidence: 0, text:
Box[4]: x=11, y=208, w=581, h=30, confidence: 89, text: 6442881097566593344612847

It did not recognize the number in box 3. What should I add or modify the script so the box 3 will show the proper result?

Thank you for your help.

Body:
Have come out below code with correct OCR result but without x,y,w,h and confidence info.

import tesserocr
from PIL import Image

print tesserocr.tesseract_version()  # print tesseract-ocr version

image = Image.open('SO_5TextLines.png')

lines = tesserocr.image_to_text(image)  # print ocr text from image
for line in lines.split("\r"):
    print line

Output:

tesseract 3.05.00
 leptonica-1.74.1
  libjpeg 8d : libpng 1.6.27 : libtiff 4.0.6 : zlib 1.2.8 : libopenjp2 2.1.2

9821480865132823066470938
4460955058223172535940812
8481117450284102701938521
1055596446229489549303819
6442881097566593344612847

Have run your code in OSX Sierra and got the same result with line 4 missed. It looks like the problem is caused in api.SetRectangle(), you may modify your code to print boxes to further check. The sample code is just based on the sample text image you provided, it needs to test with more images to verify if it fits all.

Hope this works for you.


问:
Kotlin: Blocking coroutines with non-blocking I/O
I'm trying to use Kotlin coroutines to handle a non-blocking I/O. Scenario is as follows:

Receive data from an asynchronous callback running on thread 1.

Wait for this data in thread 2 then consume it.

My current code looks like this (simplified for sake of brevity):

```<code>private var latch = CountDownLatch(1)
private var data: Any? = null

// Async callback from non-blocking I/O
fun onReceive(data: Any) {
    currentData = data
    latch.countDown()
}

// Wait and consume data
fun getData(): Any? {
    latch.await()
    latch = CountDownLatch(1)
    return currentData
}

fun processData() {
    launch(CommonPool) {
        while (true) {
            val data = getData()
            // Consume data
        }
    }
}
</code>```

From what I understand, Kotlin coroutines should be able to help me to get rid of CountDownLatch. After reading this (awesome) guide, all I could come up with is something like this:

```<code>// Wait and consume data
fun getData() = async(CommonPool) {
    latch.await()
    latch = CountDownLatch(1)
    currentData
}

fun processData() {
    launch(CommonPool) {
        while (true) {
            runBlocking {
                val data = getData().await()
                // Consume data
            }
        }
    }
}
</code>```

I also tried with Pipelines, with similar results. I'm obviously not understanding how to use these features.

答:
you did not said if data received in onReceive() can be processed in parallel. This is the main question. If yes, you can just do it in onReceive(). If this is not allowed, let each call to onReceive() start a task on CommonPool, without any coroutines. If they should be processed sequentially, then simplest way is to start a thread with a loop inside:

```<code>fun onReceive(data: Any) {
   queue.put(data);
}

 ....

// loop in a thread
while(true) {
   data = queue.take();
   processData(data);
}
</code>```

Again, coroutines are not needed.

Generally, coroutines are syntactic sugar to represent an asynchronous program as if it is synchronous. I do not think your program as a case to use coroutines.

Body:
I'm trying to use Kotlin coroutines to handle a non-blocking I/O. Scenario is as follows:

Receive data from an asynchronous callback running on thread 1.

Wait for this data in thread 2 then consume it.

My current code looks like this (simplified for sake of brevity):

private var latch = CountDownLatch(1)
private var data: Any? = null

// Async callback from non-blocking I/O
fun onReceive(data: Any) {
    currentData = data
    latch.countDown()
}

// Wait and consume data
fun getData(): Any? {
    latch.await()
    latch = CountDownLatch(1)
    return currentData
}

fun processData() {
    launch(CommonPool) {
        while (true) {
            val data = getData()
            // Consume data
        }
    }
}

From what I understand, Kotlin coroutines should be able to help me to get rid of CountDownLatch. After reading this (awesome) guide, all I could come up with is something like this:

// Wait and consume data
fun getData() = async(CommonPool) {
    latch.await()
    latch = CountDownLatch(1)
    currentData
}

fun processData() {
    launch(CommonPool) {
        while (true) {
            runBlocking {
                val data = getData().await()
                // Consume data
            }
        }
    }
}

I also tried with Pipelines, with similar results. I'm obviously not understanding how to use these features.

Body:
you did not said if data received in onReceive() can be processed in parallel. This is the main question. If yes, you can just do it in onReceive(). If this is not allowed, let each call to onReceive() start a task on CommonPool, without any coroutines. If they should be processed sequentially, then simplest way is to start a thread with a loop inside:

fun onReceive(data: Any) {
   queue.put(data);
}

 ....

// loop in a thread
while(true) {
   data = queue.take();
   processData(data);
}

Again, coroutines are not needed.

Generally, coroutines are syntactic sugar to represent an asynchronous program as if it is synchronous. I do not think your program as a case to use coroutines.


问:
querying over multiple data from function in PostgreSQL
I have a function which gives stock levels:

```<code>select * from stocklevel(ID)
</code>```

This function gives stock leverl per ID.
For example:

```<code>select * from stocklevel(23)
</code>```

Result is:

```<code>   ID  datelevel  stocklevel
   23   01.01.17   15
   23   02.01.17   18
   23   05.01.17   20
</code>```

This is the stock level for ID=23.

Not all dates appear, it depends on many things.

I want to use this function to get the stock levels for all parts from my system

basically something like this:

```<code>select *,(select stocklevel from stocklevel(parts.partid) where datelevel = ??? )
from parts
</code>```

OR:

```<code>  select *
  from parts
  left join ( select stocklevel from stocklevel(parts.partid) where datelevel = ??? ) using (ID)
</code>```

Now, the issue is with the WHERE condition I want to specific a specific date like '04.01.17' but if the date does not exist i want it to take the date before that so:

for the ID=23 and date '04.01.17' it should show 18,'02.01.17' .

for the ID=23 and date '15.01.13' it should show nothing.

for the ID=23 and date '05.01.17' it should show 20,'05.01.17' .

How can I do that?

答:
First, I would use a lateral join:

```<code>select *
from parts p left join lateral
     stocklevel(p.partid);
</code>```

Then the issue is that you want the most recent level before or on a given date.  You can do this using distinct on:

```<code>select distinct on (p.id) . . .
from parts p left join lateral
     stocklevel(p.partid)
where datelevel <= ?
order by p.id, datelevel desc;
</code>```

Note:  This will not return parts that have no dates before the given date.  You might want:

```<code>where datelevel is null or datelevel <= ?
</code>```

Body:
I have a function which gives stock levels:

select * from stocklevel(ID)

This function gives stock leverl per ID.
For example:

select * from stocklevel(23)

Result is:

   ID  datelevel  stocklevel
   23   01.01.17   15
   23   02.01.17   18
   23   05.01.17   20

This is the stock level for ID=23.

Not all dates appear, it depends on many things.

I want to use this function to get the stock levels for all parts from my system

basically something like this:

select *,(select stocklevel from stocklevel(parts.partid) where datelevel = ??? )
from parts

OR:

  select *
  from parts
  left join ( select stocklevel from stocklevel(parts.partid) where datelevel = ??? ) using (ID)

Now, the issue is with the WHERE condition I want to specific a specific date like '04.01.17' but if the date does not exist i want it to take the date before that so:

for the ID=23 and date '04.01.17' it should show 18,'02.01.17' .

for the ID=23 and date '15.01.13' it should show nothing.

for the ID=23 and date '05.01.17' it should show 20,'05.01.17' .

How can I do that?

Body:
First, I would use a lateral join:

select *
from parts p left join lateral
     stocklevel(p.partid);

Then the issue is that you want the most recent level before or on a given date.  You can do this using distinct on:

select distinct on (p.id) . . .
from parts p left join lateral
     stocklevel(p.partid)
where datelevel <= ?
order by p.id, datelevel desc;

Note:  This will not return parts that have no dates before the given date.  You might want:

where datelevel is null or datelevel <= ?


问:
Having trouble loading jquery into WordPress using many methods
I've now tried several methods to load jquery into wordpress and can't get anything to work. I've tried injecting code directly into wp-config.php, tried using the Use Google Libraries plugin and tried different code in my functions.php file and nothing will work. I've even tried adding jquery directly via cdn to my header and footer files and neither works.

Can anyone think of anything else I can try to get it to work or does anyone have any idea what might be causing this issue?

functions.php:

```<code><?php

function wpb_custom_new_menu() {
    register_nav_menu('my-custom-menu',__( 'My Custom Menu' ));
}

add_action( 'init', 'wpb_custom_new_menu' );

function enqueue_stylesheets() {

    //For registering Styles

    wp_enqueue_style('style', get_stylesheet_directory_uri() . '/css/style.css');

    wp_enqueue_style('fonts', 'https://fonts.googleapis.com/css?family=Open+Sans:400,600,700|Raleway:400,500,600,700,900');

    wp_enqueue_style('fontAwesome', 'https://maxcdn.bootstrapcdn.com/font-awesome/4.6.3/css/font-awesome.min.css');

    wp_enqueue_style('bootstrapCSS', 'https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css');

    //For registering Scripts files
    wp_enqueue_script( 'bootstrapJS', 'https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/js/bootstrap.min.js', array('jquery'), '3.3.4', true );

    wp_register_script('navbarScroll', get_stylesheet_directory_uri() . '/js/navbarScroll.js', array( 'jquery' ), '', true );

    wp_enqueue_script('navbarScroll');

    wp_register_script( 'navbarScroll', get_template_directory_uri() . '/js/jquery.navbarScroll.js', array( 'jquery' ), '', true );

    wp_enqueue_script( 'navbarScroll' );
}

add_action( 'wp_enqueue_scripts', 'enqueue_stylesheets' );
</code>```

答:
In functions.php :

```<code>function enqueue_scripts() {
    wp_deregister_script('jquery');
    wp_register_script('jquery', '//ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js', false, '1.11.2');
    wp_enqueue_script('jquery');
}
add_action( 'wp_enqueue_scripts', 'enqueue_scripts' );
</code>```

Hope this will help you.

Body:
I've now tried several methods to load jquery into wordpress and can't get anything to work. I've tried injecting code directly into wp-config.php, tried using the Use Google Libraries plugin and tried different code in my functions.php file and nothing will work. I've even tried adding jquery directly via cdn to my header and footer files and neither works.

Can anyone think of anything else I can try to get it to work or does anyone have any idea what might be causing this issue?

functions.php:

<?php

function wpb_custom_new_menu() {
    register_nav_menu('my-custom-menu',__( 'My Custom Menu' ));
}

add_action( 'init', 'wpb_custom_new_menu' );

function enqueue_stylesheets() {

    //For registering Styles

    wp_enqueue_style('style', get_stylesheet_directory_uri() . '/css/style.css');

    wp_enqueue_style('fonts', 'https://fonts.googleapis.com/css?family=Open+Sans:400,600,700|Raleway:400,500,600,700,900');

    wp_enqueue_style('fontAwesome', 'https://maxcdn.bootstrapcdn.com/font-awesome/4.6.3/css/font-awesome.min.css');

    wp_enqueue_style('bootstrapCSS', 'https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css');

    //For registering Scripts files
    wp_enqueue_script( 'bootstrapJS', 'https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/js/bootstrap.min.js', array('jquery'), '3.3.4', true );

    wp_register_script('navbarScroll', get_stylesheet_directory_uri() . '/js/navbarScroll.js', array( 'jquery' ), '', true );

    wp_enqueue_script('navbarScroll');

    wp_register_script( 'navbarScroll', get_template_directory_uri() . '/js/jquery.navbarScroll.js', array( 'jquery' ), '', true );

    wp_enqueue_script( 'navbarScroll' );
}

add_action( 'wp_enqueue_scripts', 'enqueue_stylesheets' );

Body:
In functions.php :

function enqueue_scripts() {
    wp_deregister_script('jquery');
    wp_register_script('jquery', '//ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js', false, '1.11.2');
    wp_enqueue_script('jquery');
}
add_action( 'wp_enqueue_scripts', 'enqueue_scripts' );

Hope this will help you.


问:
Pocketsphinx: App doesnt start
i got a problem with PocketSphinx, whenever i execute that Code, the app automatically shuts down. As i already try to figure out why it doesnt work for hours , maybe someone can help me? :)
so far the code looks like this,

Main:

```<code>public class MainActivity extends Activity implements RecognitionListener {

    public SpeechRecognizer recognizer;

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

        try
        {
            Assets assets = new Assets(MainActivity.this);
            File assetDir = assets.syncAssets();
            setupRecognizer(assetDir);
        }
        catch (IOException e)
        {
        }

    }
</code>```

setupRecognizer:

```<code>private void setupRecognizer(File assetsDir)
    {

        try {
            recognizer = defaultSetup()
                    .setAcousticModel(new File(assetsDir, "en-us-ptm"))
                    .setDictionary(new File(assetsDir, "cmudict-en-us.dict"))
                    .setRawLogDir(assetsDir).setKeywordThreshold(1e-20f)
                    .setBoolean("-allphone_ci", true)
                    .getRecognizer();
            recognizer.addListener(this);
            recognizer.addKeyphraseSearch("keywordsearch", "oh mighty Computer");
            recognizer.startListening("keywordsearch");

        } catch (IOException e) {
        }
</code>```

onPartialResult:

```<code>public void onPartialResult(Hypothesis hyp) {

    if (hyp == null) {

    }
    TextView t = (TextView) findViewById(R.id.textviewcontrol);
    t.setText("found");
    recognizer.cancel();

}
</code>```

maybe it helps: so far the app starts (=>does nothing but showing a textview) when i comment those lines out:

```<code>            recognizer.addKeyphraseSearch("keywordsearch", "oh mighty Computer");
            recognizer.startListening("keywordsearch");
</code>```

when i only comment one of them out, it doesnt work.

so probably there is the mistake? I tried to import everything like in the tutorialcode for android, but i could also made a mistake there too.

thank you,

Jannis

答:
Remove "recognizer.cancel();" from onPartialResult method use it when your app is closing. </p>

```<code>public void onDestroy() {
        super.onDestroy();
        recognizer.cancel();
        recognizer.shutdown();
    }
</code>```

Title: Pocketsphinx: App doesnt start

Body:
i got a problem with PocketSphinx, whenever i execute that Code, the app automatically shuts down. As i already try to figure out why it doesnt work for hours , maybe someone can help me? :)
so far the code looks like this,

Main:

public class MainActivity extends Activity implements RecognitionListener {

    public SpeechRecognizer recognizer;

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

        try
        {
            Assets assets = new Assets(MainActivity.this);
            File assetDir = assets.syncAssets();
            setupRecognizer(assetDir);
        }
        catch (IOException e)
        {
        }

    }

setupRecognizer:

private void setupRecognizer(File assetsDir)
    {

        try {
            recognizer = defaultSetup()
                    .setAcousticModel(new File(assetsDir, "en-us-ptm"))
                    .setDictionary(new File(assetsDir, "cmudict-en-us.dict"))
                    .setRawLogDir(assetsDir).setKeywordThreshold(1e-20f)
                    .setBoolean("-allphone_ci", true)
                    .getRecognizer();
            recognizer.addListener(this);
            recognizer.addKeyphraseSearch("keywordsearch", "oh mighty Computer");
            recognizer.startListening("keywordsearch");

        } catch (IOException e) {
        }

onPartialResult:

public void onPartialResult(Hypothesis hyp) {

    if (hyp == null) {

    }
    TextView t = (TextView) findViewById(R.id.textviewcontrol);
    t.setText("found");
    recognizer.cancel();

}

maybe it helps: so far the app starts (=>does nothing but showing a textview) when i comment those lines out:

            recognizer.addKeyphraseSearch("keywordsearch", "oh mighty Computer");
            recognizer.startListening("keywordsearch");

when i only comment one of them out, it doesnt work.

so probably there is the mistake? I tried to import everything like in the tutorialcode for android, but i could also made a mistake there too.

thank you,

Jannis

Body:
Remove "recognizer.cancel();" from onPartialResult method use it when your app is closing.

public void onDestroy() {
        super.onDestroy();
        recognizer.cancel();
        recognizer.shutdown();
    }


问:
Separating Divs

I am trying to separate this 2 divs with a space between them (Please see Picture 1).
The problem is when I add margin or padding this happens (Please see Picture 2).

Here is my code, Please take note I am not using Bootstrap:

.row {
  margin-left: -0.75rem !important;
  margin-right: -0.75rem !important;
}

.col-50 {
  width: 50%;
  float: left;
  position: relative;
  min-height: 1px;
  margin-left: 0.75rem !important;
  margin-right: 0.75rem !important;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="row">
  <div class="col-50">
    <div class="card-box">
      <h4 class="header-title">View Data</h4>
      <div class="table-container">
        <div class="row">
          <div class="col-50">
            <div class="btn-group">
              <span>Excel</span>
              <span>PDF</span>
            </div>
          </div>
          <div class="col-50">
            <form class="pull-right">
              <input type="text" placeholder="Search..." class="form-control">
              <span><i class="fa fa-search"></i></span>
            </form>
          </div>
        </div>
        <div class="row">
          <div class="col-100">

          </div>
        </div>
      </div>
    </div>
  </div>
  <div class="col-50">
    <div class="card-box">
      <h4 class="header-title">View Data</h4>
      <div class="table-container">
        <div class="row">
          <div class="col-50">
            <div class="btn-group">
              <span>Excel</span>
              <span>PDF</span>
            </div>
          </div>
          <div class="col-50">
            <form class="pull-right">
              <input type="text" placeholder="Search..." class="form-control">
              <span><i class="fa fa-search"></i></span>
            </form>
          </div>
        </div>
        <div class="row">
          <div class="col-100">

          </div>
        </div>
      </div>
    </div>
  </div>
</div></code>```

Here is my HTML and CSS code. I am trying to make this work for days. Please help. I want to separate these 2 divs with equal space between them perfectly. I am trying to mimic the grid from Bootstrap in order to learn before I try the Bootstrap approach.

答:
I would use flexbox to achieve the same results. Or if you aim only to modern browsers, use the newest grid properties.

.row {
  background-color: red;
  display: flex;
  flex: 2 0 50% 50%;
  width: 100%;
}

.card-box {
  width: 100%;
}

.col-50 {
  background-color: yellow;
  display: flex;
  flex: 2 0 50% 50%;
  width: 100%;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="row">
  <div class="col-50">
    <div class="card-box">
      <h4 class="header-title">View Data</h4>
      <div class="table-container">
        <div class="row">
          <div class="col-50">
            <div class="btn-group">
              <span>Excel</span>
              <span>PDF</span>
            </div>
          </div>
          <div class="col-50">
            <form class="pull-right">
              <input type="text" placeholder="Search..." class="form-control">
              <span><i class="fa fa-search"></i></span>
            </form>
          </div>
        </div>
        <div class="row">
          <div class="col-100" />
        </div>
      </div>
    </div>
  </div>
  <div class="col-50">
    <div class="card-box">
      <h4 class="header-title">View Data</h4>
      <div class="table-container">
        <div class="row">
          <div class="col-50">
            <div class="btn-group">
              <span>Excel</span>
              <span>PDF</span>
            </div>
          </div>
          <div class="col-50">
            <form class="pull-right">
              <input type="text" placeholder="Search..." class="form-control">
              <span><i class="fa fa-search"></i></span>
            </form>
          </div>
        </div>
        <div class="row">
          <div class="col-100" />
        </div>
      </div>
    </div>
  </div>
</div></code>```

Title: Separating Divs

Body:
I am trying to separate this 2 divs with a space between them (Please see Picture 1).
The problem is when I add margin or padding this happens (Please see Picture 2).

Here is my code, Please take note I am not using Bootstrap:

.row {
  margin-left: -0.75rem !important;
  margin-right: -0.75rem !important;
}

.col-50 {
  width: 50%;
  float: left;
  position: relative;
  min-height: 1px;
  margin-left: 0.75rem !important;
  margin-right: 0.75rem !important;
}

View Data

              Excel
              PDF

            <form class="pull-right">
              <input type="text" placeholder="Search..." class="form-control">

            </form>

View Data

              Excel
              PDF

            <form class="pull-right">
              <input type="text" placeholder="Search..." class="form-control">

            </form>

Here is my HTML and CSS code. I am trying to make this work for days. Please help. I want to separate these 2 divs with equal space between them perfectly. I am trying to mimic the grid from Bootstrap in order to learn before I try the Bootstrap approach.

Body:
I would use flexbox to achieve the same results. Or if you aim only to modern browsers, use the newest grid properties.

.row {
  background-color: red;
  display: flex;
  flex: 2 0 50% 50%;
  width: 100%;
}

.card-box {
  width: 100%;
}

.col-50 {
  background-color: yellow;
  display: flex;
  flex: 2 0 50% 50%;
  width: 100%;
}

<div class="row">
  <div class="col-50">
    <div class="card-box">
      <h4 class="header-title">View Data</h4>
      <div class="table-container">
        <div class="row">
          <div class="col-50">
            <div class="btn-group">
              <a class="btn-excel" href="#"><span>Excel</span></a>
              <a class="btn-pdf" href="#"><span>PDF</span></a>
            </div>
          </div>
          <div class="col-50">
            <form class="pull-right">
              <input type="text" placeholder="Search..." class="form-control">
              <span><i class="fa fa-search"></i></span>
            </form>
          </div>
        </div>
        <div class="row">
          <div class="col-100" />
        </div>
      </div>
    </div>
  </div>
  <div class="col-50">
    <div class="card-box">
      <h4 class="header-title">View Data</h4>
      <div class="table-container">
        <div class="row">
          <div class="col-50">
            <div class="btn-group">
              <a class="btn-excel" href="#"><span>Excel</span></a>
              <a class="btn-pdf" href="#"><span>PDF</span></a>
            </div>
          </div>
          <div class="col-50">
            <form class="pull-right">
              <input type="text" placeholder="Search..." class="form-control">
              <span><i class="fa fa-search"></i></span>
            </form>
          </div>
        </div>
        <div class="row">
          <div class="col-100" />
        </div>
      </div>
    </div>
  </div>
</div>


答:
```<code><?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.nulledapps.website2app">

    <uses-permission android:name="android.permission.INTERNET" />

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity
            android:name=".SplashScreen"
            android:label="@string/app_name"
            android:theme="@style/AppTheme.NoActionBar">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity android:name=".MainActivity"></activity>
    </application>

</manifest>
</code>```

Title: splash screen not work with navigation drawer

Body:
navigation drawer is working perfect but when i added splash screen to my project it not work

splasScreen

manifest


问:
How to automate loading leiningen repl from within Emacs?
I'm using Emacs, integrated with Leiningen's swank. Each time I need to start working with .clj file I have to:

Run emacs pack/my-ns.clj from console.

Type M-x lein-swank.

Compile buffer.

In Clojure REPL change namespace, i.e. type (in-ns 'pack.my-ns).

How can I automate this process to just run from console something like emacs-clj pack/my-ns.clj and get my environment ready to use?

答: Swank should automatically load the namespace pointed to by :repl-init-script in project.clj when it starts, so if you want to set that to your starting namespace, that should get you started.</p>


问:
Using jint to decode Jsfuck
I'm trying to use jint to decode jsfuck, and am basing myself off this project: https://github.com/enkhee-Osiris/Decoder-JSFuck (it's the only one I've found that can decode the jsfuck correctly). The following c# isn't working correctly:

```<code>Jint.Engine engine = new Jint.Engine();
engine.SetValue("code", jsfuck_string);
string result = engine.Execute(@"function decode() {
return (/\n(.+)/.exec(eval(code.value.replace(/\s+/, "").slice(0, -2)))[1]);
}").GetValue("decode").ToString();
</code>```

I'm getting the following exception: Line 2: Unexpected token ILLEGAL

答:
It looks like you want to run the following JavaScript code in Jint:

```<code>function decode() {
    return (/\n(.+)/.exec(eval(code.value.replace(/\s+/, "").slice(0, -2)))[1]);
}
</code>```

However, "" in a C# verbatim string (i.e. @"...") represents only a single " character.  You're actually trying to run this JS code, which isn't valid as there is an unmatched " character:

```<code>function decode() {
    return (/\n(.+)/.exec(eval(code.value.replace(/\s+/, ").slice(0, -2)))[1]);
}
</code>```

Try replacing the "" in replace(/\s+/, "") in your C# verbatim string with """", or ''.

Title: Using jint to decode Jsfuck

Body:
I'm trying to use jint to decode jsfuck, and am basing myself off this project: https://github.com/enkhee-Osiris/Decoder-JSFuck (it's the only one I've found that can decode the jsfuck correctly). The following c# isn't working correctly:

Jint.Engine engine = new Jint.Engine();
engine.SetValue("code", jsfuck_string);
string result = engine.Execute(@"function decode() {
return (/\n(.+)/.exec(eval(code.value.replace(/\s+/, "").slice(0, -2)))[1]);
}").GetValue("decode").ToString();

I'm getting the following exception: Line 2: Unexpected token ILLEGAL

Body:
It looks like you want to run the following JavaScript code in Jint:

function decode() {
    return (/\n(.+)/.exec(eval(code.value.replace(/\s+/, "").slice(0, -2)))[1]);
}

However, "" in a C# verbatim string (i.e. @"...") represents only a single " character.  You're actually trying to run this JS code, which isn't valid as there is an unmatched " character:

function decode() {
    return (/\n(.+)/.exec(eval(code.value.replace(/\s+/, ").slice(0, -2)))[1]);
}

Try replacing the "" in replace(/\s+/, "") in your C# verbatim string with """", or ''.


问:
Name error in my code
Hey I've got a very simple problem, however all the places i look to fix it don't seem to work. So for school we gotta do this thing where we save user input to an excel file and where i do Mylist.append(phone) i get an error saying phone is not defined. Any idea on how to fix this?</p>

```<code>#Zacharriah Task 3
import csv
from IPhone import*
from Android import*
import time

def start():
    print('Hello Welcome to the Phone Trouble-Shooter')
    time.sleep(2)
    phone = input('Please input what brand of phone you have')
    if "iphone" in phone:
        print('Your phone has been identified as an Iphone')
    elif "android" in phone:
        print('Your phone has been identifies as an Android')

file = open("Excel_Task_3.csv", "w", newline = "")
fileWrite = csv.writer(file,delimiter = ",")
Mylist = []

Mylist.append(phone)

fileWriter.writerow(Mylist)

file.close()
</code>```

答:
If code is exactly like posted then phone is really not defined where you need it. It is defined in the function's scope but is used outside - so there is no phone variable defined there:

```<code>def start():
    # defined in the function's scope
    phone = input('Please input what brand of phone you have')
    # rest of code

file = open("Excel_Task_3.csv", "w", newline = "")
fileWrite = csv.writer(file,delimiter = ",")
Mylist = []
# Used outside of the function's scope - it is unrecognized here
Mylist.append(phone)
</code>```

What you can do is return a value from start and then use it. Something like:

```<code>def start():
    phone = input('Please input what brand of phone you have')
    # rest of code
    return phone

# rest of code
Mylist = []
Mylist.append(start())
</code>```

Read Short Description of Python Scoping Rules

Title: Name error in my code

Body:
Hey I've got a very simple problem, however all the places i look to fix it don't seem to work. So for school we gotta do this thing where we save user input to an excel file and where i do Mylist.append(phone) i get an error saying phone is not defined. Any idea on how to fix this?

#Zacharriah Task 3
import csv
from IPhone import*
from Android import*
import time

def start():
    print('Hello Welcome to the Phone Trouble-Shooter')
    time.sleep(2)
    phone = input('Please input what brand of phone you have')
    if "iphone" in phone:
        print('Your phone has been identified as an Iphone')
    elif "android" in phone:
        print('Your phone has been identifies as an Android')

file = open("Excel_Task_3.csv", "w", newline = "")
fileWrite = csv.writer(file,delimiter = ",")
Mylist = []

Mylist.append(phone)

fileWriter.writerow(Mylist)

file.close()

Body:
If code is exactly like posted then phone is really not defined where you need it. It is defined in the function's scope but is used outside - so there is no phone variable defined there:

def start():
    # defined in the function's scope
    phone = input('Please input what brand of phone you have')
    # rest of code

file = open("Excel_Task_3.csv", "w", newline = "")
fileWrite = csv.writer(file,delimiter = ",")
Mylist = []
# Used outside of the function's scope - it is unrecognized here
Mylist.append(phone)

What you can do is return a value from start and then use it. Something like:

def start():
    phone = input('Please input what brand of phone you have')
    # rest of code
    return phone

# rest of code
Mylist = []
Mylist.append(start())

Read Short Description of Python Scoping Rules


问:
SpriteKit Nodes appear smaller in iPhone 6 plus and iPhone 6s plus simulator
In iPhone 6 Plus and 6s Plus simulator, the nodes in my GameScene look much smaller than how they're supposed to do (even though the screen fits perfectly - no black bars, empty space, ...).  Strangely, the nodes in my MenuScene and my TutorialScene (in the same simulator) are all normal-sized. My app runs perfectly (with normal-sized nodes in all Scenes) on all other simulators (iPad air, iPad pro, iPhone 5,5s,6,6s).
P
I've tried the following things:

I create launch images for all sizes --> in App Icons and Launch Images, I migrate launch images to an asset catalog --> delete the line in the "launch screen file" --> doesn't work

I tried the same thing above but this time I deleted the Launch Screen.storyboard (if I have created launch images for all iPhone sizes, why would I need this?)  --> doesn't work

I delete my launch images and restore launch screen.storyboard (basically reset everything) --> doesn't work

What is wrong with my iPhone 6 Plus and iPhone 6s Plus simulator?

答:
UPDATE: Problem solved! (but I still don't know how)

After testing my app on all simulators, I found out that the only devices in which my nodes appear smaller are iPhone 6+ and 6s+. These devices use 3x images. So I figured there's something wrong with my 3x images.

After checking, I didn't find anything wrong with those images (they were the exact same images as the 1x and 2x ones, except their names has the @3x suffix).

So I deleted all 3x images in my images.xcassets  --> problem solved

I still want to know how this solved my problem though. Please comment if you can explain it :)


答:
add *{ box-sizing: border-box; } in your,  remove negative margin for row and use padding instead of margin for .col-50

.col-50 {
width: calc(50% - 1.5rem);
float: left;
position: relative;
min-height: 1px;
padding-left: 0.75rem !important;
padding-right: 0.75rem !important;
margin:0 0.75rem;
background:green
}

.row {
margin-left: -0.75rem !important;
margin-right: -0.75rem !important;}

*{
  box-sizing: border-box;
}
input{
  width:100%
}
/*.col-50:first-child{
  margin-left:0
}
.col-50:last-child{
  margin-right:0
}*/```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="row">
    <div class="col-50">
        <div class="card-box">
            <h4 class="header-title">View Data</h4>
            <div class="table-container">
                <div class="row">
                    <div class="col-50">
                        <div class="btn-group"> <span>Excel</span> <span>PDF</span> </div>
                    </div>
                    <div class="col-50">
                        <form class="pull-right">
                            <input type="text" placeholder="Search..." class="form-control"> <span><i class="fa fa-search"></i></span> </form>
                    </div>
                </div>
                <div class="row">
                    <div class="col-100"> </div>
                </div>
            </div>
        </div>
    </div>
    <div class="col-50">
        <div class="card-box">
            <h4 class="header-title">View Data</h4>
            <div class="table-container">
                <div class="row">
                    <div class="col-50">
                        <div class="btn-group"> <span>Excel</span> <span>PDF</span> </div>
                    </div>
                    <div class="col-50">
                        <form class="pull-right">
                            <input type="text" placeholder="Search..." class="form-control"> <span><i class="fa fa-search"></i></span> </form>
                    </div>
                </div>
                <div class="row">
                    <div class="col-100"> </div>
                </div>
            </div>
        </div>
    </div>
</div></code>```

Title: Separating Divs

Body:
add *{ box-sizing: border-box; } in your,  remove negative margin for row and use padding instead of margin for .col-50

.col-50 {
width: calc(50% - 1.5rem);
float: left;
position: relative;
min-height: 1px;
padding-left: 0.75rem !important;
padding-right: 0.75rem !important;
margin:0 0.75rem;
background:green
}

.row {
margin-left: -0.75rem !important;
margin-right: -0.75rem !important;}

*{
  box-sizing: border-box;
}
input{
  width:100%
}
/*.col-50:first-child{
  margin-left:0
}
.col-50:last-child{
  margin-right:0
}*/

<div class="row">
    <div class="col-50">
        <div class="card-box">
            <h4 class="header-title">View Data</h4>
            <div class="table-container">
                <div class="row">
                    <div class="col-50">
                        <div class="btn-group"> <a class="btn-excel" href="#"><span>Excel</span></a> <a class="btn-pdf" href="#"><span>PDF</span></a> </div>
                    </div>
                    <div class="col-50">
                        <form class="pull-right">
                            <input type="text" placeholder="Search..." class="form-control"> <span><i class="fa fa-search"></i></span> </form>
                    </div>
                </div>
                <div class="row">
                    <div class="col-100"> </div>
                </div>
            </div>
        </div>
    </div>
    <div class="col-50">
        <div class="card-box">
            <h4 class="header-title">View Data</h4>
            <div class="table-container">
                <div class="row">
                    <div class="col-50">
                        <div class="btn-group"> <a class="btn-excel" href="#"><span>Excel</span></a> <a class="btn-pdf" href="#"><span>PDF</span></a> </div>
                    </div>
                    <div class="col-50">
                        <form class="pull-right">
                            <input type="text" placeholder="Search..." class="form-control"> <span><i class="fa fa-search"></i></span> </form>
                    </div>
                </div>
                <div class="row">
                    <div class="col-100"> </div>
                </div>
            </div>
        </div>
    </div>
</div>


问:
Learn C# on mac?
Is mono the only route , any specific visual studio like editors that you recommend?</p>

答: Without meaning to state the obvious and miss the point, if you mean a Mac computer rather than a Mac OS, you could install bootcamp or use parallels to run windows on the Mac and then use Visual Studio (there are also free versions of Visual Studio)</p>

Title: Learn C# on mac?

OwnerDisplayName: Christopher Edwards


问:
Automatically specifing a default post-build event in VS 2010
Is there a way in Visual Studio 2010 to automatically specify a post build event command? Right now I have to keep putting in the same command for every new project I create. Is there a way to have all new projects default to a specific post build event command?</p>

答:
This can be done by creating a new project template which includes the post build command.  The template can be derived by creating a new project, adding the post build command and then using that project as the basis for the template.

Creating the template is a bit too involved to capture in a SO answer but here are a few articles on the subject

http://msdn.microsoft.com/en-us/library/6db0hwky(v=VS.100).aspx

http://msdn.microsoft.com/en-us/magazine/cc188697.aspx


问:
How to Insert foreignKey Value in SQLite in Android?
I have a table tableGrupo (Groups) that has a foreign key from other table tableMaquinas (Machines).  When I am inserting data in the table tableGrupo (Groups), Android Studio tells me that the foreign key field must not be null because it is a foreign key.

What value should I attribute in order to have the insertion accepted and pass it the proper foreign key id?

This is my code:

```<code> //Table1
        db.execSQL("CREATE TABLE "+ tableGrupo +" ("+
                idGrupo +" INTEGER PRIMARY KEY AUTOINCREMENT, "+
                nomeGrupo +" TEXT)");

        //Table2
        db.execSQL("CREATE TABLE "+ tableMaquinas +" ("+
                idMaquina +" INTEGER PRIMARY KEY AUTOINCREMENT, "
                + nomeMaquina + " text not null, "
                + imagemMaquina + " BLOB, "
                + id_grupo + " integer, "
                + " FOREIGN KEY ("+id_grupo+") REFERENCES "+tableGrupo+"("+idGrupo+"))");

**This is the code where I make the insertion in the database**

 public void addMachine(String name, byte[] image) throws SQLiteException {
        ContentValues values = new  ContentValues();
        values.put(nomeMaquina,name);
        values.put(imagemMaquina,image);
        //here i have to put a value for the foreignkey
        this.getWritableDatabase().insert(tableMaquinas,null,values);
    }
</code>```

答:
Your table tableMaquinas defines a column id_group as an integer which has a foreign key pointing to a primary key column in the tableGrupo table.  So, beyond the requirement is that it has to point to a record in the tableGrupo table which actually exists.

Here is code which should work with your current schema:

```<code>ContentValues values = new  ContentValues();
values.put(idGrupo, 1);
this.getWritableDatabase().insert(tableGrupo, null, values);

ContentValues values = new  ContentValues();
values.put(nomeMaquina, name);
values.put(imagemMaquina, image);
values.put(id_grupo, 1);
this.getWritableDatabase().insert(tableMaquinas, null, values);
</code>```

Note that I have assumed that certain variables above exist (most already do), but you might have to slightly alter the above code to get it to work in your particular method.

Body:
I have a table tableGrupo (Groups) that has a foreign key from other table tableMaquinas (Machines).  When I am inserting data in the table tableGrupo (Groups), Android Studio tells me that the foreign key field must not be null because it is a foreign key.

What value should I attribute in order to have the insertion accepted and pass it the proper foreign key id?

This is my code:

 //Table1
        db.execSQL("CREATE TABLE "+ tableGrupo +" ("+
                idGrupo +" INTEGER PRIMARY KEY AUTOINCREMENT, "+
                nomeGrupo +" TEXT)");

        //Table2
        db.execSQL("CREATE TABLE "+ tableMaquinas +" ("+
                idMaquina +" INTEGER PRIMARY KEY AUTOINCREMENT, "
                + nomeMaquina + " text not null, "
                + imagemMaquina + " BLOB, "
                + id_grupo + " integer, "
                + " FOREIGN KEY ("+id_grupo+") REFERENCES "+tableGrupo+"("+idGrupo+"))");

**This is the code where I make the insertion in the database**

 public void addMachine(String name, byte[] image) throws SQLiteException {
        ContentValues values = new  ContentValues();
        values.put(nomeMaquina,name);
        values.put(imagemMaquina,image);
        //here i have to put a value for the foreignkey
        this.getWritableDatabase().insert(tableMaquinas,null,values);
    }

Body:
Your table tableMaquinas defines a column id_group as an integer which has a foreign key pointing to a primary key column in the tableGrupo table.  So, beyond the requirement is that it has to point to a record in the tableGrupo table which actually exists.

Here is code which should work with your current schema:

ContentValues values = new  ContentValues();
values.put(idGrupo, 1);
this.getWritableDatabase().insert(tableGrupo, null, values);

ContentValues values = new  ContentValues();
values.put(nomeMaquina, name);
values.put(imagemMaquina, image);
values.put(id_grupo, 1);
this.getWritableDatabase().insert(tableMaquinas, null, values);

Note that I have assumed that certain variables above exist (most already do), but you might have to slightly alter the above code to get it to work in your particular method.


答:
phone not defined outside the start() function.

Here: Mylist.append(phone)

You should fix it.

Optional fix:

```<code>def start():
    print('Hello Welcome to the Phone Trouble-Shooter')
    time.sleep(2)
    phone = input('Please input what brand of phone you have')
    if "iphone" in phone:
        print('Your phone has been identified as an Iphone')
    elif "android" in phone:
        print('Your phone has been identifies as an Android')
    return phone # Add this.

file = open("Excel_Task_3.csv", "w", newline = "")
fileWrite = csv.writer(file,delimiter = ",")
Mylist = []
phone = start()  # Add this.
Mylist.append(phone)

fileWriter.writerow(Mylist)

file.close()
</code>```

Title: Name error in my code

Body:
phone not defined outside the start() function.

Here: Mylist.append(phone)

You should fix it.

Optional fix:

def start():
    print('Hello Welcome to the Phone Trouble-Shooter')
    time.sleep(2)
    phone = input('Please input what brand of phone you have')
    if "iphone" in phone:
        print('Your phone has been identified as an Iphone')
    elif "android" in phone:
        print('Your phone has been identifies as an Android')
    return phone # Add this.

file = open("Excel_Task_3.csv", "w", newline = "")
fileWrite = csv.writer(file,delimiter = ",")
Mylist = []
phone = start()  # Add this.
Mylist.append(phone)

fileWriter.writerow(Mylist)

file.close()


问:
how do i know where to send item bought on my websites
When a costumer buys something from a website how does the owner know where to send the items purchased and is there a way to get notification to my phone when a purchase is made from my website </p>

答:
when a user buy something on the website the owner will get the adress that the user had type in the fields -_- the HTML page will send with a POST the content of the fields to a PHP file on the server.

the form :

```<code><form action="post.php">
  First name:<br>
  <input type="text" name="item" value="the item that you buy"><br>
  Last name:<br>
  <input type="text" name="adress" value="your adress"><br><br>
  <input type="submit" value="Submit">
</form>
</code>```

an example of the php file:

```<code><?php

$item=$_POST['item'];
$user_adress=$_POST['adress'];

echo $item;
echo $user_adress;

?>
</code>```

for the notification on your phone, you can create a page who display the information of a buy. but get a push notification on your phone will be more harder to do

Body:
when a user buy something on the website the owner will get the adress that the user had type in the fields -_- the HTML page will send with a POST the content of the fields to a PHP file on the server.

the form :

<form action="post.php">
  First name:<br>
  <input type="text" name="item" value="the item that you buy"><br>
  Last name:<br>
  <input type="text" name="adress" value="your adress"><br><br>
  <input type="submit" value="Submit">
</form>

an example of the php file:

<?php

$item=$_POST['item'];
$user_adress=$_POST['adress'];

echo $item;
echo $user_adress;

?>

for the notification on your phone, you can create a page who display the information of a buy. but get a push notification on your phone will be more harder to do


问:
Mongoose: improve find() and count() query

Background

I have a query in Mongoose that finds a set of objects, and then returns these said objects together with the total number of them:

```<code>var itemsPerPage = 4, pageNum = 1;

Survey.find({})
    .limit(itemsPerPage)
    .skip(itemsPerPage * pageNum)
    .then(docs => {
        if (docs.length === 0)
            console.log("There are no results matching your query.");
        else
            DocModel.count({})
                .then(number => {
                    console.log(JSON.stringify({number, docs}));
                });
        })
        .catch(console.log);
</code>```

To achieve this I do:

find query with params

use limit and skip to obtain results from correct page

if docs is not empty, start a count query

return information

Problem

The problem here, since I need pagination in the query, is that I have to make 2 separate requests to the DB (find and count) which can potential be very heavy.

To optimize this, I would like to avoid the count query, but I don't know how.

Another issue is the nested promises anti pattern, but that is not the issue I would like to focus on right now.

Question

I am open to any suggestions on improving this code you may have!

答:
You can install mongoose paginate that makes it easier.

```<code>npm install mongoose-paginate
</code>```

after that

```<code>/**
* querying for `all` {} items in `MyModel`
* paginating by second page, 10 items per page (10 results, page 2)
**/

MyModel.paginate({}, 2, 10, function(error, pageCount, paginatedResults) {
    if (error) {
        console.error(error);
    } else {
        console.log('Pages:', pageCount);
        console.log(paginatedResults);
    }
}
</code>```

Hope this work for you. Thanks :-)

Body:
Background

I have a query in Mongoose that finds a set of objects, and then returns these said objects together with the total number of them:

var itemsPerPage = 4, pageNum = 1;

Survey.find({})
    .limit(itemsPerPage)
    .skip(itemsPerPage * pageNum)
    .then(docs => {
        if (docs.length === 0)
            console.log("There are no results matching your query.");
        else
            DocModel.count({})
                .then(number => {
                    console.log(JSON.stringify({number, docs}));
                });
        })
        .catch(console.log);

To achieve this I do:

find query with params

use limit and skip to obtain results from correct page

if docs is not empty, start a count query

return information

Problem

The problem here, since I need pagination in the query, is that I have to make 2 separate requests to the DB (find and count) which can potential be very heavy.

To optimize this, I would like to avoid the count query, but I don't know how.

Another issue is the nested promises anti pattern, but that is not the issue I would like to focus on right now.

Question

I am open to any suggestions on improving this code you may have!

Body:
You can install mongoose paginate that makes it easier.

npm install mongoose-paginate

after that

/**
* querying for `all` {} items in `MyModel`
* paginating by second page, 10 items per page (10 results, page 2)
**/

MyModel.paginate({}, 2, 10, function(error, pageCount, paginatedResults) {
    if (error) {
        console.error(error);
    } else {
        console.log('Pages:', pageCount);
        console.log(paginatedResults);
    }
}

Hope this work for you. Thanks :-)


问:
Json from a get API Call C#
I have a GET API Call as below:

```<code>static void Main()
{
    RunAsync().Wait();
}

static async Task RunAsync()
{
    using (var client = new HttpClient())
    {
        client.BaseAddress = new Uri("myurl");
        client.DefaultRequestHeaders.Accept.Clear();
        client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
        client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("usr", "pwd");
        HttpResponseMessage response = await client.GetAsync("");
        if (response.IsSuccessStatusCode)
        {
            Console.WriteLine(response.Content);
        }
    }
}
</code>```

How do I read the JSON response from the API ?

I was trying to do this:

```<code> response.Content = new ObjectContent<Response>(new Response()
                    {
                        responseCode = Response.ResponseCodes.ItemNotFound
                    }, new JsonMediaTypeFormatter(), "application/json");
</code>```

but I have not been successful yet. Could someone help please?

UPDATE:

My updated code looks like this now:

```<code>static async Task RunAsync()
{
    using (var client = new HttpClient())
    {
        client.BaseAddress = new Uri("myurl");
        client.DefaultRequestHeaders.Accept.Clear();
        client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
        client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("BT", "pwd");
        HttpResponseMessage response = await client.GetAsync("");
        if (response.IsSuccessStatusCode)
        {
            Console.WriteLine(response.Content);
            var json = await response.Content.ReadAsStringAsync();
            Product myprod = JsonConvert.DeserializeObject<Product>(json);

            var results = myprod.result;

            for(int i=1;i<=results.Count;i++)
            {
                var value1 = results[0][0];
                var value2 = results[0][1];
                var value3 = "Nilisha";
                using (SqlConnection conn = new SqlConnection())
                {
                    conn.ConnectionString = "Server=[xx.xx.xx.xx];Database=[Mydb];User ID=sa;Password=abc@321;Trusted_Connection=true";
                    conn.Open();
                    SqlCommand insertCommand = new SqlCommand("INSERT INTO PortalData (LCID, TimeStamp, Name) VALUES ( @1, @2, @3)", conn);
                    insertCommand.Parameters.Add(new SqlParameter("1", value1));
                    insertCommand.Parameters.Add(new SqlParameter("2", value2));
                    insertCommand.Parameters.Add(new SqlParameter("3", value3));

                    Console.WriteLine("Commands executed! Total rows affected are " + insertCommand.ExecuteNonQuery());
                    conn.Close();
                }
            }
            Console.ReadLine();
        }
    }
}
</code>```

Are we allowed to use insert db calls inside the static async Task RunAsync() function ?

答:
If you use flurl, it is as simple as:</p>

```<code>var result = await "https://api.mysite.com"
.AppendPathSegment("person")
.SetQueryParams(new { a = 1, b = 2 })
.WithOAuthBearerToken("my_oauth_token")
.PostJsonAsync(new { first_name = "Frank", last_name = "Underwood" })
.ReceiveJson<T>();
</code>```

Title: Json from a get API Call C#

Body:
I have a GET API Call as below:

static void Main()
{
    RunAsync().Wait();
}

static async Task RunAsync()
{
    using (var client = new HttpClient())
    {
        client.BaseAddress = new Uri("myurl");
        client.DefaultRequestHeaders.Accept.Clear();
        client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
        client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("usr", "pwd");
        HttpResponseMessage response = await client.GetAsync("");
        if (response.IsSuccessStatusCode)
        {
            Console.WriteLine(response.Content);
        }
    }
}

How do I read the JSON response from the API ?

I was trying to do this:

 response.Content = new ObjectContent<Response>(new Response()
                    {
                        responseCode = Response.ResponseCodes.ItemNotFound
                    }, new JsonMediaTypeFormatter(), "application/json");

but I have not been successful yet. Could someone help please?

UPDATE:

My updated code looks like this now:

static async Task RunAsync()
{
    using (var client = new HttpClient())
    {
        client.BaseAddress = new Uri("myurl");
        client.DefaultRequestHeaders.Accept.Clear();
        client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
        client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("BT", "pwd");
        HttpResponseMessage response = await client.GetAsync("");
        if (response.IsSuccessStatusCode)
        {
            Console.WriteLine(response.Content);
            var json = await response.Content.ReadAsStringAsync();
            Product myprod = JsonConvert.DeserializeObject<Product>(json);

            var results = myprod.result;

            for(int i=1;i<=results.Count;i++)
            {
                var value1 = results[0][0];
                var value2 = results[0][1];
                var value3 = "Nilisha";
                using (SqlConnection conn = new SqlConnection())
                {
                    conn.ConnectionString = "Server=[xx.xx.xx.xx];Database=[Mydb];User ID=sa;Password=abc@321;Trusted_Connection=true";
                    conn.Open();
                    SqlCommand insertCommand = new SqlCommand("INSERT INTO PortalData (LCID, TimeStamp, Name) VALUES ( @1, @2, @3)", conn);
                    insertCommand.Parameters.Add(new SqlParameter("1", value1));
                    insertCommand.Parameters.Add(new SqlParameter("2", value2));
                    insertCommand.Parameters.Add(new SqlParameter("3", value3));

                    Console.WriteLine("Commands executed! Total rows affected are " + insertCommand.ExecuteNonQuery());
                    conn.Close();
                }
            }
            Console.ReadLine();
        }
    }
}

Are we allowed to use insert db calls inside the static async Task RunAsync() function ?

Body:
If you use flurl, it is as simple as:

var result = await "https://api.mysite.com"
.AppendPathSegment("person")
.SetQueryParams(new { a = 1, b = 2 })
.WithOAuthBearerToken("my_oauth_token")
.PostJsonAsync(new { first_name = "Frank", last_name = "Underwood" })
.ReceiveJson<T>();


问:
Arraylist - Set/ add method usage - Java
I have an Arraylist of integers.
My requirement is to determine if the arraylist HAS an element existing at the specified index.If YES, then a value should be set to that index (using set method), else a value should be added to that index location(using add method)

Finding it a bit difficult to handle the above condition in my java code.Please help.

Here's what I have so far:

```<code>    ArrayList<Integer> tempArray = new ArrayList<Integer>();
        int counter = 0;
        int tempValue = 0;
    For LOOP -
      if (//certain conditions are satisfied){

      tempValue = calculateNewValue();
      tempArray.add(counter, tempValue); //Need some logic here to determine if its a set or add method to be used
    }
if (//some other conditions are satisfied){
       counter++;
}
    end For LOOP
</code>```

答:
The other answers already provide information about using indexOf methods available in the list. However, just to add some info about difference between "add" and "set" in the ArrayList in java.

From the javadocs -

add(index, value) method - Inserts the specified element at the specified position in this list. Shifts the element currently at that position (if any) and any subsequent elements to the right (adds one to their indices).

set(index, value) - Replaces the element at the specified position in this list with the specified element.

So using add() instead of set() increases your list size as well. You should consider this as well whether you need this behaviour or not.

Body:
I have an Arraylist of integers.
My requirement is to determine if the arraylist HAS an element existing at the specified index.If YES, then a value should be set to that index (using set method), else a value should be added to that index location(using add method)

Finding it a bit difficult to handle the above condition in my java code.Please help.

Here's what I have so far:

    ArrayList<Integer> tempArray = new ArrayList<Integer>();
        int counter = 0;
        int tempValue = 0;
    For LOOP -
      if (//certain conditions are satisfied){

      tempValue = calculateNewValue();
      tempArray.add(counter, tempValue); //Need some logic here to determine if its a set or add method to be used
    }
if (//some other conditions are satisfied){
       counter++;
}
    end For LOOP


问:
Gulp: Read script tags from footer
I'm trying to accomplish the following with Gulp:

Read file footer.html and parse all the paths in

答:
I have same issue, it blowed my brain ))
so there is answer: you need to add cwd:process.cwd() in domSrc options, like this:

```<code>var options = {
    cwd: process.cwd(),
    file: footerFile,
    selector: "script",
    attribute: "src"
};

domSrc(options);
</code>```

Title: Gulp: Read script tags from footer

Body:
I have same issue, it blowed my brain ))
so there is answer: you need to add cwd:process.cwd() in domSrc options, like this:

var options = {
    cwd: process.cwd(),
    file: footerFile,
    selector: "script",
    attribute: "src"
};

domSrc(options);