问:
Working solution for FZF most recent files in Vim?
I have a problem with finding a proper solution for most recently used files with the FZF Vim plugin.

This plugin should have features like:

show files opened in current vim session(like buffers)

filter files like NERD_tree, fugitive

I tried two solutions

```<code>command! FZFMru call fzf#run({
\ 'source':  reverse(s:all_files()),
\ 'sink':    'edit',
\ 'options': '-m --no-sort -x',
\ 'down':    '40%' })

function! s:all_files()
  return extend(
  \ filter(copy(v:oldfiles),
  \        "v:val !~ 'fugitive:\\|\\.svg|NERD_tree\\|^/tmp/\\|.git/'"),
  \ map(filter(range(1, bufnr('$')), 'buflisted(v:val)'), 'bufname(v:val)'))
endfunction
</code>```

This one works during open session but when I restart Vim I don't see all last opened files.

```<code>command! FZFMru call s:fzf_wrap({
    \'source':  'bash -c "'.
    \               'echo -e \"'.s:old_files().'\";'.
    \               'ag -l -g \"\"'.
    \           '"',
    \})

function! s:fzf_wrap(dict)
    let defaults = {
    \'sink' : 'edit',
    \'options' : '+s -e -m',
    \'tmux_height': '40%',
    \}
    call extend(a:dict, defaults, 'keep')
    call fzf#run(a:dict)
endfunction

function! s:old_files()
    let oldfiles = copy(v:oldfiles)
    call filter(oldfiles, 'v:val !~ "fugitive"')
    call filter(oldfiles, 'v:val !~ "NERD_tree"')
    call filter(oldfiles, 'v:val !~ "^/tmp/"')
    call filter(oldfiles, 'v:val !~ ".git/"')
    call filter(oldfiles, 'v:val !~ ".svg"')
    return join(oldfiles, '\n')
endfunction
</code>```

This solution filters files properly but works only for files opened in previous session. So I need to restart Vim to get the current buffer.

Did you find a working solution for FZFMru in Vim?

答:
Check out https://github.com/junegunn/fzf/wiki/Examples-(vim). Lots of cool stuff there, including MRU, tags search, and much more. Junegunn implemented MRU simply as:</p>

```<code>command! FZFMru call fzf#run({
\  'source':  v:oldfiles,
\  'sink':    'e',
\  'options': '-m -x +s',
\  'down':    '40%'})
</code>```

Body:
I have a problem with finding a proper solution for most recently used files with the FZF Vim plugin.

This plugin should have features like:

show files opened in current vim session(like buffers)

filter files like NERD_tree, fugitive

I tried two solutions

command! FZFMru call fzf#run({
\ 'source':  reverse(s:all_files()),
\ 'sink':    'edit',
\ 'options': '-m --no-sort -x',
\ 'down':    '40%' })

function! s:all_files()
  return extend(
  \ filter(copy(v:oldfiles),
  \        "v:val !~ 'fugitive:\\|\\.svg|NERD_tree\\|^/tmp/\\|.git/'"),
  \ map(filter(range(1, bufnr('$')), 'buflisted(v:val)'), 'bufname(v:val)'))
endfunction

This one works during open session but when I restart Vim I don't see all last opened files.

command! FZFMru call s:fzf_wrap({
    \'source':  'bash -c "'.
    \               'echo -e \"'.s:old_files().'\";'.
    \               'ag -l -g \"\"'.
    \           '"',
    \})

function! s:fzf_wrap(dict)
    let defaults = {
    \'sink' : 'edit',
    \'options' : '+s -e -m',
    \'tmux_height': '40%',
    \}
    call extend(a:dict, defaults, 'keep')
    call fzf#run(a:dict)
endfunction

function! s:old_files()
    let oldfiles = copy(v:oldfiles)
    call filter(oldfiles, 'v:val !~ "fugitive"')
    call filter(oldfiles, 'v:val !~ "NERD_tree"')
    call filter(oldfiles, 'v:val !~ "^/tmp/"')
    call filter(oldfiles, 'v:val !~ ".git/"')
    call filter(oldfiles, 'v:val !~ ".svg"')
    return join(oldfiles, '\n')
endfunction

This solution filters files properly but works only for files opened in previous session. So I need to restart Vim to get the current buffer.

Did you find a working solution for FZFMru in Vim?

Body:
Check out https://github.com/junegunn/fzf/wiki/Examples-(vim). Lots of cool stuff there, including MRU, tags search, and much more. Junegunn implemented MRU simply as:

command! FZFMru call fzf#run({
\  'source':  v:oldfiles,
\  'sink':    'e',
\  'options': '-m -x +s',
\  'down':    '40%'})


来源: stackexchange

问:
Setting custom URLs with PHP
So, I need to set custom URLs so that

http://example.com/dynamic/

goes to:

http://example.com/dynamic.php

I know this is a pretty simple operation but after some googling, I can't find the answer. What is the simplest method for handling something like this?

答:
There's several methods of achieving this:-

URL Rewrite (append to .htaccess file on server in /dynamic/ directory)

```<code>RewriteEngine on
RewriteRule ^$ dynamic.php
</code>```

Creating a dummy index.htm/.html/.php file in root folder ie. /dynamic/

if HTML, use the following javascript:-

```<code><script type="text/javascript">
     window.location = "http://example.com/dynamic.php"
</script>

<script type="text/javascript">
     location.href='http://example.com/dynamic.php';
</script>

<script type="text/javascript">
     location.replace('http://example.com/dynamic.php');
</script>
</code>```

```<code>However, if using PHP instead (recommended), include the following:-
</code>```

header("Location: http://example.com/dynamic.php");

```<code>Remember to use ob_start(), ob_end_flush() to fix the output buffer, if you get the error that the headers are already sent and you can't modify the header information.
</code>```

Hope this helps.

ContentLicense: CC BY-SA 2.5

Title: Setting custom URLs with PHP

Body:
There's several methods of achieving this:-

URL Rewrite (append to .htaccess file on server in /dynamic/ directory)

RewriteEngine on
RewriteRule ^$ dynamic.php

Creating a dummy index.htm/.html/.php file in root folder ie. /dynamic/

if HTML, use the following javascript:-

<script type="text/javascript">
     window.location = "http://example.com/dynamic.php"
</script>

<script type="text/javascript">
     location.href='http://example.com/dynamic.php';
</script>

<script type="text/javascript">
     location.replace('http://example.com/dynamic.php');
</script>

However, if using PHP instead (recommended), include the following:-

header("Location: http://example.com/dynamic.php");

Remember to use ob_start(), ob_end_flush() to fix the output buffer, if you get the error that the headers are already sent and you can't modify the header information.

Hope this helps.


问:
PowerShell script calling a TSQL query result
I am having trouble with a PowerShell script calling a TSQL query result. I want the result of my SQL query to be assigned to the $Output variable as a single value, not a dataset. From my PowerShell script below the $Output variable returns…

```<code>$Output

Column1
--------
100
</code>```

When I need the result to return a single value like the following…

```<code>$Output
100
</code>```

Below is the PowerShell script I am using:

```<code>$SqlConnection = New-Object System.Data.SqlClient.SqlConnection
$SqlConnection.ConnectionString = "Data Source= myserver;Initial
Catalog=mydatabase;Integrated Security=SSPI;"

$SqlCmd = New-Object System.Data.SqlClient.SqlCommand
$SqlCmd.CommandText = "select 100"
$SqlCmd.Connection = $SqlConnection

$DataAdapter = new-object System.Data.SqlClient.SqlDataAdapter $SqlCmd
$Dataset = new-object System.Data.Dataset
write-output $DataAdapter.Fill($Dataset) | Out-Null
$Output = $DataSet.Tables
$Output
</code>```

Any help would be greatly appreciated!

答:
Is this what you're looking for?

```<code>$SqlConnection = New-Object System.Data.SqlClient.SqlConnection
$SqlConnection.ConnectionString = "Data Source= myserver;Initial
Catalog=mydatabase;Integrated Security=SSPI;"
$SqlCmd = New-Object System.Data.SqlClient.SqlCommand
$SqlCmd.CommandText = "select 100"
$SqlCmd.Connection = $SqlConnection
$SqlConnection.Open()
$Output = $SqlCmd.ExecuteScalar()
$Output
</code>```

$SqlCmd.ExecuteScalar() returns a scalar value.
Hope it helps.

ContentLicense: CC BY-SA 3.0

Body:
I am having trouble with a PowerShell script calling a TSQL query result. I want the result of my SQL query to be assigned to the $Output variable as a single value, not a dataset. From my PowerShell script below the $Output variable returns…

$Output

Column1
--------
100

When I need the result to return a single value like the following…

$Output
100

Below is the PowerShell script I am using:

$SqlConnection = New-Object System.Data.SqlClient.SqlConnection
$SqlConnection.ConnectionString = "Data Source= myserver;Initial
Catalog=mydatabase;Integrated Security=SSPI;"

$SqlCmd = New-Object System.Data.SqlClient.SqlCommand
$SqlCmd.CommandText = "select 100"
$SqlCmd.Connection = $SqlConnection

$DataAdapter = new-object System.Data.SqlClient.SqlDataAdapter $SqlCmd
$Dataset = new-object System.Data.Dataset
write-output $DataAdapter.Fill($Dataset) | Out-Null
$Output = $DataSet.Tables
$Output

Any help would be greatly appreciated!

Body:
Is this what you're looking for?

$SqlConnection = New-Object System.Data.SqlClient.SqlConnection
$SqlConnection.ConnectionString = "Data Source= myserver;Initial
Catalog=mydatabase;Integrated Security=SSPI;"
$SqlCmd = New-Object System.Data.SqlClient.SqlCommand
$SqlCmd.CommandText = "select 100"
$SqlCmd.Connection = $SqlConnection
$SqlConnection.Open()
$Output = $SqlCmd.ExecuteScalar()
$Output

$SqlCmd.ExecuteScalar() returns a scalar value.
Hope it helps.


问:
Using for loop for Rock Paper Scissors Game Java
I have been interested in Java for around 2 months now as I have done some courses online, I'm trying to create a game for Rock Paper Scissors. I want the game to be able to run 5 times by using the for loop, though I'm having trouble looping it; it keeps declaring the winner instead of repeating the game?

```<code>import java.util.Scanner;
import java.io.*;

public class Part2
{

    public static void main (String[]args)
    {
        Scanner scan = new Scanner(System.in);

        String userInput1 = " ";
        char player1Input;

        String userInput2 = " ";
        char player2Input;

        for(int i = 0; i < 5; i++) //Loop for game
        {

        System.out.println("Player 1: Please Enter e.g R for Rock:");
        System.out.println("R.Rock");
        System.out.println("P.Paper");
        System.out.println("S.Scissors");

        userInput1 = scan.next();
        player1Input = userInput1.charAt(0);

        System.out.println("Player 2: Please Enter e.g S for Scissors");
        System.out.println("R.Rock");
        System.out.println("P.Paper");
        System.out.println("S.Scissors");

        userInput2 = scan.next();
        player2Input = userInput2.charAt(0);

        }

        switch(player1Input)
        {
            case 'R':  System.out.println ("Player 1:Rock");

                switch(player2Input)
                {
                    case'R' : System.out.println("Player 2:Rock");
                    System.out.println("The Game Result is Draw");
                    break;
                    case'P' :System.out.println("Player 2:Paper");
                    System.out.println("The Game Result is: Player 2 Wins");
                    break;
                    case'S' :System.out.println("Player 2:Scissors");
                    System.out.println("The Game Result is: Player 1 Wins");
                    break;
                    default: System.out.println("Invalid Option");
                    break;
                }
            break;

            case 'P' : System.out.println ("Player 1:Paper");
                switch(player2Input)
                {
                    case'R' : System.out.println("Player 2:Rock");
                    System.out.println("The game result is: Player 1 Wins");
                    break;
                    case'P' :System.out.println("Player 2:Paper");
                    System.out.println("The game result is: Draw");
                    break;
                    case'S' :System.out.println("Player 2:Scissors");
                    System.out.println("The Game Result is: Player 2 Wins2");
                    break;
                    default: System.out.println("Invalid Option");
                    break;
                }
            break;

            case 'S' : System.out.println ("Player 1:Scissors");
                switch(player2Input)
                {
                    case'R' : System.out.println("Player 2:Rock");
                    System.out.println("The Game Result is: Player 2 Wins");
                    break;
                    case'P' :System.out.println("Player 2:Paper");
                    System.out.println("The game result is: Player 1 Wins");
                    break;
                    case'S' :System.out.println("Player 2:Scissors");
                    System.out.println ("The Game Result is: Draw");
                    break;
                    default: System.out.println("Invalid Option");
                    break;
                }
            break;

        }
    }
}
</code>```

答: Your switch statement is out of the code executed by the loop, move it to the point right after the line player2Input = userInput2.charAt(0);, it must stay inside the loop brackets.

Body:
I have been interested in Java for around 2 months now as I have done some courses online, I'm trying to create a game for Rock Paper Scissors. I want the game to be able to run 5 times by using the for loop, though I'm having trouble looping it; it keeps declaring the winner instead of repeating the game?

import java.util.Scanner;
import java.io.*;

public class Part2
{

    public static void main (String[]args)
    {
        Scanner scan = new Scanner(System.in);

        String userInput1 = " ";
        char player1Input;

        String userInput2 = " ";
        char player2Input;

        for(int i = 0; i < 5; i++) //Loop for game
        {

        System.out.println("Player 1: Please Enter e.g R for Rock:");
        System.out.println("R.Rock");
        System.out.println("P.Paper");
        System.out.println("S.Scissors");

        userInput1 = scan.next();
        player1Input = userInput1.charAt(0);

        System.out.println("Player 2: Please Enter e.g S for Scissors");
        System.out.println("R.Rock");
        System.out.println("P.Paper");
        System.out.println("S.Scissors");

        userInput2 = scan.next();
        player2Input = userInput2.charAt(0);

        }

        switch(player1Input)
        {
            case 'R':  System.out.println ("Player 1:Rock");

                switch(player2Input)
                {
                    case'R' : System.out.println("Player 2:Rock");
                    System.out.println("The Game Result is Draw");
                    break;
                    case'P' :System.out.println("Player 2:Paper");
                    System.out.println("The Game Result is: Player 2 Wins");
                    break;
                    case'S' :System.out.println("Player 2:Scissors");
                    System.out.println("The Game Result is: Player 1 Wins");
                    break;
                    default: System.out.println("Invalid Option");
                    break;
                }
            break;

            case 'P' : System.out.println ("Player 1:Paper");
                switch(player2Input)
                {
                    case'R' : System.out.println("Player 2:Rock");
                    System.out.println("The game result is: Player 1 Wins");
                    break;
                    case'P' :System.out.println("Player 2:Paper");
                    System.out.println("The game result is: Draw");
                    break;
                    case'S' :System.out.println("Player 2:Scissors");
                    System.out.println("The Game Result is: Player 2 Wins2");
                    break;
                    default: System.out.println("Invalid Option");
                    break;
                }
            break;

            case 'S' : System.out.println ("Player 1:Scissors");
                switch(player2Input)
                {
                    case'R' : System.out.println("Player 2:Rock");
                    System.out.println("The Game Result is: Player 2 Wins");
                    break;
                    case'P' :System.out.println("Player 2:Paper");
                    System.out.println("The game result is: Player 1 Wins");
                    break;
                    case'S' :System.out.println("Player 2:Scissors");
                    System.out.println ("The Game Result is: Draw");
                    break;
                    default: System.out.println("Invalid Option");
                    break;
                }
            break;

        }
    }
}


问:
Php replace string with regex

I want replace in my file all tags "<_tag_>" with "".

I've tried this solutions:

$_text = preg_replace('<\_\s*\w.*?\_>', '', $_text);

But I replace "<_tag_>" with "<>"

$_text = preg_replace('<\_(.*?)\_>', '', $_text);

But I replace "<_tag_>" with "<>"

How can I also select angle brackets?

答:
It could be

```<code><_.+?_>
# <_, anything lazily afterwards, followed by _>
</code>```

In PHP:

```<code>$string = preg_replace('~<_.+?_>~', '', $string);
</code>```

As in

```<code><?php
$string = "some <_tag_> here";
$string = preg_replace('~<_.+?_>~', '', $string);
echo $string;
# some  here
?>
</code>```

See a demo on ideone.com.

Title: Php replace string with regex

Body:
It could be

<_.+?_>
# <_, anything lazily afterwards, followed by _>

In PHP:

$string = preg_replace('~<_.+?_>~', '', $string);

As in

<?php
$string = "some <_tag_> here";
$string = preg_replace('~<_.+?_>~', '', $string);
echo $string;
# some  here
?>

See a demo on ideone.com.


问:
Allow user to write dynamic blog page with image and text
I am trying to build a blog page, that the users enter text and drag images anywhere on the blog/page, and then they could save it.

I need it to look something like:

Do you know how to make something like that? I tried to look over the web, and could't find how to make it, neither open source project.

thx (:

答:
If the drag & drop part is not mandatory I would use a WYSIWYG editor to let the user write the contents they want and include images. Well, in your case maybe 2 editors, one for the subject and another one for the content.

In google you can find lots of them like https://www.froala.com/wysiwyg-editor and https://www.tinymce.com/

In some of them (like the tinymce one) you can choose which options you let the user use from all the options they provide. I used it some years ago in a platform to create and send bunch of emails to subscribed users. And the email contents were created in a similar way at what you have just described.


问:
Preserve Line Breaks During Sort
This isn't necessarily PHP-specific, although I'm using PHP.  I guess I'm looking for a creative solution.

Say I have a list of terms in a textarea that are separated by an extra new line, for instance:

```<code>Cookie

Apple

Banana
</code>```

I want to sort() these terms and display them after page submit, so that the results look like:

```<code>Apple

Banana

Cookie
</code>```

and not like

```<code>Apple
Banana
Cookie
</code>```

(which would be preceded by two blank lines)

Anyone have any suggestions on how that might be possible?

Sorry, I should have been more clear.  The list in the textarea is entered by a user so it may or may not already contain extra newlines.

答:
If there are always two newlines, then it's as easy as splitting, sorting and joining:

```<code>$result = explode("\n\n", $text);
sort($result);
$result = implode("\n\n", $result);
</code>```

If it could be one or more newlines then:

```<code>preg_match_all("/^(.+$)(\n+)?/m", $text, $matches);

sort($matches[1]);

$result = '';
foreach($matches[1] as $key => $val) {
    $result .= $val . $matches[2][$key];
}
</code>```

Match all line text $matches[1] and the terminating newlines (if any) $matches[2]

Sort the line text array $matches[1]

Loop the line text array $matches[1] and add the corresponding newlines (if any) $matches[2]

Title: Preserve Line Breaks During Sort

Body:
This isn't necessarily PHP-specific, although I'm using PHP.  I guess I'm looking for a creative solution.

Say I have a list of terms in a textarea that are separated by an extra new line, for instance:

Cookie

Apple

Banana

I want to sort() these terms and display them after page submit, so that the results look like:

Apple

Banana

Cookie

and not like

Apple
Banana
Cookie

(which would be preceded by two blank lines)

Anyone have any suggestions on how that might be possible?

Sorry, I should have been more clear.  The list in the textarea is entered by a user so it may or may not already contain extra newlines.

Body:
If there are always two newlines, then it's as easy as splitting, sorting and joining:

$result = explode("\n\n", $text);
sort($result);
$result = implode("\n\n", $result);

If it could be one or more newlines then:

preg_match_all("/^(.+$)(\n+)?/m", $text, $matches);

sort($matches[1]);

$result = '';
foreach($matches[1] as $key => $val) {
    $result .= $val . $matches[2][$key];
}

Match all line text $matches[1] and the terminating newlines (if any) $matches[2]

Sort the line text array $matches[1]

Loop the line text array $matches[1] and add the corresponding newlines (if any) $matches[2]


问:
Running script from python command line
Using Python3.3

Trying to run a script from python command line. Need to run this from python command line instead of windows command line because of some encoding format issue. But I am getting below error:

```<code>>>> python Start.py
File "<stdin>", line 1
python Start.py
           ^
SyntaxError: invalid syntax
</code>```

I think I am already within Python so the above is invalid. I tried execfile but that doesn't help either.

Can anyone please help?

EDIT

The problem with running the script from python command line is solved. Although that doesn't solve the original encoding issue. See the thread here Changing the preferred encoding for Windows7 command prompt

Title: Running script from python command line

Body:
Using Python3.3

Trying to run a script from python command line. Need to run this from python command line instead of windows command line because of some encoding format issue. But I am getting below error:

>>> python Start.py
File "<stdin>", line 1
python Start.py
           ^
SyntaxError: invalid syntax

I think I am already within Python so the above is invalid. I tried execfile but that doesn't help either.

Can anyone please help?

EDIT

The problem with running the script from python command line is solved. Although that doesn't solve the original encoding issue. See the thread here Changing the preferred encoding for Windows7 command prompt

Body: exec(open('Start.py').read(),globals())


问:
underscore - convert complex object into array using underscore.js
I am trying to format my object array into an array to be used by a component. I need to map the exact values of the object to the correct positions.

e.g.

My Raw Data:

```<code>var rawData = [
                { name: 'john',
                  age: 23,
                  style : 'expert',
                  max : 'none'
                },
                { name: 'mick',
                  age: 36,
                  style : 'inter',
                  max : 'none'
                },
                { name: 'pete',
                  age: 44,
                  style : 'med',
                  max : 'none'
                }
               ]
</code>```

i would like to use underscore.js to convert this object to the following array format so I can use in my component which requires this format.

Please note only name age and style are required not max. I have more undesired properties but for example above I did not want to write all.

```<code>var result = [
   [ "john", "23", "expoert"],
   [ "mick", "36", "inter"],
   [ "pete", "44", "med"]
]
</code>```

I have tried pluck and map combinations, but can't seem to get the order correct in the outputted array. Any help appreciated.

答:
This is trivial without any library using Array#map() and Object.values()

var rawData = [{
  name: 'john',
  age: 23,
  style: 'expert'
}, {
  name: 'mick',
  age: 36,
  style: 'inter'
}, {
  name: 'pete',
  age: 44,
  style: 'med'
}]

var res = rawData.map(o=>Object.values(o))
console.log(res)```

Body:
I am trying to format my object array into an array to be used by a component. I need to map the exact values of the object to the correct positions.

e.g.

My Raw Data:

var rawData = [
                { name: 'john',
                  age: 23,
                  style : 'expert',
                  max : 'none'
                },
                { name: 'mick',
                  age: 36,
                  style : 'inter',
                  max : 'none'
                },
                { name: 'pete',
                  age: 44,
                  style : 'med',
                  max : 'none'
                }
               ]

i would like to use underscore.js to convert this object to the following array format so I can use in my component which requires this format.

Please note only name age and style are required not max. I have more undesired properties but for example above I did not want to write all.

var result = [
   [ "john", "23", "expoert"],
   [ "mick", "36", "inter"],
   [ "pete", "44", "med"]
]

I have tried pluck and map combinations, but can't seem to get the order correct in the outputted array. Any help appreciated.


答:
const rawData = [
     { name: 'john', age: 23, style : 'expert' },
     { name: 'mick', age: 36, style : 'inter' }
];

const result = rawData.map(Object.values);

console.log(result);```
</div>
</div>
</p>

<p>Theres no need to use a library at all. Or more explicitly:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>    const rawData = [
         { name: 'john', age: 23, style : 'expert' },
         { name: 'mick', age: 36, style : 'inter' }
    ];

    const result = rawData.map(({name, age, style}) => [name, age, style]);

    console.log(result);</code>```

I would prefer this as object key/value order is not guaranteed.

Title: underscore - convert complex object into array using underscore.js

Body:
const rawData = [
     { name: 'john', age: 23, style : 'expert' },
     { name: 'mick', age: 36, style : 'inter' }
];

const result = rawData.map(Object.values);

console.log(result);

Theres no need to use a library at all. Or more explicitly:

    const rawData = [
         { name: 'john', age: 23, style : 'expert' },
         { name: 'mick', age: 36, style : 'inter' }
    ];

    const result = rawData.map(({name, age, style}) => [name, age, style]);

    console.log(result);

I would prefer this as object key/value order is not guaranteed.


问:
Muse website won't scroll on Chrome
I'm posting on behalf of my SO. Her muse-created website at http://demi.statesideapm.com/ won't scroll horizontally on Chrome, but it works fine on Safari and Edge. The site is just for a uni project and she eventually wants it to be something like this: http://mashup.ikm.gda.pl/

I've found a few people with similar issues but the possible fixes such as removing position:fixed and overflow-x: hidden; height: auto; don't seem to work. She's trialing some sort of slideshow plugin - could it be to do with that?

答:
Go to Page Properties

Select Options

Browser Scrollbars

Change Vertical from Automatic to Always

Title: Muse website won't scroll on Chrome


问:
Copy cells and paste them in all those that are empty
I need a macro that, (at it says in the title) copy the two last cells, in this case A419 and B419, and paste their value until it find others that contain information.

In example:

As you can see in the image, there's the Value 1004-004 and 36300025 and a lot of empty cells below. And more below theres 1004-005 and 36300026 Something like from 420 to 434. And then select 1004-005 and 36300026 and repeat the process.

This:

To this:

Well, that's all, i don't really know how to do it, so i'll be very grateful if you can help me out guys.

答:
While you should be posting code you need help with, I already have this code written.  Just select your range and then run this macro.</p>

```<code> Sub Fill_from_above()

 For Each c In Selection.Cells
     If c.Value = "" Then
         c.Value = c.Offset(-1, 0).Value
     End If
 Next c
 End Sub
</code>```

Body:
While you should be posting code you need help with, I already have this code written.  Just select your range and then run this macro.

 Sub Fill_from_above()

 For Each c In Selection.Cells
     If c.Value = "" Then
         c.Value = c.Offset(-1, 0).Value
     End If
 Next c
 End Sub


问:
How to use cURL and PHP to redirect big files?
I need to use cURL with PHP to access a big file inside a Cloud storage.
The storage URL change according to request.
The PHP script is using a library to grant access using cURL and return the file.

But, HTTP request is throwing a 500 status because PHP is failing with the error:

```<code>PHP Fatal error:  Allowed memory size of 134217728 bytes exhausted (tried to allocate 133700011 bytes)
</code>```

So, How can I properly redirect the requests? The field Location: is not working too because it misses the extra parameter inside the HTTP header.

Here is the script:

```<code>function fetch($url, $cookie=null) {
    $ch =  curl_init();

    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_AUTOREFERER, true);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
    curl_setopt($ch, CURLINFO_HEADER_OUT, true);

    if ($cookie) {
        curl_setopt($ch, CURLOPT_COOKIE, $cookie);
    }

    $result = curl_exec($ch);

    curl_close($ch);

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

Any hints?

答:
curl_setopt($ch, CURLOPT_FILE, $stream_resource);

Where $stream_resource is something opened with fdopen(), say.

Body:
I need to use cURL with PHP to access a big file inside a Cloud storage.
The storage URL change according to request.
The PHP script is using a library to grant access using cURL and return the file.

But, HTTP request is throwing a 500 status because PHP is failing with the error:

PHP Fatal error:  Allowed memory size of 134217728 bytes exhausted (tried to allocate 133700011 bytes)

So, How can I properly redirect the requests? The field Location: is not working too because it misses the extra parameter inside the HTTP header.

Here is the script:

function fetch($url, $cookie=null) {
    $ch =  curl_init();

    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_AUTOREFERER, true);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
    curl_setopt($ch, CURLINFO_HEADER_OUT, true);

    if ($cookie) {
        curl_setopt($ch, CURLOPT_COOKIE, $cookie);
    }

    $result = curl_exec($ch);

    curl_close($ch);

    return $result;
}

Any hints?


问:
Program received signal SIGTRAP, Trace/breakpoint trap. [Switching to Thread 6]
I know this question has been asked before, but I have read all the threads and I didn't find an answer.
From the moment I execure run to start debugging my project, I get this : Program received signal SIGTRAP, Trace/breakpoint trap. [Switching to Thread 6]. When I do ctrl+c, gdb tells me : Program received signal SIGINT, Interrupt.
0x00000000 in ?? ()

Usually it'll tell me which file and which function it got interrupted at not 0x00000000 in ?? ()
GDB no longer hits breakpoints, and what makes matter crazier is the fact that a colleague and I, are sharing the same session (the debug is done using cygwin with a remote machine) and it works fine for them but not for me.
when I try to get info about the threads using info threads here's what I get :

```<code>[New Thread 20]
 [New Thread 21]
 [New Thread 22]
  Id   Target Id         Frame
  4    Thread 22 (ssp=0xa9004d5c) 0x00000000 in ?? ()
  3    Thread 21 (ssp=0xa9002e64) 0x00000010 in ?? ()
  2    Thread 20 (ssp=0xa9000ef4) 0x00000000 in ?? ()

The current thread <Thread ID 1> has terminated.  See `help thread'
</code>```

there's no thread 6, there's no * to indicate which thread gdb is using. And I don't even know if that's linked to the problem.
Can anyone please help me?

答:
You are not providing nearly enough info to help you. Details matter, and you are withholding them. Versions of GDB and gdbserver matter, how you invoke GDB and gdbserver matter, what warnings you receive from GDB (if any) matter.

Now, this error message:

```<code>Program received signal SIGTRAP, Trace/breakpoint trap. [Switching to Thread 6]
</code>```

usually means that gdbserver has not attached one of the threads of your process, and that thread has tried to execute breakpoint instruction (you do have breakpoints set before this happens, don't you?).

One of the reasons this may happen is when your GDB loads "wrong" libthread_db.so (one that doesn't match the target libc.so.6).

what makes matter crazier is the fact that a colleague and I, are sharing the same session (the debug is done using cygwin with a remote machine) and it works fine for them but not for me.

I am not sure what you mean by "same session", but it's probably not "when he types commands, they work; but when I type the same commands into the same GDB, they don't".

One difference between you and your colleague could be LD_LIBRATY_PATH environment variable setting. Another could be in ~/.gdbinit or in ./.gdbinit.

I suggest running gdb -nx to get rid of the latter, and unsetting LD_LIBRARY_PATH to get rid of the former.

Body:
I know this question has been asked before, but I have read all the threads and I didn't find an answer.
From the moment I execure run to start debugging my project, I get this : Program received signal SIGTRAP, Trace/breakpoint trap. [Switching to Thread 6]. When I do ctrl+c, gdb tells me : Program received signal SIGINT, Interrupt.
0x00000000 in ?? ()

Usually it'll tell me which file and which function it got interrupted at not 0x00000000 in ?? ()
GDB no longer hits breakpoints, and what makes matter crazier is the fact that a colleague and I, are sharing the same session (the debug is done using cygwin with a remote machine) and it works fine for them but not for me.
when I try to get info about the threads using info threads here's what I get :

[New Thread 20]
 [New Thread 21]
 [New Thread 22]
  Id   Target Id         Frame
  4    Thread 22 (ssp=0xa9004d5c) 0x00000000 in ?? ()
  3    Thread 21 (ssp=0xa9002e64) 0x00000010 in ?? ()
  2    Thread 20 (ssp=0xa9000ef4) 0x00000000 in ?? ()

The current thread <Thread ID 1> has terminated.  See `help thread'

there's no thread 6, there's no * to indicate which thread gdb is using. And I don't even know if that's linked to the problem.
Can anyone please help me?

Body:
You are not providing nearly enough info to help you. Details matter, and you are withholding them. Versions of GDB and gdbserver matter, how you invoke GDB and gdbserver matter, what warnings you receive from GDB (if any) matter.

Now, this error message:

Program received signal SIGTRAP, Trace/breakpoint trap. [Switching to Thread 6]

usually means that gdbserver has not attached one of the threads of your process, and that thread has tried to execute breakpoint instruction (you do have breakpoints set before this happens, don't you?).

One of the reasons this may happen is when your GDB loads "wrong" libthread_db.so (one that doesn't match the target libc.so.6).

what makes matter crazier is the fact that a colleague and I, are sharing the same session (the debug is done using cygwin with a remote machine) and it works fine for them but not for me.

I am not sure what you mean by "same session", but it's probably not "when he types commands, they work; but when I type the same commands into the same GDB, they don't".

One difference between you and your colleague could be LD_LIBRATY_PATH environment variable setting. Another could be in ~/.gdbinit or in ./.gdbinit.

I suggest running gdb -nx to get rid of the latter, and unsetting LD_LIBRARY_PATH to get rid of the former.

ContentLicense: CC BY-SA 4.0


问:
Configure slave replication for MariaDB Galera
MariaDB 10.2.10+Centos 7.

I have configured the MariaDB Galera Cluster with HAProxy, and tested successfully.

For backup, I wanted to add one async replication slave for the Galera cluster, but failed.

Below is my action:

After all galera cluster actions were done, I added below configuration under each galera node's /etc/my.cnf.d/server.cnf's [mysqld] section:

```<code>[mysqld]
log_bin
log_slave_updates
gtid_strict_mode
server_id=1
 [galera]
wsrep_gtid_mode
</code>```

and added below configuration under each slave node's /etc/my.cnf.d/server.cnf's [mysqld] section:

```<code>[mysqld]
binlog_format=ROW
log_bin
log_slave_updates
server_id=2
gtid_strict_mode
</code>```

Later created one user for replication, and did mysqldump out on one galera node and did an import on slave node.

Then ran on slave:

```<code>stop slave; change master to master_host='one galera node name ',master_port=3306,master_user='repl_user',master_password='repl_password',master_use_gtid=current_pos; start slave;
</code>```

but failed.
The error msg is:

Got fatal error 1236 from master when reading data from binary log:
  'Error: connecting slave requested to start from GTID 0-2-11, which is
  not in the master's binlog'

Do you have any suggestion, if any, very appreciated.

答:
After researching, I modified the settings I mentioned above:

on each node of the Galera Cluster, they have the same domain id and different server id:

```<code>[mysqld]
log_bin
log_slave_updates
gtid_strict_mode
gtid_domain_id=1
server_id=1
 [galera]
wsrep_gtid_mode
</code>```

on the slave node, slave node has the different domain id and server id:

```<code>[mysqld]
binlog_format=ROW
log_bin
log_slave_updates
gtid_domain_id=2
server_id=2
</code>```

then do mysqldump out and mysql import, last run

```<code>change master to master_host='one galera node name',master_port=3306, master_user='repl_user',master_password='aa',master_use_gtid=current_pos;
start slave;
</code>```

Everything goes well.

When I add database or table or insert data into one table, it can sync to the slave node.

Body:
MariaDB 10.2.10+Centos 7.

I have configured the MariaDB Galera Cluster with HAProxy, and tested successfully.

For backup, I wanted to add one async replication slave for the Galera cluster, but failed.

Below is my action:

After all galera cluster actions were done, I added below configuration under each galera node's /etc/my.cnf.d/server.cnf's [mysqld] section:

[mysqld]
log_bin
log_slave_updates
gtid_strict_mode
server_id=1
 [galera]
wsrep_gtid_mode

and added below configuration under each slave node's /etc/my.cnf.d/server.cnf's [mysqld] section:

[mysqld]
binlog_format=ROW
log_bin
log_slave_updates
server_id=2
gtid_strict_mode

Later created one user for replication, and did mysqldump out on one galera node and did an import on slave node.

Then ran on slave:

stop slave; change master to master_host='one galera node name ',master_port=3306,master_user='repl_user',master_password='repl_password',master_use_gtid=current_pos; start slave;

but failed.
The error msg is:

Got fatal error 1236 from master when reading data from binary log:
  'Error: connecting slave requested to start from GTID 0-2-11, which is
  not in the master's binlog'

Do you have any suggestion, if any, very appreciated.

Body:
After researching, I modified the settings I mentioned above:

on each node of the Galera Cluster, they have the same domain id and different server id:

[mysqld]
log_bin
log_slave_updates
gtid_strict_mode
gtid_domain_id=1
server_id=1
 [galera]
wsrep_gtid_mode

on the slave node, slave node has the different domain id and server id:

[mysqld]
binlog_format=ROW
log_bin
log_slave_updates
gtid_domain_id=2
server_id=2

then do mysqldump out and mysql import, last run

change master to master_host='one galera node name',master_port=3306, master_user='repl_user',master_password='aa',master_use_gtid=current_pos;
start slave;

Everything goes well.

When I add database or table or insert data into one table, it can sync to the slave node.


问:
KSQL - drop topic
Is there a way to drop the topic from KSQL? According to github it is possible, and I tried

```<code>DROP TOPIC my-topic
DROP TOPIC "my-topic"
DROP TOPIC 'my-topic'
DROP TOPIC `my-topic`
</code>```

But neither of this commands works. I get message

```<code> Message
-------------------------------------------------------------------------------
 io.confluent.ksql.util.KsqlException: No topic with name true was registered.
</code>```

答:
KSQL topic is different concept than Kafka topic. KSQL topic is an internal concept for KSQL that represents a kafka topic along with metadata about that topic including the topic format.
Since we do not expose KSQL topic externally you should not use it in KSQL statements.
If you wanna delete a kafka topic, you should delete it from kafka. In future we plan to add topic management capability to KSQL.</p>

Title: KSQL - drop topic

Body:
Is there a way to drop the topic from KSQL? According to github it is possible, and I tried

DROP TOPIC my-topic
DROP TOPIC "my-topic"
DROP TOPIC 'my-topic'
DROP TOPIC `my-topic`

But neither of this commands works. I get message

 Message
-------------------------------------------------------------------------------
 io.confluent.ksql.util.KsqlException: No topic with name true was registered.


问:
What does requests do with a proxyDict?
I need an explanation on what requests does with a proxyDict, specifically the following:

1. Does it evenly cycle through all of the proxies in the dictionary?

2. What happens if one of them goes down, will requests be able to handle it, or do I have to?

3. What happens if one gets "banned", will it handle it?

4. If I make a get call in a function, will it still cycle through the proxies evenly?

So if I have a dictionary of proxies like so:

```<code>proxyDict = {
    'https' : 'https://IP1:PORT',
    'https' : 'https://IP2:PORT',
    'https' : 'https://IP3:PORT',
    'https' : 'https://IP4:PORT'
}
</code>```

And I have a get request:

```<code>s = requests.Session()
data = {"Username":"user", "Password":"pass"}
s.get(download_url, proxies = proxyDict, verify=False)
</code>```

Which might be in a function, similarly to this (my question #4):

```<code> def foo(download_url, proxyDict, s):
    s.get(download_url, proxies = proxyDict, verify=False)
</code>```

Also is there any way to print which proxy is currently in use?

答:
1. Does it evenly cycle through all of the proxies in the dictionary?

No it does not. proxies is a dictionary with protocols and proxies, requests uses the proxy that mathes the protocol of the request (if any).

2. What happens if one of them goes down, will requests be able to handle it, or do I have to?

If a proxy is not avaliable for some reason requests will raise an exception, you could catch it.

3. What happens if one gets "banned", will it handle it?

No, but you could detect an ip ban if you check the status code and response body.

4. If I make a get call in a function, will it still cycle through the proxies evenly?

No it won't, see 1.  However you could create a list of proxies and loop over it.

An example:

```<code>def next_proxy(current):
    '''Returns the next item in proxies.'''
    if not proxies:
        return None
    if current not in proxies or current == proxies[-1]:
        return proxies[0]
    return proxies[proxies.index(current)+1]

def bad_response(response, error_message='some message'):
    '''Detects ip ban and other bad responses.'''
    return response.status_code == 403 or error_message in response.text

proxies = [
    {'https':'https://177.131.51.155:53281', 'http':'http://177.131.51.155:53281'},
    {'https':'https://138.197.45.196:8118', 'http':'http://138.197.45.196:8118'},
    {'https':'https://153.146.159.139:8080', 'http':'http://153.146.159.139:8080'},
]

s = requests.Session()
proxy = None
for _ in range(10):
    print("Using proxy:", proxy)
    try:
        r = s.get("http://jsonip.com/", proxies=proxy)
        print(r.text)
        if bad_response(r):
            print("bad response")
            #proxies.remove(proxy)
    except (requests.exceptions.ProxyError, requests.exceptions.ConnectionError):
        print("proxy error")
        proxies.remove(proxy)
    proxy = next_proxy(proxy)
</code>```

Title: What does requests do with a proxyDict?

Body:
I need an explanation on what requests does with a proxyDict, specifically the following:

1. Does it evenly cycle through all of the proxies in the dictionary?

2. What happens if one of them goes down, will requests be able to handle it, or do I have to?

3. What happens if one gets "banned", will it handle it?

4. If I make a get call in a function, will it still cycle through the proxies evenly?

So if I have a dictionary of proxies like so:

proxyDict = {
    'https' : 'https://IP1:PORT',
    'https' : 'https://IP2:PORT',
    'https' : 'https://IP3:PORT',
    'https' : 'https://IP4:PORT'
}

And I have a get request:

s = requests.Session()
data = {"Username":"user", "Password":"pass"}
s.get(download_url, proxies = proxyDict, verify=False)

Which might be in a function, similarly to this (my question #4):

 def foo(download_url, proxyDict, s):
    s.get(download_url, proxies = proxyDict, verify=False)

Also is there any way to print which proxy is currently in use?

Body:
1. Does it evenly cycle through all of the proxies in the dictionary?

No it does not. proxies is a dictionary with protocols and proxies, requests uses the proxy that mathes the protocol of the request (if any).

2. What happens if one of them goes down, will requests be able to handle it, or do I have to?

If a proxy is not avaliable for some reason requests will raise an exception, you could catch it.

3. What happens if one gets "banned", will it handle it?

No, but you could detect an ip ban if you check the status code and response body.

4. If I make a get call in a function, will it still cycle through the proxies evenly?

No it won't, see 1.  However you could create a list of proxies and loop over it.

An example:

def next_proxy(current):
    '''Returns the next item in proxies.'''
    if not proxies:
        return None
    if current not in proxies or current == proxies[-1]:
        return proxies[0]
    return proxies[proxies.index(current)+1]

def bad_response(response, error_message='some message'):
    '''Detects ip ban and other bad responses.'''
    return response.status_code == 403 or error_message in response.text

proxies = [
    {'https':'https://177.131.51.155:53281', 'http':'http://177.131.51.155:53281'},
    {'https':'https://138.197.45.196:8118', 'http':'http://138.197.45.196:8118'},
    {'https':'https://153.146.159.139:8080', 'http':'http://153.146.159.139:8080'},
]

s = requests.Session()
proxy = None
for _ in range(10):
    print("Using proxy:", proxy)
    try:
        r = s.get("http://jsonip.com/", proxies=proxy)
        print(r.text)
        if bad_response(r):
            print("bad response")
            #proxies.remove(proxy)
    except (requests.exceptions.ProxyError, requests.exceptions.ConnectionError):
        print("proxy error")
        proxies.remove(proxy)
    proxy = next_proxy(proxy)


答:
your code buffers it all in memory before sending it to the client, that is both slow (because it doesn't start sending to the client until your download is 100% complete) and memory hungry (because you're putting the entire file in memory at the same time), instead send the file to the client in batches as its being downloaded, then its much faster and doesn't use much memory (because you can free the batch already send to the client). luckily, that is very easy with curl, and even the default mode, but you explicitly tell curl not to do it when you invoke CURLOPT_RETURNTRANSFER, so stop doing that. now curl_exec($ch)  returns a bool instead of a string, and the transfer is  sent to the client in batches, which should solve your memory problem and be much faster. also note that curl_setopt and curl_exec returns bool(false) if there was an error, those errors should not be ignored, thus i suggest you replace them with these error-catching wrappers:

```<code>function ecurl_setopt ( /*resource*/$ch , int $option , /*mixed*/ $value ):bool{
    $ret=curl_setopt($ch,$option,$value);
    if($ret!==true){
        //option should be obvious by stack trace
        throw new RuntimeException ( 'curl_setopt() failed. curl_errno: ' . return_var_dump ( curl_errno ($ch) ).'. curl_error: '.curl_error($ch) );
    }
    return true;
}
function ecurl_exec ( /*resource*/$ch):bool{
    $ret=curl_exec($ch);
    if($ret!==true){
        throw new RuntimeException ( 'curl_exec() failed. curl_errno: ' . return_var_dump ( curl_errno ($ch) ).'. curl_error: '.curl_error($ch) );
    }
    return true;
}

function return_var_dump(/*...*/){
    $args = func_get_args ();
    ob_start ();
    call_user_func_array ( 'var_dump', $args );
    return ob_get_clean ();
}
</code>```

additionally, if the file you're downloading is compressible, and the target server supports it (the vast majority of web servers do), doing curl_setopt($ch,CURLOPT_ENCODING,''); will enable downloading with all compressions that curl was compiled with (usually gzip and deflate), which should make it even faster :)

also note, if you're going to run large number of big, slow, concurrent downloads this way, PHP is simply a bad choice of language performance-wise, each download takes up an entire php process (or in Apache mod_php's case, thread) until the download is complete, and there's usually a very limited amount of php processes allowed to run concurrently, which can block your entire website (i'd write the download proxy in Go myself, Goroutines would be near-perfect for this type of job)

Title: How to use cURL and PHP to redirect big files?

Body:
your code buffers it all in memory before sending it to the client, that is both slow (because it doesn't start sending to the client until your download is 100% complete) and memory hungry (because you're putting the entire file in memory at the same time), instead send the file to the client in batches as its being downloaded, then its much faster and doesn't use much memory (because you can free the batch already send to the client). luckily, that is very easy with curl, and even the default mode, but you explicitly tell curl not to do it when you invoke CURLOPT_RETURNTRANSFER, so stop doing that. now curl_exec($ch)  returns a bool instead of a string, and the transfer is  sent to the client in batches, which should solve your memory problem and be much faster. also note that curl_setopt and curl_exec returns bool(false) if there was an error, those errors should not be ignored, thus i suggest you replace them with these error-catching wrappers:

function ecurl_setopt ( /*resource*/$ch , int $option , /*mixed*/ $value ):bool{
    $ret=curl_setopt($ch,$option,$value);
    if($ret!==true){
        //option should be obvious by stack trace
        throw new RuntimeException ( 'curl_setopt() failed. curl_errno: ' . return_var_dump ( curl_errno ($ch) ).'. curl_error: '.curl_error($ch) );
    }
    return true;
}
function ecurl_exec ( /*resource*/$ch):bool{
    $ret=curl_exec($ch);
    if($ret!==true){
        throw new RuntimeException ( 'curl_exec() failed. curl_errno: ' . return_var_dump ( curl_errno ($ch) ).'. curl_error: '.curl_error($ch) );
    }
    return true;
}

function return_var_dump(/*...*/){
    $args = func_get_args ();
    ob_start ();
    call_user_func_array ( 'var_dump', $args );
    return ob_get_clean ();
}

additionally, if the file you're downloading is compressible, and the target server supports it (the vast majority of web servers do), doing curl_setopt($ch,CURLOPT_ENCODING,''); will enable downloading with all compressions that curl was compiled with (usually gzip and deflate), which should make it even faster :)

also note, if you're going to run large number of big, slow, concurrent downloads this way, PHP is simply a bad choice of language performance-wise, each download takes up an entire php process (or in Apache mod_php's case, thread) until the download is complete, and there's usually a very limited amount of php processes allowed to run concurrently, which can block your entire website (i'd write the download proxy in Go myself, Goroutines would be near-perfect for this type of job)


问:
SQL Add to Existing Table from Temp Table
I'm making a basketball stats database, and have a table in SQL with the player's totals from all of their games combined. I'm having trouble adding to it, however. I use a temporary table for each game, and then I need to add all of the temporary values to the player's total table. How would I do this? I have tried many methods, each of which throw an error. Here are a few:

(live_players is the temporary table, and here I'm only trying to join the points column.)

```<code>db.execute("UPDATE players JOIN live_players AS t1 ON players.player_id
= t1.player_id SET points = points + t1.points")

db.execute("MERGE INTO players USING live_players ON players.player_id
= live_players.player_id WHEN MATCHED THEN UPDATE
SET points = points + live_players.points")
</code>```

答:
I think your update statement is wrong.

You do not have to make a join direct behind the update statement, it has to be put into the FROM clause.

```<code>UPDATE table_to_update
SET what_you_want_to_set
FROM define_the_table(s)
WHERE some_restrictions (maybe with sub select)
</code>```

Have a look here:

How can I do an UPDATE statement with JOIN in SQL?

or here:

SQL update query using joins

Best,

me

Body:
I'm making a basketball stats database, and have a table in SQL with the player's totals from all of their games combined. I'm having trouble adding to it, however. I use a temporary table for each game, and then I need to add all of the temporary values to the player's total table. How would I do this? I have tried many methods, each of which throw an error. Here are a few:

(live_players is the temporary table, and here I'm only trying to join the points column.)

db.execute("UPDATE players JOIN live_players AS t1 ON players.player_id
= t1.player_id SET points = points + t1.points")

db.execute("MERGE INTO players USING live_players ON players.player_id
= live_players.player_id WHEN MATCHED THEN UPDATE
SET points = points + live_players.points")

Body:
I think your update statement is wrong.

You do not have to make a join direct behind the update statement, it has to be put into the FROM clause.

UPDATE table_to_update
SET what_you_want_to_set
FROM define_the_table(s)
WHERE some_restrictions (maybe with sub select)

Have a look here:

How can I do an UPDATE statement with JOIN in SQL?

or here:

SQL update query using joins

Best,

me


问:
Python argparser mutually exclusive with same argument in multiple groups
I use argparser as a generic way to provide inputs on multiple different files, that are used to generate at the end a json, and sent to a database.
Have that said, I want to use multiple mutually exclusive groups, with the option to a flag being part of multiple different groups (as in the example below).

```<code>parser = argparser.argumentParser

group1 = parser.add_mutually_exclusive_group()
group2 = parser.add_mutually_exclusive_group(required=True)
group3 = parser.add_mutually_exclusive_group()

group1.add_argument('-a', type=int)
group1.add_argument('-d', type=int)

group2.add_argument('-z', type=int)
group2.add_argument('-x', type=int)

group3.add_argument('-a', type=int)
group3.add_argument('-z', type=int)
</code>```

it means that -d and -z can go together (but -z or -x are mandatory), giving me the option to have -a -d -x OR -z -d

for some reason, the argparser thinks each one of the -a or -z flags are conflicting, so i have added the conflict_handler to 'resolve', but seems to have no effect

答:
When you add an argument to a group, it is also added to the parser.  Groups, both argument_group and mutually_exclusive_group are ways of defining some special actions (in help and testing), but they don't change the fundamental parsing.

So the arguments you try to define via group3 conflict with the arguments already defined via the other groups.  I should also note that add_argument creates an argument Action object.

For a bug/issue I came up with a way of adding pre existing Actions to a new group.  That is, a way of adding the -a and -z that were created earlier to group3.  Actually I wrote it as a way defining a group with a list of existing Actions.  That wasn't very hard to do.  But displaying such a group required a major rewrite to the usage formatter.

https://bugs.python.org/issue10984

mutually_exclusive_group does 2 things - it modifies the usage - if possible.  And it does the 'mutually-exclusive' test.  Otherwise it does not modify the parsing.  You could perform the same tests after parsing.

In your example, all arguments have a default of None.  So after parsing, you could do:

```<code>if args.a is not None and args.z is not None:
   parse.error('cannot use both -a and -z')
</code>```

In the bug/issue I modified add_mutually_exclusive_group to effectively do:

```<code>group1 = parser.add_mutually_exclusive_group()
group2 = parser.add_mutually_exclusive_group(required=True)

a1 = group1.add_argument('-a', type=int) # hang onto the newly created Action
group1.add_argument('-d', type=int)

a2 = group2.add_argument('-z', type=int)
group2.add_argument('-x', type=int)

group3 = parser.add_mutually_exclusive_group()
group3._group_actions.append(a1)      # add existing Action to group
group3._group_actions.append(a2)
#group3.add_argument('-a', type=int)
#group3.add_argument('-z', type=int)
</code>```

That is, pointers to the existing Actions are added directly to the new group, without going through add_argument.

testing group3:

```<code>2347:~/mypy$ python3 stack47670008.py -z 3 -a3
usage: stack47670008.py [-h] [-a A | -d D] (-z Z | -x X)
stack47670008.py: error: argument -a: not allowed with argument -z

2347:~/mypy$ python3 stack47670008.py -z 3 -d3
Namespace(a=None, d=3, x=None, z=3)

2347:~/mypy$ python3 stack47670008.py -h
usage: stack47670008.py [-h] [-a A | -d D] (-z Z | -x X)

optional arguments:
  -h, --help  show this help message and exit
  -a A
  -d D
  -z Z
  -x X
</code>```

group1 and group2 show up in the usage, but not group3.

Body:
I use argparser as a generic way to provide inputs on multiple different files, that are used to generate at the end a json, and sent to a database.
Have that said, I want to use multiple mutually exclusive groups, with the option to a flag being part of multiple different groups (as in the example below).

parser = argparser.argumentParser

group1 = parser.add_mutually_exclusive_group()
group2 = parser.add_mutually_exclusive_group(required=True)
group3 = parser.add_mutually_exclusive_group()

group1.add_argument('-a', type=int)
group1.add_argument('-d', type=int)

group2.add_argument('-z', type=int)
group2.add_argument('-x', type=int)

group3.add_argument('-a', type=int)
group3.add_argument('-z', type=int)

it means that -d and -z can go together (but -z or -x are mandatory), giving me the option to have -a -d -x OR -z -d

for some reason, the argparser thinks each one of the -a or -z flags are conflicting, so i have added the conflict_handler to 'resolve', but seems to have no effect

Body:
When you add an argument to a group, it is also added to the parser.  Groups, both argument_group and mutually_exclusive_group are ways of defining some special actions (in help and testing), but they don't change the fundamental parsing.

So the arguments you try to define via group3 conflict with the arguments already defined via the other groups.  I should also note that add_argument creates an argument Action object.

For a bug/issue I came up with a way of adding pre existing Actions to a new group.  That is, a way of adding the -a and -z that were created earlier to group3.  Actually I wrote it as a way defining a group with a list of existing Actions.  That wasn't very hard to do.  But displaying such a group required a major rewrite to the usage formatter.

https://bugs.python.org/issue10984

mutually_exclusive_group does 2 things - it modifies the usage - if possible.  And it does the 'mutually-exclusive' test.  Otherwise it does not modify the parsing.  You could perform the same tests after parsing.

In your example, all arguments have a default of None.  So after parsing, you could do:

if args.a is not None and args.z is not None:
   parse.error('cannot use both -a and -z')

In the bug/issue I modified add_mutually_exclusive_group to effectively do:

group1 = parser.add_mutually_exclusive_group()
group2 = parser.add_mutually_exclusive_group(required=True)

a1 = group1.add_argument('-a', type=int) # hang onto the newly created Action
group1.add_argument('-d', type=int)

a2 = group2.add_argument('-z', type=int)
group2.add_argument('-x', type=int)

group3 = parser.add_mutually_exclusive_group()
group3._group_actions.append(a1)      # add existing Action to group
group3._group_actions.append(a2)
#group3.add_argument('-a', type=int)
#group3.add_argument('-z', type=int)

That is, pointers to the existing Actions are added directly to the new group, without going through add_argument.

testing group3:

2347:~/mypy$ python3 stack47670008.py -z 3 -a3
usage: stack47670008.py [-h] [-a A | -d D] (-z Z | -x X)
stack47670008.py: error: argument -a: not allowed with argument -z

2347:~/mypy$ python3 stack47670008.py -z 3 -d3
Namespace(a=None, d=3, x=None, z=3)

2347:~/mypy$ python3 stack47670008.py -h
usage: stack47670008.py [-h] [-a A | -d D] (-z Z | -x X)

optional arguments:
  -h, --help  show this help message and exit
  -a A
  -d D
  -z Z
  -x X

group1 and group2 show up in the usage, but not group3.


问:
JPA repository return type
I have read that JpaRepository methods return a List<MyEntity> when more entities are requested from the database, and CrudRepository (which is a superinterface of JpaRepository) returns a Iterable<MyEntity>.

Why does this happen? Is there any advantage?

答:
I don't know the exact history behind the return types.
But I would day that they have chosen Iterable because this is the super type of the collections and you can use it in for each loops.

In JPA List is the return type of Query.getResultList() so it makes sense to follow the standard.
It's List because the result can be sorted with order by clause.

Hope this helps.

Title: JPA repository return type


问:
gem install returns FloatDomainError Infinity or NaN
On Ubuntu 10.10, I cannot install any gems!

```<code>$ sudo gem install rails
ERROR:  http://rubygems.org/ does not appear to be a repository
ERROR:  Could not find a valid gem 'rails' (>= 0) in any repository
ERROR:  While executing gem ... (Gem::RemoteFetcher::FetchError)
    too many connection resets (http://rubygems.org/latest_specs.4.8.gz)
</code>```

Ok, so the proxy is in the way :-

```<code>$ sudo gem install -p http://username:password@the.proxy.com:8080 rails
ERROR:  While executing gem ... (FloatDomainError)
    NaN
Fetching: activesupport-3.0.3.gem(1)
</code>```

1) This is where it returned the cursor to, not a new line?! It does this on every call below as well.

Get the same with another gem :-

```<code>$ sudo gem install --http-proxy=http://username:password@proxy:8080 twitter
ERROR:  While executing gem ... (FloatDomainError)
    NaN
Fetching: hashie-0.4.0.gem
</code>```

I have tried -p as well!

But myhttp_proxyenv var is setup correctly :-

```<code>$ env | grep http
http_proxy=http://username:password@proxy.com:8080
</code>```

As stuff like this works :-

```<code>$ gem list -r rails

*** REMOTE GEMS ***

rails (3.0.3)
rails-action-args (0.1.1)
rails-admin (0.0.0)
rails-app-installer (0.2.0)
rails-app-spec (0.3.2)
...
</code>```

And all theapt-get&curlcommands go straight though without problems.

Versions :-

```<code>$ ruby -v
ruby 1.8.7 (2010-06-23 patchlevel 299) [i686-linux]

$ which ruby
/usr/bin/ruby
$ whereis ruby
ruby: /usr/bin/ruby1.8 /usr/bin/ruby /usr/lib/ruby /usr/share/man/man1/ruby.1.gz

$ rvm list

rvm rubies

   ree-1.8.7-2010.02 [ i386 ]
   ruby-1.9.2-p136 [ i386 ]

$ rvm -v
rvm 1.2.2 by Wayne E. Seguin (wayneeseguin@gmail.com) [http://rvm.beginrescueend.com/]

$ gem -v
1.4.2

$ which gem
/usr/bin/gem
$ whereis gem
gem: /usr/bin/gem /usr/bin/gem1.8 /usr/share/man/man1/gem.1.gz
</code>```

Any help/ideas?

答:
This appears to be a bug in RubyGems 1.4.2.  See this GemCutter Help page for more details.

If you want to try out the latest build from trunk that fixes this, feel free to checkout Rubygems from source and install manually:

```<code>$> git clone https://github.com/rubygems/rubygems.git
$> cd rubygems
$> ruby setup.rb
$> gem env  // You should see RubyGems 1.5.0 or something similar if you've installed it
$> gem update // or `gem install` or whatever you want to test out
</code>```

Body:
On Ubuntu 10.10, I cannot install any gems!

$ sudo gem install rails
ERROR:  http://rubygems.org/ does not appear to be a repository
ERROR:  Could not find a valid gem 'rails' (>= 0) in any repository
ERROR:  While executing gem ... (Gem::RemoteFetcher::FetchError)
    too many connection resets (http://rubygems.org/latest_specs.4.8.gz)

Ok, so the proxy is in the way :-

$ sudo gem install -p http://username:password@the.proxy.com:8080 rails
ERROR:  While executing gem ... (FloatDomainError)
    NaN
Fetching: activesupport-3.0.3.gem(1)

1) This is where it returned the cursor to, not a new line?! It does this on every call below as well.

Get the same with another gem :-

$ sudo gem install --http-proxy=http://username:password@proxy:8080 twitter
ERROR:  While executing gem ... (FloatDomainError)
    NaN
Fetching: hashie-0.4.0.gem

I have tried -p as well!

But myhttp_proxyenv var is setup correctly :-

$ env | grep http
http_proxy=http://username:password@proxy.com:8080

As stuff like this works :-

$ gem list -r rails

*** REMOTE GEMS ***

rails (3.0.3)
rails-action-args (0.1.1)
rails-admin (0.0.0)
rails-app-installer (0.2.0)
rails-app-spec (0.3.2)
...

And all theapt-get&curlcommands go straight though without problems.

Versions :-

$ ruby -v
ruby 1.8.7 (2010-06-23 patchlevel 299) [i686-linux]

$ which ruby
/usr/bin/ruby
$ whereis ruby
ruby: /usr/bin/ruby1.8 /usr/bin/ruby /usr/lib/ruby /usr/share/man/man1/ruby.1.gz

$ rvm list

rvm rubies

   ree-1.8.7-2010.02 [ i386 ]
   ruby-1.9.2-p136 [ i386 ]

$ rvm -v
rvm 1.2.2 by Wayne E. Seguin (wayneeseguin@gmail.com) [http://rvm.beginrescueend.com/]

$ gem -v
1.4.2

$ which gem
/usr/bin/gem
$ whereis gem
gem: /usr/bin/gem /usr/bin/gem1.8 /usr/share/man/man1/gem.1.gz

Any help/ideas?

Body:
This appears to be a bug in RubyGems 1.4.2.  See this GemCutter Help page for more details.

If you want to try out the latest build from trunk that fixes this, feel free to checkout Rubygems from source and install manually:

$> git clone https://github.com/rubygems/rubygems.git
$> cd rubygems
$> ruby setup.rb
$> gem env  // You should see RubyGems 1.5.0 or something similar if you've installed it
$> gem update // or `gem install` or whatever you want to test out


问:
using python to send json and files to flask
I have this issue where I am trying to send/receive to a flask API some file and JSON in a single function.

On my client ( sender ) I have :

```<code>#my json to be sent
datas = {'var1' : 'var1','var2'  : 'var2',}
#my file to be sent
local_file_to_send = 'user_picture.jpg'
url = "http://10.100.2.6:80/customerupdate"
headers = {'Content-type': 'multipart/form-data'}
files = {'document': open(local_file_to_send, 'rb')}
r = requests.post(url, files=files, data=datas, headers=headers)
</code>```

On my Flask server I have :

```<code>class OPERATIONS(Resource):
        @app.route('/',methods=['GET'])
        def hello_world():
            return 'Hello World!'

        @app.route('/customerupdate',methods=['GET','POST'])
        def customerupdate():
            event_data_2 = json.loads(request.get_data().decode('utf-8'))
            print event_data_2
</code>```

I have this error message telling me that the data is actually not a json format nor a utf8 format. If I print the content of the "get_data" without trying to decode it shows some binary characters..

What would be the syntax on my client to read the json and write the file locally ?

答:
I would recommend sending both the JSON and the file as parts of the multipart form. In that case you would read them from request.files on the server. (One caveat: I tested all my examples with Python 3, requests 2.18.4, and Flask 0.12.2 -- you might need to change the code around to match your environment).

From https://stackoverflow.com/a/35940980/2415176 (and the Flask docs at http://docs.python-requests.org/en/latest/user/advanced/#post-multiple-multipart-encoded-files), you don't need to specify headers or anything. You can just let requests handle it for you:

```<code>import json
import requests

# Ton to be sent
datas = {'var1' : 'var1','var2'  : 'var2',}

#my file to be sent
local_file_to_send = 'tmpfile.txt'
with open(local_file_to_send, 'w') as f:
    f.write('I am a file\n')

url = "http://127.0.0.1:3000/customerupdate"

files = [
    ('document', (local_file_to_send, open(local_file_to_send, 'rb'), 'application/octet')),
    ('datas', ('datas', json.dumps(datas), 'application/json')),
]

r = requests.post(url, files=files)
print(str(r.content, 'utf-8'))
</code>```

Then on the server you can read from request.files (see http://flask.pocoo.org/docs/0.12/api/#flask.Request.files but note that request.files used to work a little differently, see https://stackoverflow.com/a/11817318/2415176):

```<code>import json

from flask import Flask, request

app = Flask(__name__)

@app.route('/',methods=['GET'])
def hello_world():
    return 'Hello World!'

@app.route('/customerupdate',methods=['GET','POST'])
def customerupdate():
    posted_file = str(request.files['document'].read(), 'utf-8')
    posted_data = json.load(request.files['datas'])
    print(posted_file)
    print(posted_data)
    return '{}\n{}\n'.format(posted_file, posted_data)
</code>```

Body:
I have this issue where I am trying to send/receive to a flask API some file and JSON in a single function.

On my client ( sender ) I have :

#my json to be sent
datas = {'var1' : 'var1','var2'  : 'var2',}
#my file to be sent
local_file_to_send = 'user_picture.jpg'
url = "http://10.100.2.6:80/customerupdate"
headers = {'Content-type': 'multipart/form-data'}
files = {'document': open(local_file_to_send, 'rb')}
r = requests.post(url, files=files, data=datas, headers=headers)

On my Flask server I have :

class OPERATIONS(Resource):
        @app.route('/',methods=['GET'])
        def hello_world():
            return 'Hello World!'

        @app.route('/customerupdate',methods=['GET','POST'])
        def customerupdate():
            event_data_2 = json.loads(request.get_data().decode('utf-8'))
            print event_data_2

I have this error message telling me that the data is actually not a json format nor a utf8 format. If I print the content of the "get_data" without trying to decode it shows some binary characters..

What would be the syntax on my client to read the json and write the file locally ?

Body:
I would recommend sending both the JSON and the file as parts of the multipart form. In that case you would read them from request.files on the server. (One caveat: I tested all my examples with Python 3, requests 2.18.4, and Flask 0.12.2 -- you might need to change the code around to match your environment).

From https://stackoverflow.com/a/35940980/2415176 (and the Flask docs at http://docs.python-requests.org/en/latest/user/advanced/#post-multiple-multipart-encoded-files), you don't need to specify headers or anything. You can just let requests handle it for you:

import json
import requests

# Ton to be sent
datas = {'var1' : 'var1','var2'  : 'var2',}

#my file to be sent
local_file_to_send = 'tmpfile.txt'
with open(local_file_to_send, 'w') as f:
    f.write('I am a file\n')

url = "http://127.0.0.1:3000/customerupdate"

files = [
    ('document', (local_file_to_send, open(local_file_to_send, 'rb'), 'application/octet')),
    ('datas', ('datas', json.dumps(datas), 'application/json')),
]

r = requests.post(url, files=files)
print(str(r.content, 'utf-8'))

Then on the server you can read from request.files (see http://flask.pocoo.org/docs/0.12/api/#flask.Request.files but note that request.files used to work a little differently, see https://stackoverflow.com/a/11817318/2415176):

import json

from flask import Flask, request

app = Flask(__name__)

@app.route('/',methods=['GET'])
def hello_world():
    return 'Hello World!'

@app.route('/customerupdate',methods=['GET','POST'])
def customerupdate():
    posted_file = str(request.files['document'].read(), 'utf-8')
    posted_data = json.load(request.files['datas'])
    print(posted_file)
    print(posted_data)
    return '{}\n{}\n'.format(posted_file, posted_data)


问:
Xcode 8 Adding Layout Margins Crash
When I try to add layout margins to a label on a TableViewCell, using the right panel on Xcode, I try to add Explicit Margins (top, Left, Bottom, Right). But, as soon as I input a number value, or tap the arrow to change the value, Xcode crashes.

I've attached a photo to show the panel I am trying to add the layout margins in, and where it crashes.

Any ideas why it wont let me adjust the margins?

答: Clear all the constraints and try from applying one by one.and take .xib file and connecte with Table view Cell</p>

Title: Xcode 8 Adding Layout Margins Crash


问:
python: Inserting JSON data into dataframe
```<code>{
"total_count": 2316913,
"incomplete_results": false,
"items": [
    {
        "id": 13737149,
        "name": "gremlins.js",
        "full_name": "marmelab/gremlins.js",
        "owner": {
            "login": "marmelab",
            "id": 3116319,
            "avatar_url": "https://avatars1.githubusercontent.com/u/3116319?v=4",
            "gravatar_id": "",
            "url": "https://api.github.com/users/marmelab",
            "html_url": "https://github.com/marmelab",
            "followers_url": "https://api.github.com/users/marmelab/followers",
            "following_url": "https://api.github.com/users/marmelab/following{/other_user}",
            "gists_url": "https://api.github.com/users/marmelab/gists{/gist_id}",
            "starred_url": "https://api.github.com/users/marmelab/starred{/owner}{/repo}",
            "subscriptions_url": "https://api.github.com/users/marmelab/subscriptions",
            "organizations_url": "https://api.github.com/users/marmelab/orgs",
            "repos_url": "https://api.github.com/users/marmelab/repos",
            "events_url": "https://api.github.com/users/marmelab/events{/privacy}",
            "received_events_url": "https://api.github.com/users/marmelab/received_events",
            "type": "Organization",
            "site_admin": false
        },
</code>```

The above is data from the Github search API. What I am attempting to do is pull certain fields out and insert it into a dataframe.

Using a standard for loop like:

```<code>for i in jdata['items']:
  print(i['name']  + "\t" + i['html_url'])
</code>```

prints the data I need, but, its ugly, hard to read, and since I have more things to extract, I am at a stopping point.

```<code>url = "https://api.github.com/search/repositories?q={}".format(sTerm)
jdata = requests.get(url).json()
</code>```

I am using this to get input from the user, and storing the results in jdata.

Dataframes are new to me, and it seems that no matter what I try, it either displays everything in the search results, or nothing. Not sure what I'm doing wrong. (I know I didn't paste any dataframe code, nothing is working, so I figured I'd save everyone the eye cancer.)

答:
It sounds like you want to do something like

```<code>import pandas as pd
df = pd.DataFrame(jdata['items'], columns=['name', 'html_url'])
</code>```

For example, if sTerm is 'hest',

```<code>In [15]: pd.DataFrame(jdata['items'], columns=['name', 'html_url'])
Out[15]:
                 name                                        html_url
0                Hest           https://github.com/MegaCakeEater/Hest
1              heston           https://github.com/daleroberts/heston
2   NotoSansKR-Hestia  https://github.com/theeluwin/NotoSansKR-Hestia
3                hest                https://github.com/mastensg/hest
4              Heston                https://github.com/jcfrei/Heston
5                Hest           https://github.com/abirk2thebone/Hest
6                Hest                   https://github.com/h6899/Hest
7                Hest                  https://github.com/hsurce/Hest
8                hest                   https://github.com/kmajo/hest
</code>```

Body:
{
"total_count": 2316913,
"incomplete_results": false,
"items": [
    {
        "id": 13737149,
        "name": "gremlins.js",
        "full_name": "marmelab/gremlins.js",
        "owner": {
            "login": "marmelab",
            "id": 3116319,
            "avatar_url": "https://avatars1.githubusercontent.com/u/3116319?v=4",
            "gravatar_id": "",
            "url": "https://api.github.com/users/marmelab",
            "html_url": "https://github.com/marmelab",
            "followers_url": "https://api.github.com/users/marmelab/followers",
            "following_url": "https://api.github.com/users/marmelab/following{/other_user}",
            "gists_url": "https://api.github.com/users/marmelab/gists{/gist_id}",
            "starred_url": "https://api.github.com/users/marmelab/starred{/owner}{/repo}",
            "subscriptions_url": "https://api.github.com/users/marmelab/subscriptions",
            "organizations_url": "https://api.github.com/users/marmelab/orgs",
            "repos_url": "https://api.github.com/users/marmelab/repos",
            "events_url": "https://api.github.com/users/marmelab/events{/privacy}",
            "received_events_url": "https://api.github.com/users/marmelab/received_events",
            "type": "Organization",
            "site_admin": false
        },

The above is data from the Github search API. What I am attempting to do is pull certain fields out and insert it into a dataframe.

Using a standard for loop like:

for i in jdata['items']:
  print(i['name']  + "\t" + i['html_url'])

prints the data I need, but, its ugly, hard to read, and since I have more things to extract, I am at a stopping point.

url = "https://api.github.com/search/repositories?q={}".format(sTerm)
jdata = requests.get(url).json()

I am using this to get input from the user, and storing the results in jdata.

Dataframes are new to me, and it seems that no matter what I try, it either displays everything in the search results, or nothing. Not sure what I'm doing wrong. (I know I didn't paste any dataframe code, nothing is working, so I figured I'd save everyone the eye cancer.)

Body:
It sounds like you want to do something like

import pandas as pd
df = pd.DataFrame(jdata['items'], columns=['name', 'html_url'])

For example, if sTerm is 'hest',

In [15]: pd.DataFrame(jdata['items'], columns=['name', 'html_url'])
Out[15]:
                 name                                        html_url
0                Hest           https://github.com/MegaCakeEater/Hest
1              heston           https://github.com/daleroberts/heston
2   NotoSansKR-Hestia  https://github.com/theeluwin/NotoSansKR-Hestia
3                hest                https://github.com/mastensg/hest
4              Heston                https://github.com/jcfrei/Heston
5                Hest           https://github.com/abirk2thebone/Hest
6                Hest                   https://github.com/h6899/Hest
7                Hest                  https://github.com/hsurce/Hest
8                hest                   https://github.com/kmajo/hest


问:
How to send files with Sinch Instant Message?
I am developing a chat app and I am using Sinch SDK for JavaScript. My question is simple.

How can I send files through the Instant Message, to another user that I am chatting with?

答:
Sinch until now supported text only , therefore you can benefit from texting attachments between two devices.

Make your own API to upload files to your server when uploading is successfully done you can send json object to sinch client to tell him an file send successfully like this

```<code>{ "type":"image" , "value":"<your-url-image-in-your-server>"}
</code>```

The receiver device can fetch this message and convert it from text to json object and receive the file from value attribute.

And you can do same for any type of files (Images - Sound - PDF ...etc).

I hope to help any one to use Sinch for sending attachments.

Body:
Sinch until now supported text only , therefore you can benefit from texting attachments between two devices.

Make your own API to upload files to your server when uploading is successfully done you can send json object to sinch client to tell him an file send successfully like this

{ "type":"image" , "value":"<your-url-image-in-your-server>"}

The receiver device can fetch this message and convert it from text to json object and receive the file from value attribute.

And you can do same for any type of files (Images - Sound - PDF ...etc).

I hope to help any one to use Sinch for sending attachments.


问:
css being applied to all elements in array
When I run this function the CSS is being applied to all the buttons. How do I modify so that the CSS only gets modified for the buttons where the buttonAttr attribute equals disabled?</p>

```<code>$('.product_tile .addtocartbutton').each(function(){
    var $this = $(this);
    var buttonAttr = $this.attr('disabled');

    if($this.attr('disabled') = 'disabled'){
        $this.css('background','#ccc');
    } else {
        $this.css('background','#EEDED1');
    }
});
</code>```

答:
You need double or triple equal signs to do a comparison.</p>

```<code> if($this.buttonAttr == 'disabled')
</code>```

Body:
When I run this function the CSS is being applied to all the buttons. How do I modify so that the CSS only gets modified for the buttons where the buttonAttr attribute equals disabled?

$('.product_tile .addtocartbutton').each(function(){
    var $this = $(this);
    var buttonAttr = $this.attr('disabled');

    if($this.attr('disabled') = 'disabled'){
        $this.css('background','#ccc');
    } else {
        $this.css('background','#EEDED1');
    }
});

Body:
You need double or triple equal signs to do a comparison.

 if($this.buttonAttr == 'disabled')


问:
How to write less code for a long if-else statement in Scala (code review)
I have the following code:

```<code>  def updateProgrammcounter(element: Name) {
    val level = findSecurityLevelOfNameInSymboltable(element.toString.trim)
    var pc = new HashSet[String]
    println("LEVEL: " + level)
    if (pc.isEmpty && level != "N") {
      // the pc is empty so add the level
      pc += level
    } else if (pc.contains("H") && level == "L") {
      // giving high information to low is not allowed
      errorReject()
    } else if (pc.contains("L") && level == "L") {
      // nothing to change because the pc is the same
      println("okay")
    } else if (pc.contains("H") && level == "H") {
      println("okay")
    } else if (pc.contains("L") && level == "H")
      // we have to raise the pc
    pc += level
    else if (level == "N") {
      println("We have a not valid operation!")
    } else {
      println("Something went terribly wrong!")
    }
  }
</code>```

Do you see some level of enhancement I can do, so that this big chunk of code looks just better. Thanks for your advise, Matthias.

答:
You can certainly rearrange this into levels, then pc:

```<code>def updateProgrammcounter(element: Name) {
    val level = findSecurityLevelOfNameInSymboltable(element.toString.trim)
    var pc = new HashSet[String]
    println("LEVEL: " + level)
    if (level == "L") {
    } else if (level == "H") {
        // All the "H" stuff in here
    } else {
       // Put the "N" case at the top here - it looks like your fall through default.
    }
  }
</code>```

For the other items, perhaps you can use a Map with pc as the key and behavior functions as the values.

This might suggest that you could have L and H updater objects that you could look up using the level.

You can also combine level and pc into the key in a Map and lookup what you'd like to do.

Your instinct is good: when you see long if/then/else, you should think about polymorphism or lookups to simplify it.  Think how you could modify the flow by adding objects rather than rewriting code (open/closed principle).

Body:
I have the following code:

  def updateProgrammcounter(element: Name) {
    val level = findSecurityLevelOfNameInSymboltable(element.toString.trim)
    var pc = new HashSet[String]
    println("LEVEL: " + level)
    if (pc.isEmpty && level != "N") {
      // the pc is empty so add the level
      pc += level
    } else if (pc.contains("H") && level == "L") {
      // giving high information to low is not allowed
      errorReject()
    } else if (pc.contains("L") && level == "L") {
      // nothing to change because the pc is the same
      println("okay")
    } else if (pc.contains("H") && level == "H") {
      println("okay")
    } else if (pc.contains("L") && level == "H")
      // we have to raise the pc
    pc += level
    else if (level == "N") {
      println("We have a not valid operation!")
    } else {
      println("Something went terribly wrong!")
    }
  }

Do you see some level of enhancement I can do, so that this big chunk of code looks just better. Thanks for your advise, Matthias.

Body:
You can certainly rearrange this into levels, then pc:

def updateProgrammcounter(element: Name) {
    val level = findSecurityLevelOfNameInSymboltable(element.toString.trim)
    var pc = new HashSet[String]
    println("LEVEL: " + level)
    if (level == "L") {
    } else if (level == "H") {
        // All the "H" stuff in here
    } else {
       // Put the "N" case at the top here - it looks like your fall through default.
    }
  }

For the other items, perhaps you can use a Map with pc as the key and behavior functions as the values.

This might suggest that you could have L and H updater objects that you could look up using the level.

You can also combine level and pc into the key in a Map and lookup what you'd like to do.

Your instinct is good: when you see long if/then/else, you should think about polymorphism or lookups to simplify it.  Think how you could modify the flow by adding objects rather than rewriting code (open/closed principle).


问:
Initializing array inside struct
I'm trying to initialize an array inside a struct, Like this.

I want the array to have the size of row*col.

Here is part of the code:

```<code>struct tbl{
    int col;
    int row;
    char** elem [col*row];
};

int main(int argc, char** argv){

    int i, row, col;
    col = row = 0;
    bool loop = true;
    char c;
    col = col/row;

    table tab;
    tab.row = row;
    tab.col = col;

    return 0;
}
</code>```

答:
There are few of errors in the code. You probably want something posted below. Also, don't divide by zero. </p>

```<code>struct tbl{
    int col;
    int row;
    // char** elem [col*row]; // can't initialize array size this way
    char** elem;
};

int main(int argc, char** argv){

    int i, row, col;
    col = row = 0;
    bool loop = true;
    char c;           // Unused?
    col = col/row;    // zero divided by zero? You sure you want that?

    // table tab;        // not defined correctly, Use next line instead
    struct tbl tab;
    tab.row = row;
    tab.col = col;

    tab.elem = malloc(sizeof(char*)*tab.row);
    for (i=0 ; i<tab.row ; i++) {
        tab.elem[i] = malloc(sizeof(char)*tab.col);
        /* initalize tab.elem[i] */
    }

    /* ... do stuff */

    // free memory
    for (i=0 ; i<tab.row ; i++) {
        free(tab.elem[i]);
    }
    free(tab.elem);

    return 0;
}
</code>```

Title: Initializing array inside struct

Body:
I'm trying to initialize an array inside a struct, Like this.

I want the array to have the size of row*col.

Here is part of the code:

struct tbl{
    int col;
    int row;
    char** elem [col*row];
};

int main(int argc, char** argv){

    int i, row, col;
    col = row = 0;
    bool loop = true;
    char c;
    col = col/row;

    table tab;
    tab.row = row;
    tab.col = col;

    return 0;
}

Body:
There are few of errors in the code. You probably want something posted below. Also, don't divide by zero.

struct tbl{
    int col;
    int row;
    // char** elem [col*row]; // can't initialize array size this way
    char** elem;
};

int main(int argc, char** argv){

    int i, row, col;
    col = row = 0;
    bool loop = true;
    char c;           // Unused?
    col = col/row;    // zero divided by zero? You sure you want that?

    // table tab;        // not defined correctly, Use next line instead
    struct tbl tab;
    tab.row = row;
    tab.col = col;

    tab.elem = malloc(sizeof(char*)*tab.row);
    for (i=0 ; i<tab.row ; i++) {
        tab.elem[i] = malloc(sizeof(char)*tab.col);
        /* initalize tab.elem[i] */
    }

    /* ... do stuff */

    // free memory
    for (i=0 ; i<tab.row ; i++) {
        free(tab.elem[i]);
    }
    free(tab.elem);

    return 0;
}


问:
Is there a way to update the same line in F# interactive using printf?

Hello everyone!

I am using F# in Visual Studio Community 2017 for scripting. Im handling large datasets, over which i often loop using recursvive functions. To have a rough idea how long this will take, I am currently using printfn to print the current iteration index. Although i guess this sounds (and is) trivial, here is an example:

```<code>let foo f bar maxIter =
    let rec loop currentIter resultList=
        if currentIter<maxIter then
            printfn "current Iteration: %i" currentIter
            loop (currentIter+1) ((f bar)::resultList)
        else
            List.rev resultList
    loop 0 []
</code>```

This is really cluttering the fsi window, and it is impossible to follow if I additionally print other strings on different steps in a bigger function.

My Question is the following: can i somehow update just one line in fsi with the current iteration number? I have tried using printf and a carriage return:

```<code>printf "%i\r"
</code>```

but this has the same result as using printfn.

Thanks in advance for your help!

Edit: As commenters on this thread pointed out, there currently seems to be no way to do this in VS FSI.

答:
A (self-contained) iteration counter could be implemeted by setting the cursor position:

```<code>let rec progress i : unit =
    printf "%i" i
    System.Threading.Thread.Sleep 1000
    System.Console.SetCursorPosition(0, System.Console.CursorTop)
    progress (i+1)

progress 0
</code>```

Note 1: This will overwrite whatever is on the current line, i.e. other log output will be overwritten unless you implement some synchronization means or always use printfn except for the progress. This behaviour can be observed by:

```<code>open System
open System.Threading

let rec progress i p : unit =
    printf "%s %i" p i
    Thread.Sleep 1000
    Console.SetCursorPosition(0, Console.CursorTop)
    progress (i+1) p

Tasks.Task.Run(fun () -> progress 0 "t1")
Thread.Sleep 500
Tasks.Task.Run(fun () -> progress 0 "t2")
</code>```

Note 2: Due to VS limitations this will not work in VisualStudio FSI. It does work in VS Code, the console (compiled to EXE, running CMD or PowerShell) or using non-VS FSI though (tested on Windows 10, VS 15.5.1).

Body:
Hello everyone!

I am using F# in Visual Studio Community 2017 for scripting. Im handling large datasets, over which i often loop using recursvive functions. To have a rough idea how long this will take, I am currently using printfn to print the current iteration index. Although i guess this sounds (and is) trivial, here is an example:

let foo f bar maxIter =
    let rec loop currentIter resultList=
        if currentIter<maxIter then
            printfn "current Iteration: %i" currentIter
            loop (currentIter+1) ((f bar)::resultList)
        else
            List.rev resultList
    loop 0 []

This is really cluttering the fsi window, and it is impossible to follow if I additionally print other strings on different steps in a bigger function.

My Question is the following: can i somehow update just one line in fsi with the current iteration number? I have tried using printf and a carriage return:

printf "%i\r"

but this has the same result as using printfn.

Thanks in advance for your help!

Edit: As commenters on this thread pointed out, there currently seems to be no way to do this in VS FSI.

Body:
A (self-contained) iteration counter could be implemeted by setting the cursor position:

let rec progress i : unit =
    printf "%i" i
    System.Threading.Thread.Sleep 1000
    System.Console.SetCursorPosition(0, System.Console.CursorTop)
    progress (i+1)

progress 0

Note 1: This will overwrite whatever is on the current line, i.e. other log output will be overwritten unless you implement some synchronization means or always use printfn except for the progress. This behaviour can be observed by:

open System
open System.Threading

let rec progress i p : unit =
    printf "%s %i" p i
    Thread.Sleep 1000
    Console.SetCursorPosition(0, Console.CursorTop)
    progress (i+1) p

Tasks.Task.Run(fun () -> progress 0 "t1")
Thread.Sleep 500
Tasks.Task.Run(fun () -> progress 0 "t2")

Note 2: Due to VS limitations this will not work in VisualStudio FSI. It does work in VS Code, the console (compiled to EXE, running CMD or PowerShell) or using non-VS FSI though (tested on Windows 10, VS 15.5.1).


问:
Get list of numbers from SQL server and use it to get unique values from pandas dataframe
I am trying to do the following:

I have a pandas dataframe 'df' with 20 columns. 'ISBN-13' is one of them.

Our SQL server database 'Book_records' has a table with 'Isbn13' column containing the IDs similar to 'ISBN-13' in the pandas dataframe.

My goal is to get the records(rows) from the pandas dataframe which are not present in our SQL server database

I tried doing this:

Get a list of 'Isbn13' numbers from my SQL database into pandas using the following.

```<code>cnxn = pyodbc.connect(driver='{SQL Server}', host=server, database=db1,trusted_connection=tcon)
cursor = cnxn.cursor()
cursor.execute("SELECT distinct(DBF.Isbn13) FROM Book_records as DBF")
isbn13_list = cursor.fetchall()
</code>```

Then using this list, compare it with the pandas dataframe ISBN-13 values eliminate those that are already present in our database.
However, when I run this. I am getting, what I think is a list of list as follows

```<code>isbn13_list[1:4]
[(u'9780004707631', ), (u'9780004812595', ), (u'9780006485131', )]
</code>```

My pandas dataframe column is as follows: Name: ISBN-13, Length: 821, dtype: float64 and will have elements like 9780004707631.0

When I run the following program to get the new values not present it our database, I get all the values which is wrong (I checked I should get 200 less values)

```<code>Final_df = df[~df['ISBN-13'].isin(isbn13_list)]
</code>```

What am I doing wrong? Also, should I convert ISBN-13 in my df to int or anything else?

答:
This was a workaround I was able to do. It was quite quick that what all I previously tried. It might not be optimal so sorry for that.</p>

```<code>cnxn = pyodbc.connect(driver='{SQL Server}', host=server, database=db1,trusted_connection=tcon)
cursor = cnxn.cursor()
cursor.execute("SELECT distinct(DBF.Isbn13) FROM Book_records as DBF")
isbn13_list = pd.DataFrame.from_records(cursor.fetchall(),columns=['isbn13'])
isbn13_list = isbn13_list['isbn13'].astype('int64')
Final_df = condition_df[~condition_df['ISBN-13'].isin(isbn13_list)]
</code>```

Body:
I am trying to do the following:

I have a pandas dataframe 'df' with 20 columns. 'ISBN-13' is one of them.

Our SQL server database 'Book_records' has a table with 'Isbn13' column containing the IDs similar to 'ISBN-13' in the pandas dataframe.

My goal is to get the records(rows) from the pandas dataframe which are not present in our SQL server database

I tried doing this:

Get a list of 'Isbn13' numbers from my SQL database into pandas using the following.

cnxn = pyodbc.connect(driver='{SQL Server}', host=server, database=db1,trusted_connection=tcon)
cursor = cnxn.cursor()
cursor.execute("SELECT distinct(DBF.Isbn13) FROM Book_records as DBF")
isbn13_list = cursor.fetchall()

Then using this list, compare it with the pandas dataframe ISBN-13 values eliminate those that are already present in our database.
However, when I run this. I am getting, what I think is a list of list as follows

isbn13_list[1:4]
[(u'9780004707631', ), (u'9780004812595', ), (u'9780006485131', )]

My pandas dataframe column is as follows: Name: ISBN-13, Length: 821, dtype: float64 and will have elements like 9780004707631.0

When I run the following program to get the new values not present it our database, I get all the values which is wrong (I checked I should get 200 less values)

Final_df = df[~df['ISBN-13'].isin(isbn13_list)]

What am I doing wrong? Also, should I convert ISBN-13 in my df to int or anything else?

Body:
This was a workaround I was able to do. It was quite quick that what all I previously tried. It might not be optimal so sorry for that.

cnxn = pyodbc.connect(driver='{SQL Server}', host=server, database=db1,trusted_connection=tcon)
cursor = cnxn.cursor()
cursor.execute("SELECT distinct(DBF.Isbn13) FROM Book_records as DBF")
isbn13_list = pd.DataFrame.from_records(cursor.fetchall(),columns=['isbn13'])
isbn13_list = isbn13_list['isbn13'].astype('int64')
Final_df = condition_df[~condition_df['ISBN-13'].isin(isbn13_list)]