问:
Redirecting System.out to JTextPane
I have a class (shown below) that extends JPanel and contains a JTextPane. I want to redirect System.out and System.err to my JTextPane. My class does not seem to work. When I run it, it does redirect the system prints, but they do not print to my JTextPane. Please help!

Note: The calls are only redirected when the application launches. But any time after launch, the System.out calls are not redirected to the JTextPane. (ie, if I place a System.out.prinln(); in the class, it will be called, but if it is placed in a actionListener for later use, it does not redirect).

```<code>public class OSXConsole extends JPanel {
    public static final long serialVersionUID = 21362469L;

    private JTextPane textPane;
    private PipedOutputStream pipeOut;
    private PipedInputStream pipeIn;

    public OSXConsole() {
        super(new BorderLayout());
        textPane = new JTextPane();
        this.add(textPane, BorderLayout.CENTER);

        redirectSystemStreams();

        textPane.setBackground(Color.GRAY);
        textPane.setBorder(new EmptyBorder(5, 5, 5, 5));

    }

    private void updateTextPane(final String text) {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                Document doc = textPane.getDocument();
                try {
                    doc.insertString(doc.getLength(), text, null);
                } catch (BadLocationException e) {
                    throw new RuntimeException(e);
                }
                textPane.setCaretPosition(doc.getLength() - 1);
            }
        });
    }

    private void redirectSystemStreams() {
      OutputStream out = new OutputStream() {
        @Override
        public void write(final int b) throws IOException {
          updateTextPane(String.valueOf((char) b));
        }

        @Override
        public void write(byte[] b, int off, int len) throws IOException {
          updateTextPane(new String(b, off, len));
        }

        @Override
        public void write(byte[] b) throws IOException {
          write(b, 0, b.length);
        }
      };

      System.setOut(new PrintStream(out, true));
      System.setErr(new PrintStream(out, true));
    }

}
</code>```

答:
Message Console class does this for you.

Edit:

Here is a simple test class:

```<code>import java.io.*;
import java.awt.*;
import javax.swing.*;
import javax.swing.event.*;
import javax.swing.text.*;

public class MessageConsoleTest
{
    public static int counter;

    public static void main(String[] args)
        throws Exception
    {
        JTextComponent textComponent = new JTextPane();
        JScrollPane scrollPane = new JScrollPane( textComponent );

        JFrame.setDefaultLookAndFeelDecorated(true);
        JFrame frame = new JFrame("Message Console");
        frame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
        frame.getContentPane().add( scrollPane );
        frame.setSize(400, 120);
        frame.setVisible(true);

        MessageConsole console = new MessageConsole(textComponent);
        console.redirectOut();
        console.redirectErr(Color.RED, null);

        Timer timer = new Timer(1000, new java.awt.event.ActionListener()
        {
            public void actionPerformed(java.awt.event.ActionEvent e)
            {
                System.out.println( new java.util.Date().toString() );
            }
        });
        timer.start();

        Thread.sleep(750);

        Timer timer2 = new Timer(1000, new java.awt.event.ActionListener()
        {
            public void actionPerformed(java.awt.event.ActionEvent e)
            {
                System.err.println( "Error Message: " + ++counter);
            }
        });
        timer2.start();
    }
}
</code>```

Title: Redirecting System.out to JTextPane

Body:
I have a class (shown below) that extends JPanel and contains a JTextPane. I want to redirect System.out and System.err to my JTextPane. My class does not seem to work. When I run it, it does redirect the system prints, but they do not print to my JTextPane. Please help!

Note: The calls are only redirected when the application launches. But any time after launch, the System.out calls are not redirected to the JTextPane. (ie, if I place a System.out.prinln(); in the class, it will be called, but if it is placed in a actionListener for later use, it does not redirect).

public class OSXConsole extends JPanel {
    public static final long serialVersionUID = 21362469L;

    private JTextPane textPane;
    private PipedOutputStream pipeOut;
    private PipedInputStream pipeIn;

    public OSXConsole() {
        super(new BorderLayout());
        textPane = new JTextPane();
        this.add(textPane, BorderLayout.CENTER);

        redirectSystemStreams();

        textPane.setBackground(Color.GRAY);
        textPane.setBorder(new EmptyBorder(5, 5, 5, 5));

    }

    private void updateTextPane(final String text) {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                Document doc = textPane.getDocument();
                try {
                    doc.insertString(doc.getLength(), text, null);
                } catch (BadLocationException e) {
                    throw new RuntimeException(e);
                }
                textPane.setCaretPosition(doc.getLength() - 1);
            }
        });
    }

    private void redirectSystemStreams() {
      OutputStream out = new OutputStream() {
        @Override
        public void write(final int b) throws IOException {
          updateTextPane(String.valueOf((char) b));
        }

        @Override
        public void write(byte[] b, int off, int len) throws IOException {
          updateTextPane(new String(b, off, len));
        }

        @Override
        public void write(byte[] b) throws IOException {
          write(b, 0, b.length);
        }
      };

      System.setOut(new PrintStream(out, true));
      System.setErr(new PrintStream(out, true));
    }

}

Body:
Message Console class does this for you.

Edit:

Here is a simple test class:

import java.io.*;
import java.awt.*;
import javax.swing.*;
import javax.swing.event.*;
import javax.swing.text.*;

public class MessageConsoleTest
{
    public static int counter;

    public static void main(String[] args)
        throws Exception
    {
        JTextComponent textComponent = new JTextPane();
        JScrollPane scrollPane = new JScrollPane( textComponent );

        JFrame.setDefaultLookAndFeelDecorated(true);
        JFrame frame = new JFrame("Message Console");
        frame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
        frame.getContentPane().add( scrollPane );
        frame.setSize(400, 120);
        frame.setVisible(true);

        MessageConsole console = new MessageConsole(textComponent);
        console.redirectOut();
        console.redirectErr(Color.RED, null);

        Timer timer = new Timer(1000, new java.awt.event.ActionListener()
        {
            public void actionPerformed(java.awt.event.ActionEvent e)
            {
                System.out.println( new java.util.Date().toString() );
            }
        });
        timer.start();

        Thread.sleep(750);

        Timer timer2 = new Timer(1000, new java.awt.event.ActionListener()
        {
            public void actionPerformed(java.awt.event.ActionEvent e)
            {
                System.err.println( "Error Message: " + ++counter);
            }
        });
        timer2.start();
    }
}


来源: stackexchange

问:
How set imageview scaletype to topCrop
I'm coding android and I have a imageview. I want to set scaletype of this to topcrop.
I could find centercrop in options, but it's not my request. How do I do? </p>

答:
I just wanted a temporary solution without excess work . Try this

```<code><ImageView
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:scaleType="centerCrop"
    android:scrollY="-100dp"
    android:id="@+id/poster"
   />
</code>```

scrollY pulls your image up or down. Try it with different dp's and you 'll find the right size.

ContentLicense: CC BY-SA 3.0

Title: How set imageview scaletype to topCrop

Body:
I just wanted a temporary solution without excess work . Try this

<ImageView
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:scaleType="centerCrop"
    android:scrollY="-100dp"
    android:id="@+id/poster"
   />

scrollY pulls your image up or down. Try it with different dp's and you 'll find the right size.


问:
MethodNotAllowedHttpException with POST method
I am very new with Laravel and facing some problem with it. I am trying to make a register page and facing MethodNotAllowedHttpException after I submitted the form. I have searched many of posts and still get nothing. Could someone help me to find out what should I do? Here is my code.

web.php

```<code>Route::get('/farm/register', 'AccountsController@create');
Route::post('/farm', 'AccountsController@store');
</code>```

AccountsController.php

```<code>public function store(Request $request)
{
    dd(request()->all());
}
</code>```

register.blade.php

```<code><form method="POST" action="{{ URL::route('/farm') }}" >
{{ csrf_field() }}
</code>```

答:
I'm not sure if this will work, but try this:

```<code>Route::post('/farm', 'AccountsController@store')->name('farm')

<form method="post" action="{{ route('farm') }}" >
{{ csrf_field() }}
</code>```

This works for me.

Body:
I am very new with Laravel and facing some problem with it. I am trying to make a register page and facing MethodNotAllowedHttpException after I submitted the form. I have searched many of posts and still get nothing. Could someone help me to find out what should I do? Here is my code.

web.php

Route::get('/farm/register', 'AccountsController@create');
Route::post('/farm', 'AccountsController@store');

AccountsController.php

public function store(Request $request)
{
    dd(request()->all());
}

register.blade.php

<form method="POST" action="{{ URL::route('/farm') }}" >
{{ csrf_field() }}

Body:
I'm not sure if this will work, but try this:

Route::post('/farm', 'AccountsController@store')->name('farm')

<form method="post" action="{{ route('farm') }}" >
{{ csrf_field() }}

This works for me.


问:
Using STUFF in order to get multiple elements into one block in SQL
I have three tables.

1st Table is called Customers with this dummy info in it:

2nd table is called Customer_Product with this dummy info in it:

3rd table is called Products with this dummy info in it:

And the diagram looks like this:

I currently have this code that I wrote:

```<code>SELECT
    A.Customer_Name [Customer Name],
    (SELECT CASE
        WHEN A.Customer_ID = A.Customer_Parent_ID
            THEN 'Is the Parent'
        ELSE(
        SELECT F.Customer_Name
        FROM dbo.Customers F
        Where F.Customer_ID = A.Customer_Parent_ID)
     END)  [Customer Parent's Name],
    C.Product_Name [Product They Own]
FROM dbo.Customers A
JOIN Customer_Product B ON A.Customer_ID = B.Customer_ID
JOIN Products C ON C.Product_ID = B.Product_ID
</code>```

That gives this output:

My question is how can I write a query that instead of what its currently giving me, it would give me an output that looks like this:

Thank you for any and all help! I'm new to SQL so an answer here doesn't really stand out to me, that current code is the closest I can seem to get to what I want. I realize I'll need to use STUFF, but I don't understand how. I've been taking a look at this post (how to get name from another table with matching id in another table?) and trying to use it to work for me, but with little luck.

答:
Make the script you have a CTE.  Then, once you define it as a CTE, you can run this. </p>

```<code>SELECT Customer_name,
      STUFF((
        SELECT ', ' + [Product They Own]
        FROM CTE
        WHERE Customer_name= final.Customer_name
FOR XML PATH('')),1,1,'') AS [Products They Own]
FROM CTE final
GROUP BY Customer_name
</code>```

Body:
I have three tables.

1st Table is called Customers with this dummy info in it:

2nd table is called Customer_Product with this dummy info in it:

3rd table is called Products with this dummy info in it:

And the diagram looks like this:

I currently have this code that I wrote:

SELECT
    A.Customer_Name [Customer Name],
    (SELECT CASE
        WHEN A.Customer_ID = A.Customer_Parent_ID
            THEN 'Is the Parent'
        ELSE(
        SELECT F.Customer_Name
        FROM dbo.Customers F
        Where F.Customer_ID = A.Customer_Parent_ID)
     END)  [Customer Parent's Name],
    C.Product_Name [Product They Own]
FROM dbo.Customers A
JOIN Customer_Product B ON A.Customer_ID = B.Customer_ID
JOIN Products C ON C.Product_ID = B.Product_ID

That gives this output:

My question is how can I write a query that instead of what its currently giving me, it would give me an output that looks like this:

Thank you for any and all help! I'm new to SQL so an answer here doesn't really stand out to me, that current code is the closest I can seem to get to what I want. I realize I'll need to use STUFF, but I don't understand how. I've been taking a look at this post (how to get name from another table with matching id in another table?) and trying to use it to work for me, but with little luck.

Body:
Make the script you have a CTE.  Then, once you define it as a CTE, you can run this.

SELECT Customer_name,
      STUFF((
        SELECT ', ' + [Product They Own]
        FROM CTE
        WHERE Customer_name= final.Customer_name
FOR XML PATH('')),1,1,'') AS [Products They Own]
FROM CTE final
GROUP BY Customer_name


问:
Why won't it draw the Koch curve
```<code>import turtle
import random

screen = turtle.Screen()

X = 400
Y = 400
screen.setup(X, Y)

def drawKoch(ttl, length, generation):
    if (generation == 0 ):
        ttl.fd(generation)
        return
    else:
        drawKoch(ttl, length - 1, generation / 3)
        ttl.lt(60)
        drawKoch(ttl, length - 1, generation / 3)
        ttl.lt(120)
        drawKoch(ttl, length - 1, generation / 3)
        ttl.lt(60)
        drawKoch(ttl, length - 1, generation / 3)

turtle.clearscreen()
screen.reset()
screen.screensize(X, Y)

ttl = turtle.Turtle()
ttl.speed(10)
ttl.penup()
ttl.setposition(-X/2 + 10, -Y/2 + 50)
ttl.pendown()

sides = 3
gens = 3
length = 300
angle = ((sides - 2) * 180) / sides

for i in range(sides):
    drawKoch(ttl, length, gens)
    ttl.left(180-angle)
</code>```

<p>I'm not sure why it won't draw the koch curve. I just begin learning this language not long ago. I need some assistant on this.........hope you guys who know this can help me </p>

答:
A bunch of problems:

you are recursing like length - 1, generation / 3 when it should be length / 3, generation - 1

because of this, where generation should go 3, 2, 1, 0 (halt) instead it is going 3, 1.0, 0.333, 0.111, 0.037, 0.01234, 0.00411, 0.00137, ...  It never "equals" 0, so your function just keeps recursing

you are using generation instead of length in ttl.fd()

ttl.lt(120) should be ttl.rt(120)

Title: Why won't it draw the Koch curve

Body:
import turtle
import random

screen = turtle.Screen()

X = 400
Y = 400
screen.setup(X, Y)

def drawKoch(ttl, length, generation):
    if (generation == 0 ):
        ttl.fd(generation)
        return
    else:
        drawKoch(ttl, length - 1, generation / 3)
        ttl.lt(60)
        drawKoch(ttl, length - 1, generation / 3)
        ttl.lt(120)
        drawKoch(ttl, length - 1, generation / 3)
        ttl.lt(60)
        drawKoch(ttl, length - 1, generation / 3)

turtle.clearscreen()
screen.reset()
screen.screensize(X, Y)

ttl = turtle.Turtle()
ttl.speed(10)
ttl.penup()
ttl.setposition(-X/2 + 10, -Y/2 + 50)
ttl.pendown()

sides = 3
gens = 3
length = 300
angle = ((sides - 2) * 180) / sides

for i in range(sides):
    drawKoch(ttl, length, gens)
    ttl.left(180-angle)

I'm not sure why it won't draw the koch curve. I just begin learning this language not long ago. I need some assistant on this.........hope you guys who know this can help me


问:
Make a select statement output a number with commas
I am using SQL Server and am trying to figure out how to make a select statement output a number separated by commas. I am only able to find how to transform a number into a number with commas, which isn't what I want. The following code is the code I am trying to get to output as a number with commas. Right now when you execute the statement it returns a value of 750000.00 and I want it to return 750,000.00.

Code:

```<code>select max(c.salary) as MaxSalary
from #Career c inner join
     #Member m
    on c.Member_ID = m.Member_ID
where m.age < 35
</code>```

答:
you can use Format if your dataset is minimal as below

```<code>select format(75000.00, 'N')
</code>```

You can do that as below:

```<code>select Format(max(c.salary),'N') as MaxSalary
from #Career c inner join
  #Member m
  on c.Member_ID = m.Member_ID
where m.age < 35
</code>```

Body:
I am using SQL Server and am trying to figure out how to make a select statement output a number separated by commas. I am only able to find how to transform a number into a number with commas, which isn't what I want. The following code is the code I am trying to get to output as a number with commas. Right now when you execute the statement it returns a value of 750000.00 and I want it to return 750,000.00.

Code:

select max(c.salary) as MaxSalary
from #Career c inner join
     #Member m
    on c.Member_ID = m.Member_ID
where m.age < 35

Body:
you can use Format if your dataset is minimal as below

select format(75000.00, 'N')

You can do that as below:

select Format(max(c.salary),'N') as MaxSalary
from #Career c inner join
  #Member m
  on c.Member_ID = m.Member_ID
where m.age < 35


问:
Array from php to javascript file
I have a php file that I gather data on an array and I need to send this data to an external javascript file.
I have read that I need to encode data to JSON format and echo the variable stored, then I try to use this variable on the javascript file but I get an error "Can't find variable: jArray"
What I do wrong?

file.php

```<code><?php $playerNames_new = array();
for ($i=0; $i<$_POST["playerNo"]; $i++) {
    $j = $i+1;
    echo "<form name=\"input\" action=\"#\" method=\"POST\">Player Name $j: <input type=\"text\" name=\"playerName[]\" value=\"\"><br/>";
        $playerNames_new[$i] = $_REQUEST['playerName'];
}

?>
<script type="text/javascript">var jArray = <?php echo json_encode($playerNames_new); ?>;</script>
<script type="text/javascript" src="script.js"></script>
</code>```

script.js

```<code>$(document).ready(function() {
// global variables
var playerNames = jArray;});
</code>```

答:
The following works for me.

```<code><script> var php = <?php echo json_encode([1, 2 ,3]); ?>;</script>
<script src="s.js"></script>
</code>```

or

```<code><script> var php = <?php echo json_encode([1, 2 ,3]); ?>;</script>
<script> console.log(php); </script>
</code>```

Title: Array from php to javascript file

Body:
I have a php file that I gather data on an array and I need to send this data to an external javascript file.
I have read that I need to encode data to JSON format and echo the variable stored, then I try to use this variable on the javascript file but I get an error "Can't find variable: jArray"
What I do wrong?

file.php

<?php $playerNames_new = array();
for ($i=0; $i<$_POST["playerNo"]; $i++) {
    $j = $i+1;
    echo "<form name=\"input\" action=\"#\" method=\"POST\">Player Name $j: <input type=\"text\" name=\"playerName[]\" value=\"\">
";
        $playerNames_new[$i] = $_REQUEST['playerName'];
}

?>

script.js

$(document).ready(function() {
// global variables
var playerNames = jArray;});

Body:
The following works for me.

<script> var php = <?php echo json_encode([1, 2 ,3]); ?>;</script>
<script src="s.js"></script>

or

<script> var php = <?php echo json_encode([1, 2 ,3]); ?>;</script>
<script> console.log(php); </script>


问:
What happens if I overwrite a system-wide variable in a batch script on windows?
I am new to batch scripting (for Windows), so I am reading a tutorial on it. The tutorial states

WARNING: SET will always overwrite (clobber) any existing
  variables. . It’s a good idea to verify you aren’t overwriting a system-wide variable when writing a script... For example, it might be tempting to name a variable
  “temp”, but, that would change the meaning of the widely used “%TEMP%”
  environmental variable.

However the tutorial does not go into the consequences of doing this.
What will happen if I write a batch file that simply overwrites one of these system-wide variables, will it only change the variable in the scope of the script? What about if I type it straight into the command line?

Normally I would just run it an see what happens, but I don't want to accidentally overwrite something important.

答:
set only overwrites variables in that instance of cmd.exe (and child processes started from this instance), it does not affect other console windows (new or existing) and all these variable changes are lost when you close the console window.

You can also make set changes scoped to your batch file with setlocal:

```<code>@echo off
set global=Hello
setlocal
set private=world
</code>```

Persistent changes can be made with the setx resource kit utility.

Body:
set only overwrites variables in that instance of cmd.exe (and child processes started from this instance), it does not affect other console windows (new or existing) and all these variable changes are lost when you close the console window.

You can also make set changes scoped to your batch file with setlocal:

@echo off
set global=Hello
setlocal
set private=world

Persistent changes can be made with the setx resource kit utility.


问:
How can I pass command-line arguments via file association in Vista 64?
How can one pass command line arguments via file association in Vista 64?

I recently built a PC running Vista Ultimate 64-bit.  I noticed several of the Perl scripts I transferred failed due to command-line arguments not being passed.  As a simple test, I wrote the following (foo.pl):

```<code>#!/usr/bin/perl -w
use strict;
my $num_args = $#ARGV + 1;
print "${num_args} arguments read\n";
print "$^X\n" # to see what was being used
</code>```

Running "foo.pl 1 2 3" undesirably yielded:

```<code>0 arguments read
C:\strawberry\perl\bin\perl.exe
</code>```

Running "perl foo.pl 1 2 3" expectedly yielded:

```<code>3 arguments read
C:\strawberry\perl\bin\perl.exe
</code>```

On my old Windows XP PC, both invocations returned 3 arguments.  I documented more of my sleuthing here (win32.perl.org wiki talk), but I've yet to find a solution that works.

I've also tried ActivePerl-5.10.0.1004-MSWin32-x64-287188.msi to no avail.

Any help would be appreciated.  This is driving me batty.

答:
Don't know about Vista and 64bits, but under "classic" versions of Windows you can edit the registry:

```<code>HKEY_CLASSES_ROOT\.pl
</code>```

contains default string "Perl"

```<code>HKEY_CLASSES_ROOT\Perl\shell\open\command
</code>```

contains the default string:

```<code>"C:\path-to\Perl\bin\perl.exe" "%1" %*
</code>```

where %* is a macro for all parameters following the first. Probably the %* is missing.

ContentLicense: CC BY-SA 2.5

Body:
How can one pass command line arguments via file association in Vista 64?

I recently built a PC running Vista Ultimate 64-bit.  I noticed several of the Perl scripts I transferred failed due to command-line arguments not being passed.  As a simple test, I wrote the following (foo.pl):

#!/usr/bin/perl -w
use strict;
my $num_args = $#ARGV + 1;
print "${num_args} arguments read\n";
print "$^X\n" # to see what was being used

Running "foo.pl 1 2 3" undesirably yielded:

0 arguments read
C:\strawberry\perl\bin\perl.exe

Running "perl foo.pl 1 2 3" expectedly yielded:

3 arguments read
C:\strawberry\perl\bin\perl.exe

On my old Windows XP PC, both invocations returned 3 arguments.  I documented more of my sleuthing here (win32.perl.org wiki talk), but I've yet to find a solution that works.

I've also tried ActivePerl-5.10.0.1004-MSWin32-x64-287188.msi to no avail.

Any help would be appreciated.  This is driving me batty.

LastEditorDisplayName: Kurt Leucht

Body:
Don't know about Vista and 64bits, but under "classic" versions of Windows you can edit the registry:

HKEY_CLASSES_ROOT\.pl

contains default string "Perl"

HKEY_CLASSES_ROOT\Perl\shell\open\command

contains the default string:

"C:\path-to\Perl\bin\perl.exe" "%1" %*

where %* is a macro for all parameters following the first. Probably the %* is missing.

OwnerDisplayName: devio


问:
Java RegEx check for one or more formatted strings
Sorry if the title isn't descriptive enough.
I want to be able to extract into a group if a specificly formatted sequence occurs one or more times.

Here is my current REGEX-> (removed duplicate slashes for clarity)

(.?):([A-Z\d]{3}-[A-Z\d]{5}-[A-Z\d]{2})(:[A-Z\d]{3}-[A-Z\d]{5}-[A-Z\d]{2}).

I know I'm close but not quite there.

So these are valid

TEST1:001-12345-67:ABC-DEFGH-IJ

returned as TEST1 , 001-12345-67 , :ABC-DEFGH-IJ (commas separate groups)

WHATEVER:123-12345-12:987-98765-98:ASD-ASDFA-AS  (current regex doesn't work for this)

returned as WHATEVER , 123-12345-12 , :987-98765-98:ASD-ASDFA-AS

And these aren't

TEST1:001-12345-67

WHATEVER:123-12345-12:HMMMM

It's like I need to do a bracket with a '.' for the whole second sequence.  Thanks for everyone's contemplation.  PS Regex make my head hurt.

答:
I would do something like this:

```<code>/(.*?(?::[A-Z\d]{3}-[A-Z\d]{5}-[A-Z\d]{2}){2,})/
</code>```

And then split the captured text on the ":" to get the separate chunks.

EDIT: Wait, you just want three chunks regardless of how many groups there are? That's pretty easy. You could get it by calling split(':', 3) (rather than just split(':') on the results of the above, or go for the regex solution:

```<code>/(.*?):([A-Z\d]{3}-[A-Z\d]{5}-[A-Z\d]{2})((?::[A-Z\d]{3}-[A-Z\d]{5}-[A-Z\d]{2})+)/
</code>```

(The third group will start with an extra ":" that you don't want, that can be removed if you don't mind bloating the pattern even more):

```<code>/(.*?):([A-Z\d]{3}-[A-Z\d]{5}-[A-Z\d]{2}):([A-Z\d]{3}-[A-Z\d]{5}-[A-Z\d]{2}(?::[A-Z\d]{3}-[A-Z\d]{5}-[A-Z\d]{2})*)/
</code>```

Body:
I would do something like this:

/(.*?(?::[A-Z\d]{3}-[A-Z\d]{5}-[A-Z\d]{2}){2,})/

And then split the captured text on the ":" to get the separate chunks.

EDIT: Wait, you just want three chunks regardless of how many groups there are? That's pretty easy. You could get it by calling split(':', 3) (rather than just split(':') on the results of the above, or go for the regex solution:

/(.*?):([A-Z\d]{3}-[A-Z\d]{5}-[A-Z\d]{2})((?::[A-Z\d]{3}-[A-Z\d]{5}-[A-Z\d]{2})+)/

(The third group will start with an extra ":" that you don't want, that can be removed if you don't mind bloating the pattern even more):

/(.*?):([A-Z\d]{3}-[A-Z\d]{5}-[A-Z\d]{2}):([A-Z\d]{3}-[A-Z\d]{5}-[A-Z\d]{2}(?::[A-Z\d]{3}-[A-Z\d]{5}-[A-Z\d]{2})*)/


问:
Clear Symfony2 Http Cache
Is there an easy way for fast removing http cache in symfony2? We've over 30.000 files in cache directory and removing them tooks very long. Is there an better way for doing this? Btw...linking the cache to /dev/null when removing...</p>

答:
If you look in Symfony's cache directory /var/cache/ you'll find an http_cache directory.

So you could use PHP's exec() to remove the directory.

```<code>$root = $this->get('kernel')->getRootDir();
$path = $root . '/../var/cache/prod/http_cache';
exec('rm -rf ' . $path);
</code>```

Title: Clear Symfony2 Http Cache

Body:
If you look in Symfony's cache directory /var/cache/ you'll find an http_cache directory.

So you could use PHP's exec() to remove the directory.

$root = $this->get('kernel')->getRootDir();
$path = $root . '/../var/cache/prod/http_cache';
exec('rm -rf ' . $path);


问:
The working copy <Project name> failed to commit files. - The repository has an uncompleted operation
I've just updated my Xcode from 6 to 7 (and code from Swift 1.2 to Swift 2.0) and try to create new branch in Xcode. After that I can't push my code to Bitbucket.

Is there a way how can I delete repository from directory and setup Bitbucket again and maybe push to another (a new one) repository? Fix of this problem will be great, but I will be satisfied even with move to another repository.

答: In my case I ran git status which revealed that You are currently bisecting. (I was doing a bisect and must had forgotten to reset). I did a git bisect reset and attached the head to my latest commit and it was all fine afterwards.


问:
Count frequency of words in multiple lists from a larger vocabulary?
I know how to count frequency of elements in a list but here's a lightly different question. I have a larger set of vocabulary and a few lists that only use part of the total vocabulary. Using numbers instead of words as an example:

```<code>vocab=[1,2,3,4,5,6,7]
list1=[1,2,3,4]
list2=[2,3,4,5,6,6,7]
list3=[3,2,4,4,1]
</code>```

and I want the output to keep "0"s when a word is not used:

```<code>count1=[1,1,1,1,0,0,0]
count2=[0,1,1,1,1,2,1]
count3=[1,1,1,2,0,0,0]
</code>```

I guess I need to sort the words, but how do I keep the "0" records?

答:
You could also achieve this with the follwing (Python 2):</p>

```<code>map(lambda v: list1.count(v), vocab)
</code>```

Body:
I know how to count frequency of elements in a list but here's a lightly different question. I have a larger set of vocabulary and a few lists that only use part of the total vocabulary. Using numbers instead of words as an example:

vocab=[1,2,3,4,5,6,7]
list1=[1,2,3,4]
list2=[2,3,4,5,6,6,7]
list3=[3,2,4,4,1]

and I want the output to keep "0"s when a word is not used:

count1=[1,1,1,1,0,0,0]
count2=[0,1,1,1,1,2,1]
count3=[1,1,1,2,0,0,0]

I guess I need to sort the words, but how do I keep the "0" records?

Body:
You could also achieve this with the follwing (Python 2):

map(lambda v: list1.count(v), vocab)


问:
Tableau Column Difference - as a dimension
I am looking for difference of two columns in Tableau. I have the formula with me.

```<code>IF ATTR([Valuation Profile]) = "Base" THEN
LOOKUP(ZN(SUM([Value])), 1) > - ZN(LOOKUP(SUM([Value]),0)) END
</code>```

But I get it as a separate column in the columns sections. How do I get that in the rows section? Basically how to get the difference as a dimension?

Please see attached images of what I want and what I have. Apparently, I cannot upload my excel sheet and tableau worksheet here. So I have upload just the screenshots.

What I have - vs - What I want

Tableau Workbook

答:
First off, there is no way that you can generate additional rows for your data in Tableau!
In your case however you could use a workaround and do the following:

Create a calculated field for BASE and one for CSA. The formula should
be IF [Valuation Profile] = 'BASE' THEN [Value] END and IF
[Valuation Profile] = 'CSA' THEN [Value] END respectively

Afterwards you can drag Measure Names onto your rows shelf and

replace the SUM([Value]) with your two newly created calculated fields

that should give you all three measures in different rows in your table

Body:
I am looking for difference of two columns in Tableau. I have the formula with me.

IF ATTR([Valuation Profile]) = "Base" THEN
LOOKUP(ZN(SUM([Value])), 1) > - ZN(LOOKUP(SUM([Value]),0)) END

But I get it as a separate column in the columns sections. How do I get that in the rows section? Basically how to get the difference as a dimension?

Please see attached images of what I want and what I have. Apparently, I cannot upload my excel sheet and tableau worksheet here. So I have upload just the screenshots.

What I have - vs - What I want

Tableau Workbook


问:
Change selected value if radio button is selected
I have a radio button:

```<code><input type="radio" name="editList" id="suc" value="S">Suc
</code>```

If I select radio button I disable lst2 as:

```<code> $('input:radio[name="editList"]')
                       .click(function () {
                           if ($(this).val() === "S") {
                               $('#lst2').prop('disabled', true);
                           } else {
                                $('#lst2').prop('disabled', false);
                           }
                       });
</code>```

But now I want know how can I change value of lst2 automatically with the same value of lst1 if radio button is selected, how can I do it into onChange state?

Select JS:

```<code>function getlst2(sender) {

  // sender: jQuery Object which called this method.
  sender.addClass("changed");
  $("#lst2").getJSONCatalog({
    url: 'https://demo9451608.mockable.io/getTest',
    valueProperty: "id",
    textProperty: "text"
  });
}

$("#lst1").getJSONCatalog({
  url: 'https://demo9451608.mockable.io/getTest',
  valueProperty: "key",
  textProperty: "value",
  onChange: getlst2
});
</code>```

Note: if radio is not selected you can choose lst2 value.

Demo

答:
Sorry, but maybe you could explain yourself better, it's kind of hard to understand you.

Kind of Answer

The change event exists with jQuery, just use change(callbackFunction) function on a jQuery object. in the change callback function, "this" variable is the changed object.

Take care : With a radio button, the change event could be triggered multiple time, for each changing item, so the checked state is important.

Just get the value with val() function on jQuery object.

Body:
I have a radio button:

<input type="radio" name="editList" id="suc" value="S">Suc

If I select radio button I disable lst2 as:

 $('input:radio[name="editList"]')
                       .click(function () {
                           if ($(this).val() === "S") {
                               $('#lst2').prop('disabled', true);
                           } else {
                                $('#lst2').prop('disabled', false);
                           }
                       });

But now I want know how can I change value of lst2 automatically with the same value of lst1 if radio button is selected, how can I do it into onChange state?

Select JS:

function getlst2(sender) {

  // sender: jQuery Object which called this method.
  sender.addClass("changed");
  $("#lst2").getJSONCatalog({
    url: 'https://demo9451608.mockable.io/getTest',
    valueProperty: "id",
    textProperty: "text"
  });
}

$("#lst1").getJSONCatalog({
  url: 'https://demo9451608.mockable.io/getTest',
  valueProperty: "key",
  textProperty: "value",
  onChange: getlst2
});

Note: if radio is not selected you can choose lst2 value.

Demo


问:
How to deploy django project and postgreSQL from localhost to Digital ocean
I have developed django project on my computer. I used virtuelenv and installed all libraries and packages there. I also have postgreSQL database on my computer. How could I deploy my existing server with all files and libraries, my postgreSQL database with all tables and all rows to digitalocean. I only found tutorials on how to create new django projects on digitalocean.</p>

答:
Actually there is plenty of tutorials and documentation for doing this.

https://www.digitalocean.com/community/tags/django?type=tutorials

In the other hand you only have to migrate your data base from your computer to your new server. Maybe you should check this


问:
How to set cookies on a response in a ServiceWorker
In a fetch handler triggered by a page navigation, I tried to do this:

```<code>return event.respondWith(new Response('Hello!', {
  headers: {
    "Set-Cookie": "TestCookie=foo; path=/; Max-Age=60;"
    "TestHeader": "foo"
  }
}));
</code>```

Then I loaded any URL in the browser, and got the "Hello!" body.  In Chrome devtools, I see the TestHeader set in the network panel. But the cookie is not showing up in the network panel, nor in the Application > Cookies viewer.  document.cookie also fails to produce it.

The request is initiated by a page navigation, so there's no opportunity to set credentials: "include" on the fetch from the browser tab.

Is it possible to add a cookie to a response in the ServiceWorker?  If not, is it possible to write cookies in any other way?

答:
There's some relevant information in the Fetch specification.

As per https://fetch.spec.whatwg.org/#forbidden-response-header-name:

A forbidden response-header name is a header name that is a
  byte-case-insensitive match for one of:

Set-Cookie

Set-Cookie2

And then as per item 6 in https://fetch.spec.whatwg.org/#concept-headers-append:

Otherwise, if guard is "response" and name is a forbidden response-header name, return.

This restriction on adding in the Set-Cookie header applies to either constructing new Response objects with an initial set of headers, or adding in headers after the fact to an existing Response object.

There is a plan to add in support for reading and writing cookies inside of a service worker, but that will use a mechanism other than the Set-Cookie header in a Response object. There's more information about the plans in this GitHub issue.

Body:
In a fetch handler triggered by a page navigation, I tried to do this:

return event.respondWith(new Response('Hello!', {
  headers: {
    "Set-Cookie": "TestCookie=foo; path=/; Max-Age=60;"
    "TestHeader": "foo"
  }
}));

Then I loaded any URL in the browser, and got the "Hello!" body.  In Chrome devtools, I see the TestHeader set in the network panel. But the cookie is not showing up in the network panel, nor in the Application > Cookies viewer.  document.cookie also fails to produce it.

The request is initiated by a page navigation, so there's no opportunity to set credentials: "include" on the fetch from the browser tab.

Is it possible to add a cookie to a response in the ServiceWorker?  If not, is it possible to write cookies in any other way?


问:
I have to use a serial port that is shared across two UIs in C# .NET 4.5
I have a C# application that opens up two GUIs at startup.
One of the GUI opens three virtual COM Ports. I want the other GUI that is a part of the same application to show the data that is being sent on those virtual COM Ports. Is there anyway to share this COM Port declaration that I do in the Main/First GUI that I am opening up.</p>

答:
Three ways:

1) Copy the instance of the connection from Window1 to Window2.

window2.Connection = this.Connection;

2) Make it the connection a public static member

```<code>class Window1 : Window
{
   public static SerialConnectionClass Connection { get; set; } = new SerialConnectionClass();
}
</code>```

You can access the connection like that:

```<code>class Window2 :Window
{
...
   private void func()
   {
      Window1.Connection.Send("");
   }
}
</code>```

3) Make a static ConnectionManager

```<code>static class ConnectionManager
{
    public static SerialConnectionClass Connection { get; set; } = new SerialConnectionClass();
    public static EventHandler MessageReceived;
    public static void Send(string text)
    {
        Connection.Send(text);
    }
    ...
}
</code>```

Use it in Window1 and Window2 like this:

```<code>class Window2 :Window
{
...
   private void func()
   {
      ConnectionManager.init("COM1");
      ConnectionManager.MessageReceived += this.MessageReceived;
      ConnectionManager.Send("test123");
   }
}
</code>```

Body:
Three ways:

1) Copy the instance of the connection from Window1 to Window2.

window2.Connection = this.Connection;

2) Make it the connection a public static member

class Window1 : Window
{
   public static SerialConnectionClass Connection { get; set; } = new SerialConnectionClass();
}

You can access the connection like that:

class Window2 :Window
{
...
   private void func()
   {
      Window1.Connection.Send("");
   }
}

3) Make a static ConnectionManager

static class ConnectionManager
{
    public static SerialConnectionClass Connection { get; set; } = new SerialConnectionClass();
    public static EventHandler MessageReceived;
    public static void Send(string text)
    {
        Connection.Send(text);
    }
    ...
}

Use it in Window1 and Window2 like this:

class Window2 :Window
{
...
   private void func()
   {
      ConnectionManager.init("COM1");
      ConnectionManager.MessageReceived += this.MessageReceived;
      ConnectionManager.Send("test123");
   }
}


问:
SQL Server 2008 and Almost-Progressive Sum and Average?
I have a table with several million rows, with an ID column and a DateTimeOffset column. The table simply tracks elapsed time for some operations.

Without touching a cursor or doing RBAR, how can I get the difference between each row, and then the average time among all rows?

For example, if row 1 is 12:00 and row 2 is 12:01 and row 3 is 12:03 then my result set would have row 1 with 0, row 2 with 1, and row 3 with 2. Then my next result set would have a value of 1.5.

Help?

Thanks.

答:
I assume each row has an identity value?

Have a forign key relationship on the table back to itsself.

As you insert each row you give it Fk of the previous row.

Then you can join the table back to itsself e.g.

```<code>Select row2.Offset - row1.Offset from Offsets row1 inner join Offsets row2
on row1.IdentityCol = row2.ForignKeyCol
</code>```

the last row is

```<code>Select avg(row2.Offset - row1.Offset) from Offsets row1 inner join Offsets row2
on row1.IdentityCol = row2.ForignKeyCol
</code>```

Hope this makes sense and is of use to you

BW

Body:
I assume each row has an identity value?

Have a forign key relationship on the table back to itsself.

As you insert each row you give it Fk of the previous row.

Then you can join the table back to itsself e.g.

Select row2.Offset - row1.Offset from Offsets row1 inner join Offsets row2
on row1.IdentityCol = row2.ForignKeyCol

the last row is

Select avg(row2.Offset - row1.Offset) from Offsets row1 inner join Offsets row2
on row1.IdentityCol = row2.ForignKeyCol

Hope this makes sense and is of use to you

BW


问:
React cannot find entry file in any of the roots
I am using React Native as a Pod in my iOS project.
When I try to load a view that I created with React Native I get the Error screen referring me to the Terminal window where npm is running.

In the Terminal the error I am seeing is:
Error: Cannot find entry file in any of the roots:

I tried a few things, moving the file to a different location, but no luck.
I did run "npm start" and I am looking for the file in "http://localhost:8081/".
The current location of the file is in the same location as where I ran "npm start" from.

I am completely stuck here.
Did I configure something wrong. How can I troubleshoot from here?

答:
I wanted to update this after getting a bit frustrated my setup still wasn't working after killing all node processes and running the command above.

There seems to be a ReactNative open issue at present: https://github.com/facebook/react-native/issues/14246

The solution for this is to kill the externally launched package manager and just run "npm start" in the project folder.


问:
OOP: Share an instance of class (Hardware Port) with multiple instances of another class (Filter)
I have a program (user interface) to collect data from  5 different nodes and performs filtering (moving average, winsormean, mode and many other filters) over the received data. The entire program is designed using 3 classes

Class #1 : SerialComm class provide the read and write methods to the
ONLY one serial port to which all the nodes are physically connected.

Class #2 : StatusBar class provide updating the status bar on the user
interface ( error messages , acknowledgment to user action of key
press).

Class #3 : Node class holds the data for each of the 5 nodes , the
data collected over serial interface is post processed using various
filtering techniques.

The serial port can have one instance but each of the node instance needs to use this instance to get_data(). Similarly StatusBar is also only one and currently I'm passing the instance of SerialComm and StatusBar to each instance of the 5 nodes, shown below.

I do not like this approach of passing the instances to each object, is there a better way of handling this?

```<code>class StatusBar:

   def __init__(self):
      self.status_message = 'none'

   def get_status_msg(self):
      return self.status_message

   def update_status_msg(self, msg):
      self.status_message = msg

class SerialComm:
   def __init__(self, portnum, obj_statusbar, baud=19200):

     # More code follows

     self._portNumber = portnum
     self.statusMsg = obj_statusbar

     try:
        self._portInstance = serial.Serial(self._portNumber,baud, timeout=0.05)
     except IOError, e:
        print e

   def write_bytes(self,len):
     # Write method
   def read_bytes(self,len):
     # read method

class Node:
   def __init__(self,obj_statusbar, obj_comm, n_address, n_location=0, ref_rssi=-50,
                n_color=(255,255,0)):
     self._address= n_address
     self._location=n_location
     self._status_bar =obj_statusbar
     self._comm_port = obj_comm

   def read_sensor(self):
        if(  self._comm_port.read_bytes(10) != "112233445566778899AA"):
               self._status_bar.update_status_msg(" Data out of boundary")
     ...
     # More code follows
status_bar = StatusBar()
comm_interface = SerialComm('COM4', status_bar, 19200)

Node_1 = Node(status_bar,comm_interface,0x9,Point(0, 0),-57,RED)
Node_2 = Node(status_bar,comm_interface,0xA,Point(2, 0),-57,GREEN)
Node_3 = Node(status_bar,comm_interface,0xB,Point(1, 2),-57,BLUE)
Node_4 = Node(status_bar,comm_interface,0xC,Point(1, 3),-57,ORANGE)
Node_5 = Node(status_bar,comm_interface,0xD,Point(1, 0),-57,BPINK)
</code>```

答:
This approach is fine. The whole point of a constructor is that you have to provide it with the minimum number of arguments so that it can function after instantiation. If your node relies on a statusbar instance then you should pass it to every node.

This gives you the flexibility to have multiple Nodes, StatusBars and SerialComm objects in different relationships. This is especially important for mocking and unit testing. Do NOT be tempted into using some kind of global hack like using singletons or static variables as singletons. Those quickly become very difficult to test.

Body:
I have a program (user interface) to collect data from  5 different nodes and performs filtering (moving average, winsormean, mode and many other filters) over the received data. The entire program is designed using 3 classes

Class #1 : SerialComm class provide the read and write methods to the
ONLY one serial port to which all the nodes are physically connected.

Class #2 : StatusBar class provide updating the status bar on the user
interface ( error messages , acknowledgment to user action of key
press).

Class #3 : Node class holds the data for each of the 5 nodes , the
data collected over serial interface is post processed using various
filtering techniques.

The serial port can have one instance but each of the node instance needs to use this instance to get_data(). Similarly StatusBar is also only one and currently I'm passing the instance of SerialComm and StatusBar to each instance of the 5 nodes, shown below.

I do not like this approach of passing the instances to each object, is there a better way of handling this?

class StatusBar:

   def __init__(self):
      self.status_message = 'none'

   def get_status_msg(self):
      return self.status_message

   def update_status_msg(self, msg):
      self.status_message = msg

class SerialComm:
   def __init__(self, portnum, obj_statusbar, baud=19200):

     # More code follows

     self._portNumber = portnum
     self.statusMsg = obj_statusbar

     try:
        self._portInstance = serial.Serial(self._portNumber,baud, timeout=0.05)
     except IOError, e:
        print e

   def write_bytes(self,len):
     # Write method
   def read_bytes(self,len):
     # read method

class Node:
   def __init__(self,obj_statusbar, obj_comm, n_address, n_location=0, ref_rssi=-50,
                n_color=(255,255,0)):
     self._address= n_address
     self._location=n_location
     self._status_bar =obj_statusbar
     self._comm_port = obj_comm

   def read_sensor(self):
        if(  self._comm_port.read_bytes(10) != "112233445566778899AA"):
               self._status_bar.update_status_msg(" Data out of boundary")
     ...
     # More code follows
status_bar = StatusBar()
comm_interface = SerialComm('COM4', status_bar, 19200)

Node_1 = Node(status_bar,comm_interface,0x9,Point(0, 0),-57,RED)
Node_2 = Node(status_bar,comm_interface,0xA,Point(2, 0),-57,GREEN)
Node_3 = Node(status_bar,comm_interface,0xB,Point(1, 2),-57,BLUE)
Node_4 = Node(status_bar,comm_interface,0xC,Point(1, 3),-57,ORANGE)
Node_5 = Node(status_bar,comm_interface,0xD,Point(1, 0),-57,BPINK)


答:
Assuming SQL Server 2012 +, the following will get you what you need:

```<code>  SELECT FORMAT([COLUMN], 'N#')
</code>```

where # is the number of decimal places. Put N0 for 0, N2 for 2, etc.

SQL Server 2008 R2:

```<code>  SELECT REPLACE(CONVERT(varchar(20), (CAST([COLUMN] AS MONEY)), 1), '.00', '')
</code>```

Title: Make a select statement output a number with commas

Body:
I am using SQL Server and am trying to figure out how to make a select statement output a number separated by commas. I am only able to find how to transform a number into a number with commas, which isn't what I want. The following code is the code I am trying to get to output as a number with commas. Right now when you execute the statement it returns a value of 750000.00 and I want it to return 750,000.00.

Code:

select max(c.salary) as MaxSalary
from #Career c inner join
     #Member m
    on c.Member_ID = m.Member_ID
where m.age < 35

Body:
Assuming SQL Server 2012 +, the following will get you what you need:

  SELECT FORMAT([COLUMN], 'N#')

where # is the number of decimal places. Put N0 for 0, N2 for 2, etc.

SQL Server 2008 R2:

  SELECT REPLACE(CONVERT(varchar(20), (CAST([COLUMN] AS MONEY)), 1), '.00', '')


问:
dark area in react-vis example
I'm trying to use react-vis. If I use the privided examples, I get black areas between the lines. What do I miss?

答:
I missed some installation instruction:

"Include the built main CSS file in your HTML page or via SASS:

@import "./node_modules/react-vis/dist/style";"

ContentLicense: CC BY-SA 4.0

Title: dark area in react-vis example


问:
Unable to marshall request to JSON, Amazon AWS
I am using amazon aws sns for push notification on android, everything works correctly and I am able to send and receive the notifications on my phone (lollipop os), while when I install the app on a device with (jellybean os), the app crashes when I am calling this

CreatePlatformEndpointResult result = pushClient.createPlatformEndpoint(cpeReq);

The error says Unable to marshall request to JSON and java.lang.NoClassDefFoundError: com.google.gson.stream.JsonWriter

I included the gson library but the problem persists.

EDIT:

I resolved this by using the latest gcm library 8.4.0 in my case and upgrading gradle to 2.10

答: I resolved this by using the latest gcm library 8.4.0 in my case and upgrading gradle to 2.10</p>


问:
Babel setup on ES7
I have been upgrading my project to use ES7. I have changed some codes, made use of classes.

But there is a problem.

```<code>class Example {

   change = async (params) => {

       const job = await Some.job();
   }
}
</code>```

Everytime I wanted to debug it gives me Unexpected token problem. Even if I run it with Babel, it fails. I know a project where people use this kind of syntax and it works. I could not a valid solution on the internet, a couple github issues but nothing solid, so asking here.
What is the problem here? How should I setup the Babel or the project? Below the error from the console and my config file screenshots.

答:
Just check out this link. Installing Babel V6.x ES7 Async/Await on Node.js v6.2.0 with Nodemon
(You can also check this if you want to install plugin: https://babeljs.io/docs/plugins/transform-async-to-generator/ )

Alternatively search Google "babel async await support" and see the results.

Babel does not give you whole things supported out of the box, you have to make some configurations, installing presets/plugins etc.

In my situation I needed to install stage-0 preset and/or transform plugins to make sure async keywords are supported. In the link above it says stage-3 but you can install stage-0 also, it includes all the plugins up to stage-3.

Babel needs to be documented much better, there is no way you could just get to documentation and set things up. There is not a straight one way Getting started a Project setup that shows you things in an ordered way. Hope they woul add it.

Title: Babel setup on ES7

Body:
I have been upgrading my project to use ES7. I have changed some codes, made use of classes.

But there is a problem.

class Example {

   change = async (params) => {

       const job = await Some.job();
   }
}

Everytime I wanted to debug it gives me Unexpected token problem. Even if I run it with Babel, it fails. I know a project where people use this kind of syntax and it works. I could not a valid solution on the internet, a couple github issues but nothing solid, so asking here.
What is the problem here? How should I setup the Babel or the project? Below the error from the console and my config file screenshots.


问:
In an array of objects, fastest way to find the index of an object whose attributes match a search
I've been surfing around a little trying to find an efficient way to do this, but have gotten nowhere. I have an array of objects that looks like this:

```<code>array[i].id = some number;
array[i].name = some name;
</code>```

What I want to do is to find the INDEXES of the objects where id is equal to, for example, one of 0,1,2,3 or 4.
I suppose I could just do something like :

```<code>var indexes = [];
for(i=0; i<array.length; i++) {
  (array[i].id === 0) ? { indexes[0] = i }
  (array[i].id === 1) ? { indexes[1] = i }
  (array[i].id === 2) ? { indexes[2] = i }
  (array[i].id === 3) ? { indexes[3] = i }
  (array[i].id === 4) ? { indexes[4] = i }
}
</code>```

While this would work, it looks to be quite expensive and slow (not to mention ugly), especially if array.length could be large. Any ideas on how to spruce this up a bit? I thought of using array.indexOf somehow but I don't see how to force the syntax. This

```<code>array.indexOf(this.id === 0);
</code>```

for example, returns undefined, as it probably should.

答:
Since there's no answer using regular array find:

var one = {id: 1, name: 'one'};
var two = {id: 2, name:'two'}
var arr = [one, two]

var found = arr.find((a) => a.id === 2)

console.log(found === two) // true

console.log(arr.indexOf(found)) // 1```

Body:
I've been surfing around a little trying to find an efficient way to do this, but have gotten nowhere. I have an array of objects that looks like this:

array[i].id = some number;
array[i].name = some name;

What I want to do is to find the INDEXES of the objects where id is equal to, for example, one of 0,1,2,3 or 4.
I suppose I could just do something like :

var indexes = [];
for(i=0; i<array.length; i++) {
  (array[i].id === 0) ? { indexes[0] = i }
  (array[i].id === 1) ? { indexes[1] = i }
  (array[i].id === 2) ? { indexes[2] = i }
  (array[i].id === 3) ? { indexes[3] = i }
  (array[i].id === 4) ? { indexes[4] = i }
}

While this would work, it looks to be quite expensive and slow (not to mention ugly), especially if array.length could be large. Any ideas on how to spruce this up a bit? I thought of using array.indexOf somehow but I don't see how to force the syntax. This

array.indexOf(this.id === 0);

for example, returns undefined, as it probably should.


问:
Identifying ExtJS elements with selenium webdriver
I am having handling a drop down button in EXTJS application which i am trying to automation with selenium web driver.

clicking on the image i will get a list of elements in the form of 's
to click select from

Please help me how i can device a xpath to click this image, which i should not use "id" (as its extjs it might vary every now and then).
if there are any selector i can use for extjs please suggest. Thanks for your help.

```<code><DIV id=ext-gen2337 class=x-form-field-wrap style="WIDTH: 0px"><INPUT id=ext-gen2023 class=" x-form-text x-form-field" style="WIDTH: 297px" readOnly size=24 value="Clients with pending exceptions" name=ext-gen2023 autocomplete="off"><IMG id=ext-gen2338 class="x-form-trigger x-form-arrow-trigger" src="https:REDACTED/com.ssc.epw.gui.EPWHome/clear.cache.gif">
</code>```

答:
Try below XPath to match required img element:

```<code>//input[@value="Clients with pending exceptions"]/following-sibling::img
</code>```

Body:
I am having handling a drop down button in EXTJS application which i am trying to automation with selenium web driver.

clicking on the image i will get a list of elements in the form of 's
to click select from

Please help me how i can device a xpath to click this image, which i should not use "id" (as its extjs it might vary every now and then).
if there are any selector i can use for extjs please suggest. Thanks for your help.

<INPUT id=ext-gen2023 class=" x-form-text x-form-field" style="WIDTH: 297px" readOnly size=24 value="Clients with pending exceptions" name=ext-gen2023 autocomplete="off">

Body:
Try below XPath to match required img element:

//input[@value="Clients with pending exceptions"]/following-sibling::img


问:
React-Native AirBnb Maps not rendering
So within the constructor, I define a state

```<code>this.state = {
  markers: [{
            title: "Bike1",
            description: "Bike1",
            latitude: 38.232,
            longitude: -121.3312186
          },
          {
            title: "Bike2",
            description: "Bike2",
            latitude: 39.532,
            longitude: -123.5312186
          }]
}
</code>```

Later on, I call the function to map all markers to actual MapView.Markers.

This looks as follows:

```<code>{this.state.markers.map( marker => {
          console.log(JSON.stringify(marker));
          <MapView.Marker
          coordinate={{longitude: marker.longitude, latitude: marker.latitude}}
          title={marker.title}
          description={marker.description}
          >
          <View style={styles.bikeRadius}>
            <View style={styles.bikeMarker}></View>
          </View>
          </MapView.Marker>
        })}
</code>```

However, this works when I call a single marker.

```<code><MapView.Marker coordinate={{latitude: this.state.gpsPosition.latitude, longitude: this.state.gpsPosition.longitude}}>
        <View style={styles.radius}>
          <View style={styles.marker}></View>
        </View>
      </MapView.Marker>
</code>```

I am new to react-native and am not sure what I am doing wrong. Any suggestions?

The link to the full file is https://codepen.io/yeni/pen/QgyWPZ

答:
Try putting "marker" in parenthesis: </p>

```<code>{this.state.markers.map( (marker) => {...
</code>```

Title: React-Native AirBnb Maps not rendering

Body:
So within the constructor, I define a state

this.state = {
  markers: [{
            title: "Bike1",
            description: "Bike1",
            latitude: 38.232,
            longitude: -121.3312186
          },
          {
            title: "Bike2",
            description: "Bike2",
            latitude: 39.532,
            longitude: -123.5312186
          }]
}

Later on, I call the function to map all markers to actual MapView.Markers.

This looks as follows:

{this.state.markers.map( marker => {
          console.log(JSON.stringify(marker));
          <MapView.Marker
          coordinate={{longitude: marker.longitude, latitude: marker.latitude}}
          title={marker.title}
          description={marker.description}
          >
          <View style={styles.bikeRadius}>
            <View style={styles.bikeMarker}></View>
          </View>
          </MapView.Marker>
        })}

However, this works when I call a single marker.

<MapView.Marker coordinate={{latitude: this.state.gpsPosition.latitude, longitude: this.state.gpsPosition.longitude}}>
        <View style={styles.radius}>
          <View style={styles.marker}></View>
        </View>
      </MapView.Marker>

I am new to react-native and am not sure what I am doing wrong. Any suggestions?

The link to the full file is https://codepen.io/yeni/pen/QgyWPZ

Body:
Try putting "marker" in parenthesis:

{this.state.markers.map( (marker) => {...


答:
Try this:

$('input:radio[name="editList"]').change(function (e) {
                           if ($(this).is(':checked')) {
                               $('#lst2').prop('disabled', true);
                             //set the value of lst1 to lst 2
                              $("#lst2").val($("#lst1").val());
                           } else {
                                $('#lst2').prop('disabled', true);
                           }

                       });

                       $('#lst1').change(function (e) {
                           if ($('input:radio[name="editList"]').is(':checked')) {
                               $('#lst2').prop('disabled', true);
                             //set the value of lst1 to lst 2
                              $("#lst2").val($("#lst1").val());
                           } else {
                                $('#lst2').prop('disabled', true);
                           }

                       });

                       (function($) {
  "use strict";

  $.fn.getJSONCatalog = function(options) {

    try {

      var self = this;

      var defaults = {
        url: null,
        headers: {},
        crossDomain: false,
        method: "GET",
        dataType: "json",
        contentType: "application/json; charset=utf-8",
        valueProperty: "",
        textProperty: "",
        dataExtended: null,
        selectedValue: null,
        assignWithoutProperties: false,
        appendDefaultFirstOption: true,
        defaultFirstOptionValue: "",
        defaultFirstOptionText: "-- Seleccione una Opción --",
        defaultFirstOptionDisabled: false,
        isChosenSelect: false,
        onChange: null,
        oneChange: null,
        onSuccess: function() {
          return false;
        },
        messageText: "Get JSON Catalog",
        list: null,
        devMode: false
      };

      var settings = $.extend(defaults, options);

      var appendOptions = function(optionsList) {

        var isChosenSelect = settings.isChosenSelect === true ? true : null;

        if (isChosenSelect) {
          self.chosen("destroy");
        }

        self.empty();

        if (settings.appendDefaultFirstOption === true) {
          self.append($("<option>", {
            value: settings.defaultFirstOptionValue,
            text: settings.defaultFirstOptionText,
            disabled: settings.defaultFirstOptionDisabled === false ? false : true
          }));
        }

        if (optionsList) {

          $.each(optionsList, function() {

            var optionObj;

            if (settings.assignWithoutProperties === false) {

              var hasProperties = {
                value: this[settings.valueProperty],
                text: this[settings.textProperty]
              };

              optionObj = hasProperties;

            } else if (settings.assignWithoutProperties === true) {

              var noProperties = {
                value: this,
                text: this
              };

              optionObj = noProperties;

            }

            if (optionObj) {

              var $option = $("<option>", optionObj);

              if (settings.dataExtended) {
                $option.attr("data-extended", this[settings.dataExtended]);
              }

              self.append($option);
            }

          });

          if (settings.selectedValue) {

            self.val(settings.selectedValue);

            $("option", self).filter(function() {
              return this.value === settings.selectedValue;
            }).prop("selected", true);

          }

          if (settings.onChange) {
            self.on("change", function() {
              settings.onChange(self);
            });
          }

          if (settings.oneChange) {
            self.one("change", function() {
              settings.oneChange(self);
            });
          }

        }

        if (isChosenSelect) {
          self.chosen({
            placeholder_text_single: "-- Seleccione una opción --",
            placeholder_text_multiple: "-- Seleccione múltiples opciones --",
            width: "100%"
          });
        }

      }

      var successfulResponse = function(data) {
        appendOptions(data);
        settings.onSuccess(data);
      };

      if (settings.url) {

        $.ajax({
          method: settings.method,
          dataType: settings.dataType,
          cache: false,
          url: settings.url,
          headers: settings.headers,
          crossDomain: settings.crossDomain,
          contentType: settings.contentType,
          beforeSend: function() {
            // Add hooks before sending data
          },
          success: function(data) {
            if (settings.devMode === true) console.log(data);
            successfulResponse(data);
          },
          failure: function(jqXhr) {
            //console.log("Estatus " + jqXhr.status + ". Error: " + jqXhr.statusText);
          },
          error: function(jqXhr) {
            //console.log("Estatus " + jqXhr.status + ". Error: " + jqXhr.statusText);
          },
          complete: function() {
            //Add complete hooks
          }
        });

      } else if (settings.list) {
        if (settings.devMode === true) console.log(settings.list);
        successfulResponse(settings.list);
      }

    } catch (e) {
      // console.log(e);
    }

    return undefined;
  }

}(jQuery));

  // sender: jQuery Object which called this method.

  $("#lst2").getJSONCatalog({
    url: 'https://demo9451608.mockable.io/getTest',
    valueProperty: "id",
    textProperty: "value"
  });

$("#lst1").getJSONCatalog({
  url: 'https://demo9451608.mockable.io/getTest',
  valueProperty: "key",
  textProperty: "value",
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="radio" name="editList" id="suc" value="S">Suc

<select id="lst1"></select>
<select id="lst2"></select></code>```

Title: Change selected value if radio button is selected

Body:
Try this:

$('input:radio[name="editList"]').change(function (e) {
                           if ($(this).is(':checked')) {
                               $('#lst2').prop('disabled', true);
                             //set the value of lst1 to lst 2
                              $("#lst2").val($("#lst1").val());
                           } else {
                                $('#lst2').prop('disabled', true);
                           }

                       });

                       $('#lst1').change(function (e) {
                           if ($('input:radio[name="editList"]').is(':checked')) {
                               $('#lst2').prop('disabled', true);
                             //set the value of lst1 to lst 2
                              $("#lst2").val($("#lst1").val());
                           } else {
                                $('#lst2').prop('disabled', true);
                           }

                       });

                       (function($) {
  "use strict";

  $.fn.getJSONCatalog = function(options) {

    try {

      var self = this;

      var defaults = {
        url: null,
        headers: {},
        crossDomain: false,
        method: "GET",
        dataType: "json",
        contentType: "application/json; charset=utf-8",
        valueProperty: "",
        textProperty: "",
        dataExtended: null,
        selectedValue: null,
        assignWithoutProperties: false,
        appendDefaultFirstOption: true,
        defaultFirstOptionValue: "",
        defaultFirstOptionText: "-- Seleccione una Opción --",
        defaultFirstOptionDisabled: false,
        isChosenSelect: false,
        onChange: null,
        oneChange: null,
        onSuccess: function() {
          return false;
        },
        messageText: "Get JSON Catalog",
        list: null,
        devMode: false
      };

      var settings = $.extend(defaults, options);

      var appendOptions = function(optionsList) {

        var isChosenSelect = settings.isChosenSelect === true ? true : null;

        if (isChosenSelect) {
          self.chosen("destroy");
        }

        self.empty();

        if (settings.appendDefaultFirstOption === true) {
          self.append($("<option>", {
            value: settings.defaultFirstOptionValue,
            text: settings.defaultFirstOptionText,
            disabled: settings.defaultFirstOptionDisabled === false ? false : true
          }));
        }

        if (optionsList) {

          $.each(optionsList, function() {

            var optionObj;

            if (settings.assignWithoutProperties === false) {

              var hasProperties = {
                value: this[settings.valueProperty],
                text: this[settings.textProperty]
              };

              optionObj = hasProperties;

            } else if (settings.assignWithoutProperties === true) {

              var noProperties = {
                value: this,
                text: this
              };

              optionObj = noProperties;

            }

            if (optionObj) {

              var $option = $("<option>", optionObj);

              if (settings.dataExtended) {
                $option.attr("data-extended", this[settings.dataExtended]);
              }

              self.append($option);
            }

          });

          if (settings.selectedValue) {

            self.val(settings.selectedValue);

            $("option", self).filter(function() {
              return this.value === settings.selectedValue;
            }).prop("selected", true);

          }

          if (settings.onChange) {
            self.on("change", function() {
              settings.onChange(self);
            });
          }

          if (settings.oneChange) {
            self.one("change", function() {
              settings.oneChange(self);
            });
          }

        }

        if (isChosenSelect) {
          self.chosen({
            placeholder_text_single: "-- Seleccione una opción --",
            placeholder_text_multiple: "-- Seleccione múltiples opciones --",
            width: "100%"
          });
        }

      }

      var successfulResponse = function(data) {
        appendOptions(data);
        settings.onSuccess(data);
      };

      if (settings.url) {

        $.ajax({
          method: settings.method,
          dataType: settings.dataType,
          cache: false,
          url: settings.url,
          headers: settings.headers,
          crossDomain: settings.crossDomain,
          contentType: settings.contentType,
          beforeSend: function() {
            // Add hooks before sending data
          },
          success: function(data) {
            if (settings.devMode === true) console.log(data);
            successfulResponse(data);
          },
          failure: function(jqXhr) {
            //console.log("Estatus " + jqXhr.status + ". Error: " + jqXhr.statusText);
          },
          error: function(jqXhr) {
            //console.log("Estatus " + jqXhr.status + ". Error: " + jqXhr.statusText);
          },
          complete: function() {
            //Add complete hooks
          }
        });

      } else if (settings.list) {
        if (settings.devMode === true) console.log(settings.list);
        successfulResponse(settings.list);
      }

    } catch (e) {
      // console.log(e);
    }

    return undefined;
  }

}(jQuery));

  // sender: jQuery Object which called this method.

  $("#lst2").getJSONCatalog({
    url: 'https://demo9451608.mockable.io/getTest',
    valueProperty: "id",
    textProperty: "value"
  });

$("#lst1").getJSONCatalog({
  url: 'https://demo9451608.mockable.io/getTest',
  valueProperty: "key",
  textProperty: "value",
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="radio" name="editList" id="suc" value="S">Suc

<select id="lst1"></select>
<select id="lst2"></select>


问:
How to Use Sitecore Ship with TDS
Could be a basic question but i am not able to find any manual.  I installed Sitecore ship via nuget package
The Sitecore ship is installed. I have a update package created by TDS. i now need to install this.
When I hit the url

"http://mysite/services/package/install/fileupload"

i get a 404.

I am not sure what to do next.
where do i give the path of the package?

Am i missing anything else?

```<code>Sitecore version 8.1
S.ship version 0.4
</code>```

答:
You'll want to issue a POST request to the /services/package/install/fileupload and pass it the location of an update package file to uload to the server.

An Example would be something like

```<code>POST /services/package/install/fileupload HTTP/1.1
Host: shiptester
Accept: application/json, text/javascript, */*
Cache-Control: no-cache

----WebKitFormBoundaryE19zNvXGzXaLvS5C
Content-Disposition: form-data; name="path"; filename="package.update"
Content-Type:

----WebKitFormBoundaryE19zNvXGzXaLvS5C
</code>```

You can reference the Sitecore.Ship Wiki for additional options and feature uses.

Title: How to Use Sitecore Ship with TDS

Body:
Could be a basic question but i am not able to find any manual.  I installed Sitecore ship via nuget package
The Sitecore ship is installed. I have a update package created by TDS. i now need to install this.
When I hit the url

"http://mysite/services/package/install/fileupload"

i get a 404.

I am not sure what to do next.
where do i give the path of the package?

Am i missing anything else?

Sitecore version 8.1
S.ship version 0.4

Body:
You'll want to issue a POST request to the /services/package/install/fileupload and pass it the location of an update package file to uload to the server.

An Example would be something like

POST /services/package/install/fileupload HTTP/1.1
Host: shiptester
Accept: application/json, text/javascript, */*
Cache-Control: no-cache

----WebKitFormBoundaryE19zNvXGzXaLvS5C
Content-Disposition: form-data; name="path"; filename="package.update"
Content-Type:

----WebKitFormBoundaryE19zNvXGzXaLvS5C

You can reference the Sitecore.Ship Wiki for additional options and feature uses.


问:
calling a command through python 3 "shell"
ok. so i have a startup script that i run with "python -i /home/josh/pysh.py" from .bashrc so i can run a term and it goes straight to python and runs my script. this is so i can make a command line environment like bash but in python(i didnt care for ipython).

i've been doing this but it doesnt always work in some cases.
the variable would be a list if there are args.

```<code>from subprocess import call
nano = 'clear'
</code>```

then at the shell i can type:

```<code>call(clear)
</code>```

how can i make it so i can just type:

```<code>clear
</code>```

also if possible id like to embed some of these in seperate modules to import.

答:
The answer to this question is simple.

```<code>from subprocess import call
def clear():
     call("clear")
clear()
</code>```

Just copy the file to /usr/lib/python3.4/clear.py

chmod a+x /usr/lib/python3.4/clear.py
and run
import clear

Body:
ok. so i have a startup script that i run with "python -i /home/josh/pysh.py" from .bashrc so i can run a term and it goes straight to python and runs my script. this is so i can make a command line environment like bash but in python(i didnt care for ipython).

i've been doing this but it doesnt always work in some cases.
the variable would be a list if there are args.

from subprocess import call
nano = 'clear'

then at the shell i can type:

call(clear)

how can i make it so i can just type:

clear

also if possible id like to embed some of these in seperate modules to import.

Body:
The answer to this question is simple.

from subprocess import call
def clear():
     call("clear")
clear()

Just copy the file to /usr/lib/python3.4/clear.py

chmod a+x /usr/lib/python3.4/clear.py
and run
import clear


问:
How to plot a table with non-numeric values in python?
I've got a dataframe with three columns, which I'd like to plot into a chart. I need the chart to show how many (or what's the %) of "Yes" rows from the whole "coverage". I struggle with creating a chart as these are non-numeric values. Can anyone advise, please?

```<code>parent      rule        coverage
AFKS RM     AFKS RM     Yes
AFLT RM     AFLT RM     Yes
AGRO LI     NaN         No
AKRN RM     AKRN RM     Yes
ALRS RM     ALRS RM     Yes
BANE RM     BANE RM     Yes
</code>```

I looked at one of the other answers in Stackoverflow and tried the below but it gives me "TypeError: Empty 'DataFrame': no numeric data to plot".

grouped = df.groupby(['coverage'])['parent']
 grouped.sum().plot(kind='bar')

I also tried to calculate percentage of coverage, but not sure how if that's the right way and how to plot from here.

```<code>df = df[result['coverage']=='Yes'].count() /df['coverage'].count()
</code>```

答:
The easiest way to find percentage is to use mean:

```<code>(df.loc[:,'coverage'] == 'Yes').mean()
</code>```

Output:

```<code>0.83333333333333337
</code>```

Plotting:

df.groupby('coverage')['coverage'].count().plot.pie(autopct='%.2f',figsize=(5,5))

Body:
I've got a dataframe with three columns, which I'd like to plot into a chart. I need the chart to show how many (or what's the %) of "Yes" rows from the whole "coverage". I struggle with creating a chart as these are non-numeric values. Can anyone advise, please?

parent      rule        coverage
AFKS RM     AFKS RM     Yes
AFLT RM     AFLT RM     Yes
AGRO LI     NaN         No
AKRN RM     AKRN RM     Yes
ALRS RM     ALRS RM     Yes
BANE RM     BANE RM     Yes

I looked at one of the other answers in Stackoverflow and tried the below but it gives me "TypeError: Empty 'DataFrame': no numeric data to plot".

grouped = df.groupby(['coverage'])['parent']
 grouped.sum().plot(kind='bar')

I also tried to calculate percentage of coverage, but not sure how if that's the right way and how to plot from here.

df = df[result['coverage']=='Yes'].count() /df['coverage'].count()

Body:
The easiest way to find percentage is to use mean:

(df.loc[:,'coverage'] == 'Yes').mean()

Output:

0.83333333333333337

Plotting:

df.groupby('coverage')['coverage'].count().plot.pie(autopct='%.2f',figsize=(5,5))


问:
Creating a table using jinja2
I am trying to create a (latex) table using jinja2. I defined a macro to help me to create the table:

```<code>{% macro table(header, rows, columns) %}
\begin{tabular}{(formatting, later)}
  {{ row(header) }}
  {% for row in rows %}
    {% for column in columns %}
    {{ caller(row, column) }} & % *here*
    {% endfor %} \\
  {% endfor %}
\end{tabular}
{% endmacro %}
</code>```

I can use the template like this:

```<code>{% call(row, column) table.table(header, rows, columns) %}
  Content at row = {{row}}, column = {{column}}
{% endcall %}
</code>```

I quite like how these macros work. The problem is however that I would like to join the results  of the macro by a & sign rather than
playing a sign after each row. Essentially now I have this:

```<code>    Content at row = 0, column = 0 &
    Content at row = 0, column = 1 & \\
</code>```

and I would like to get this instead:

```<code>    Content at row = 0, column = 0 &
    Content at row = 0, column = 1 \\
</code>```

Is it possible to use filters on macro results? Is there some other way to generate a table where each cell is another jinja2 template depending on parameters?

答:
I'm not familiar with a join functionality in Jinja itself. However it does have built in indexes on your loop. Using loop.last you can determine where to change the output symbol

```<code>    {% macro table(header, rows, columns, ) %}
    \begin{tabular}{(formatting, later)}
      {{ row(header) }}
      {% for row in rows %}
        {% for column in columns %}
        {{ caller(row, column) }} {% if loop.last %}\\{% else %}&{%endif%}
        {% endfor %}
      {% endfor %}
    \end{tabular}
    {% endmacro %}
</code>```

Here's documentation on the other loop variables that are available: http://jinja.pocoo.org/docs/2.9/templates/#for

Title: Creating a table using jinja2

Body:
I am trying to create a (latex) table using jinja2. I defined a macro to help me to create the table:

{% macro table(header, rows, columns) %}
\begin{tabular}{(formatting, later)}
  {{ row(header) }}
  {% for row in rows %}
    {% for column in columns %}
    {{ caller(row, column) }} & % *here*
    {% endfor %} \\
  {% endfor %}
\end{tabular}
{% endmacro %}

I can use the template like this:

{% call(row, column) table.table(header, rows, columns) %}
  Content at row = {{row}}, column = {{column}}
{% endcall %}

I quite like how these macros work. The problem is however that I would like to join the results  of the macro by a & sign rather than
playing a sign after each row. Essentially now I have this:

    Content at row = 0, column = 0 &
    Content at row = 0, column = 1 & \\

and I would like to get this instead:

    Content at row = 0, column = 0 &
    Content at row = 0, column = 1 \\

Is it possible to use filters on macro results? Is there some other way to generate a table where each cell is another jinja2 template depending on parameters?

Body:
I'm not familiar with a join functionality in Jinja itself. However it does have built in indexes on your loop. Using loop.last you can determine where to change the output symbol

    {% macro table(header, rows, columns, ) %}
    \begin{tabular}{(formatting, later)}
      {{ row(header) }}
      {% for row in rows %}
        {% for column in columns %}
        {{ caller(row, column) }} {% if loop.last %}\\{% else %}&{%endif%}
        {% endfor %}
      {% endfor %}
    \end{tabular}
    {% endmacro %}

Here's documentation on the other loop variables that are available: http://jinja.pocoo.org/docs/2.9/templates/#for


问:
Calling Yelp API from frontend JavaScript code running in a browser
Would really appreciate anyone's help. I am relatively new to developing in React, using Mac OSX and Chrome as my browser. I have a small application that attempts to make an async GET request from Yelp Fusion's API using 'isomorphic-fetch', but receive the following error:

Fetch API cannot load https://api.yelp.com/v3/businesses/search?[remaining URL] Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:3000' is therefore not allowed access. The response had HTTP status code 500. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.

I have done a lot of searching to see what responses to identical issues already exist, but I am left even more confused in how to tackle my problem with my relatively new knowledge to this kind of development environment. (Answers that seem particularly helpful are: Response to preflight request doesn't pass access control check and API Request with HTTP Authorization Header inside of componentDidMount, but I do not really understand how to actually implement those solutions with my environment. Any attempts I make seem incorrect and do not result in a change.).

As a side note: I have installed the Allow-Control-Allow-Origin: * extension on my Chrome browser, but I receive the same error - just a shortened, less elaborate description of it:

Fetch API cannot load https://api.yelp.com/v3/businesses/search?[remaining URL]. Response for preflight has invalid HTTP status code 500

The following is how I call the fetch in my code:

```<code>var options = (
    method: 'get',
    headers: new Headers({
        'Access-Control-Allow-Origin': '*',
        'Authorization': [my token]
        'Content-Type': 'application/json'
    })
}
return fetch(url, options);
</code>```

Is this an issue due to the syntax of my header with Yelp Fusion's OAUTH2 token requirements, do I need to do something proxy-related, or is the reason because of something else? If proxy-related, currently I am running a fully client-driven application and do not use server-side code at all. Would this still be possible given my environment? Any guidance as to which direction I should go and clarification of my misconceptions would be greatly appreciated.

Again, thank you for your help for a growing developer.

答:
This cause of the problem is that https://api.yelp.com/ doesn’t support CORS.

And there’s nothing you can in your own application code to fix that—no matter what you try, you can’t change the fact that https://api.yelp.com/ doesn’t support CORS.

Apparently the Yelp API does support JSONP though; see for example Yelp API Origin http://localhost:8888 is not allowed by Access-Control-Allow-Origin.

So using https://api.jquery.com/jquery.getjson/ or similar in your frontend code would allow you make requests to the Yelp API cross-origin from your frontend code.

A related issue in the GitHub issue tracker for the Yelp API examples repo confirms no CORS:

TL;DR: No CORS is not supported by api.yelp.com

And another related issue:

As I answered in #99 , we do not provide the CORS headers necessary to use clientside js to directly make requests to the api.

Both of the comments cited above are from a Yelp engineer.

So what the means is, there’s no way your frontend JavaScript code can make requests directly to Yelp API endpoints and get normal responses (as opposed to JSONP responses).

Specifically, because responses from the https://api.yelp.com/v3/businesses/search API endpoint don’t include the Access-Control-Allow-Origin response header, browsers will not allow your frontend JavaScript code to access those responses.

Also, because your request includes the Authorization and a Content-Type header with the value application/json, your browser does a CORS preflight options request before ever attempting the actual GET request you’re trying to send.

And that preflight is what’s specifically failing in this case. But any other request you make from the frontend code to that API endpoint would also fail—even if it didn’t trigger a preflight.

Body:
Would really appreciate anyone's help. I am relatively new to developing in React, using Mac OSX and Chrome as my browser. I have a small application that attempts to make an async GET request from Yelp Fusion's API using 'isomorphic-fetch', but receive the following error:

Fetch API cannot load https://api.yelp.com/v3/businesses/search?[remaining URL] Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:3000' is therefore not allowed access. The response had HTTP status code 500. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.

I have done a lot of searching to see what responses to identical issues already exist, but I am left even more confused in how to tackle my problem with my relatively new knowledge to this kind of development environment. (Answers that seem particularly helpful are: Response to preflight request doesn't pass access control check and API Request with HTTP Authorization Header inside of componentDidMount, but I do not really understand how to actually implement those solutions with my environment. Any attempts I make seem incorrect and do not result in a change.).

As a side note: I have installed the Allow-Control-Allow-Origin: * extension on my Chrome browser, but I receive the same error - just a shortened, less elaborate description of it:

Fetch API cannot load https://api.yelp.com/v3/businesses/search?[remaining URL]. Response for preflight has invalid HTTP status code 500

The following is how I call the fetch in my code:

var options = (
    method: 'get',
    headers: new Headers({
        'Access-Control-Allow-Origin': '*',
        'Authorization': [my token]
        'Content-Type': 'application/json'
    })
}
return fetch(url, options);

Is this an issue due to the syntax of my header with Yelp Fusion's OAUTH2 token requirements, do I need to do something proxy-related, or is the reason because of something else? If proxy-related, currently I am running a fully client-driven application and do not use server-side code at all. Would this still be possible given my environment? Any guidance as to which direction I should go and clarification of my misconceptions would be greatly appreciated.

Again, thank you for your help for a growing developer.


问:
Add_Image_Size() - Keep asked ratio even if image is smaller
In my current project, I want to have an image that is 1200x600 to fill a 1060x593 space.

Simple enough, I go an do add_image_size('normalSlider',1200,600,true); and done right?

But my client uploads an image that is 750x700. So the image that gets put in my slider is 750x600. So instead of having a rectangle, I get a pretty much square, which breaks my slider.

Is there a way in WP to ask, if the image doesn't fill the size, to keep cropping in the right ratio? Like in my exemple, I need an image with the ratio 2:1, and I would like that the cropped image still be a 2:1 ratio. So if my client uploads a 750x700, the crop should be 750x375.

答:
Question has been asked/answered on Wordpress.SE https://wordpress.stackexchange.com/questions/165374/how-to-get-post-id-of-static-front-page/165376

The gist of it is you better deal with that on the input, because WP has no way to do it by itself.

Another solution, used in my project, is to watch for the size of the image before using it. If the image doesn't have the right width and height, skip the output of the image.

Couldn't just inform the client about it because it's a site with multiple people coming and modifying contents that will probably not give a damn if they break the site or not. Better make sure some dummy can't break the structure instead of having a site that breaks!


问:
Center point coordinates
I have a certain function which takes inputs as milling parameters and then generates a surface .
Within this function I have a for loop which stores the co-ordinates of the center point of my tool.
I wanted to know how can i store the X and Y coordinates of my center point CP
in an array so that i can use these values for further manipulations?
for further manipulation i need to access each value of X-Coordinate of my CP variable using a for loop , multiply the value of X coordinate with some factor and then make this as my new CP x-coordinates for the next iteration of loop.
How do i do this?

```<code>def Milling(xdim, ydim, resolution, feed, infeed, radius ):
"""
Die Funktion gibt eine Punktwolke zurück (x1 y1 z1)
xdim, ydim: gemessenes Feld [mm] \n
resolution: Messpunktauflösung [1/mm] \n
feed: Bahnabstand [mm] \n
infeed: vertikale Zustellung [mm] \n
"""
tstart = time.time()
surface = np.zeros((xdim*resolution+1, ydim*resolution+1))  #inititalisation of the array
i = 0                                                       # Run index for the milling paths
phi = np.arccos(1-infeed/radius)                            # angle between ball cutter center point and extreme trimming edge on the path
print("np.zeros():                          ", (time.time()-tstart)*1000)
for i in range(0,int((xdim+radius)//feed)):                                 #Here is a post-checked-loop, a milling operation is always executed
    cp = [feed*i,-infeed+radius]                            # Center point location of the spherical cutter
    if radius*np.sin(phi) > i*feed:
        x0 = 0                                              # Milling path has a wide range of x0 to x1.
    else:
        x0 = cp[0]-radius*np.sin(phi)                       #if X0 is outside surface set it 0 , i.e at staarting point of workpiece
    if cp[0]+radius*np.sin(phi) > xdim:
        x1 = xdim                                           #if x1 exeeds XDIM set it as last point of workpeice
    else:
        x1 = cp[0]+radius*np.sin(phi)
    for x in range(int(np.round(x0*resolution)),int(np.round(x1*resolution))): # Ball Mill# represents the discretized points on between X0 &x1..remember res is 1/res**
        phi_ = np.arcsin((cp[0]-x/resolution)/radius)
        z = cp[1] - radius * np.cos(phi_)             #this y should be actually a temperory value along Z...
        if surface[x,0] > z:
            surface[x,0] = z
</code>```

So I just wanted to know how can i store and print out the values of my variable cp?

答:
You can use a list to store values in. As an example, you can initiate an empty list storage = [] and then append values to it, using storage.append(value).

```<code>storage = []
for i in range(10):
    cp = [2*i, -i/2]
    storage.append(cp)
    # do other things with cp
</code>```

You can also use the last stored value to calculate the next one, e.g.,

```<code>storage = [[1,1]]
for i in range(10):
    cp = storage[-1]
    cp = [cp[0]+i, -cp[1]/2.]
    storage.append(cp)
</code>```

You may then print the complete list print(storage), or only some value of interest out of it print(storage[3]). You can also let your function return the list,

```<code>def func():
    storage = []
    #....
    return storage
</code>```

Title: Center point coordinates

Body:
I have a certain function which takes inputs as milling parameters and then generates a surface .
Within this function I have a for loop which stores the co-ordinates of the center point of my tool.
I wanted to know how can i store the X and Y coordinates of my center point CP
in an array so that i can use these values for further manipulations?
for further manipulation i need to access each value of X-Coordinate of my CP variable using a for loop , multiply the value of X coordinate with some factor and then make this as my new CP x-coordinates for the next iteration of loop.
How do i do this?

def Milling(xdim, ydim, resolution, feed, infeed, radius ):
"""
Die Funktion gibt eine Punktwolke zurück (x1 y1 z1)
xdim, ydim: gemessenes Feld [mm] \n
resolution: Messpunktauflösung [1/mm] \n
feed: Bahnabstand [mm] \n
infeed: vertikale Zustellung [mm] \n
"""
tstart = time.time()
surface = np.zeros((xdim*resolution+1, ydim*resolution+1))  #inititalisation of the array
i = 0                                                       # Run index for the milling paths
phi = np.arccos(1-infeed/radius)                            # angle between ball cutter center point and extreme trimming edge on the path
print("np.zeros():                          ", (time.time()-tstart)*1000)
for i in range(0,int((xdim+radius)//feed)):                                 #Here is a post-checked-loop, a milling operation is always executed
    cp = [feed*i,-infeed+radius]                            # Center point location of the spherical cutter
    if radius*np.sin(phi) > i*feed:
        x0 = 0                                              # Milling path has a wide range of x0 to x1.
    else:
        x0 = cp[0]-radius*np.sin(phi)                       #if X0 is outside surface set it 0 , i.e at staarting point of workpiece
    if cp[0]+radius*np.sin(phi) > xdim:
        x1 = xdim                                           #if x1 exeeds XDIM set it as last point of workpeice
    else:
        x1 = cp[0]+radius*np.sin(phi)
    for x in range(int(np.round(x0*resolution)),int(np.round(x1*resolution))): # Ball Mill# represents the discretized points on between X0 &x1..remember res is 1/res**
        phi_ = np.arcsin((cp[0]-x/resolution)/radius)
        z = cp[1] - radius * np.cos(phi_)             #this y should be actually a temperory value along Z...
        if surface[x,0] > z:
            surface[x,0] = z

So I just wanted to know how can i store and print out the values of my variable cp?

Body:
You can use a list to store values in. As an example, you can initiate an empty list storage = [] and then append values to it, using storage.append(value).

storage = []
for i in range(10):
    cp = [2*i, -i/2]
    storage.append(cp)
    # do other things with cp

You can also use the last stored value to calculate the next one, e.g.,

storage = [[1,1]]
for i in range(10):
    cp = storage[-1]
    cp = [cp[0]+i, -cp[1]/2.]
    storage.append(cp)

You may then print the complete list print(storage), or only some value of interest out of it print(storage[3]). You can also let your function return the list,

def func():
    storage = []
    #....
    return storage


问:
How do I store the location of an image in a database?
I have a list of colors, with textures that I want to show to particular users, so I need to load the image of the colors that a particular user has, the color's information is contained in a ObjecDTO and one of the properties is its image path. My question is how should I store the image path in the database, are there any special rules, for example since the database and the image file are on the same server should I store a complete file URL, or a relative url, what characters should I escape etcetera, or are there better approaches than mine?

I've searched the web but mostly point to storing BLOBs in the database, which I've found  to be a bad practice.

Any guidance is really appreciated.

regards Tristian.

答:
Create a column called: image_path VARCHAR(255) NOT NULL

And it would contain data like this:

~/images/image1.jpg