问:
CSV writer writes set to a single row rather than multiple rows
I am working on a web scraper for class.  I basically have to compile all of the http links from a website and write them to a csv. They also need to be de-duplicated which is why I'm using a set.  I have all the parts complete expect when it writes to the csv, the entire set of links writes to a single row rather than one link per row. Can someone review my code and tell me what i'm missing?  I cannot find a solution anywhere.

My code is below:

```<code>from bs4 import BeautifulSoup
import requests
import csv
import urllib.parse

base_url = 'https://www.census.gov'

l = set()

r = requests.get("https://www.census.gov/programs-surveys/popest.html")
c = r.content

soup = BeautifulSoup(c, 'html.parser')

file = open('c996webscraper_writer.csv', 'w', newline="")

for link in soup.findAll('a'):
    output = link.get('href')
    abs_url = urllib.parse.urljoin(base_url, output)
    l.add(abs_url)

with file:
    write = csv.writer(file, delimiter = ',', lineterminator = '\r')
    write.writerow(['List of Links'])
    write.writerows([l])

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

This is a printout of what's happening:

CSV Image

答:
```<code>from bs4 import BeautifulSoup
import requests
import csv
import urllib.parse

base_url = 'https://www.census.gov'

l = list()

r = requests.get("https://www.census.gov/programs-surveys/popest.html")
c = r.content

soup = BeautifulSoup(c, 'html.parser')

file = open('c996webscraper_writer.csv', 'w', newline="")

for link in soup.findAll('a'):
    output = link.get('href')
    abs_url = urllib.parse.urljoin(base_url, output)
    l.append(abs_url)

with file:
    write = csv.writer(file)
    write.writerow(['List of Links'])
    for x in l:
        write.writerow([x])

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

Body:
I am working on a web scraper for class.  I basically have to compile all of the http links from a website and write them to a csv. They also need to be de-duplicated which is why I'm using a set.  I have all the parts complete expect when it writes to the csv, the entire set of links writes to a single row rather than one link per row. Can someone review my code and tell me what i'm missing?  I cannot find a solution anywhere.

My code is below:

from bs4 import BeautifulSoup
import requests
import csv
import urllib.parse

base_url = 'https://www.census.gov'

l = set()

r = requests.get("https://www.census.gov/programs-surveys/popest.html")
c = r.content

soup = BeautifulSoup(c, 'html.parser')

file = open('c996webscraper_writer.csv', 'w', newline="")

for link in soup.findAll('a'):
    output = link.get('href')
    abs_url = urllib.parse.urljoin(base_url, output)
    l.add(abs_url)

with file:
    write = csv.writer(file, delimiter = ',', lineterminator = '\r')
    write.writerow(['List of Links'])
    write.writerows([l])

file.close()

This is a printout of what's happening:

CSV Image


来源: stackexchange

问:
Value in "word" makes no difference to my if statement
I am on day 4 of learning python so I apologize in advance if I am missing something very obvious.

The entire program is posted below. word = input() no matter what I type into the input prompt my tree function will not be called. However if I change: if word == 'Chris' or 'j': to if word == 'Chris': it seems to work.

```<code>def tree(pine):
    return 'Hello' + pine

def app():
    word = input()
    if word == 'Chris' or 'j':
        print('Welcome ' + word + ' it is nice today! ', end='')
        print('It is so sunny')
    else:
        print(tree('lplp'))

app()
</code>```

答:
The problem lies with

    if word == 'Chris' or 'j':
```

<p>If we break down this statement, you're evaluating two conditions:</p>

<ol>
<li><code>word == 'Chris'</code></li>
<li><code>'j'</code></li>
</ol>

<p>So Python is a funny language because pretty much any kind of object can be evaluated as a boolean. This means when you check <code>if 'j'</code>, that actually comes out as <code>True</code> instead of some sort of error because Python does a lot of stuff behind the scenes.</p>

<p>To fix the issue you just want to make sure you're checking that <code>word == "j"</code>.</p>

<p>Just to get you started, for example, here are some common python boolean evals:</p>

<pre class="lang-py prettyprint-override"><code>>>> bool("")
False
>>> bool("j")
True
>>> bool(0)
False
>>> bool(69)
True
>>> bool([])
False
>>> bool(["hello", "world"])
True
>>> class Foo:

    def __init__(self):
        self.x = "y"

>>> bool(Foo())
True
>>> bool(None)
False
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I am on day 4 of learning python so I apologize in advance if I am missing something very obvious.

The entire program is posted below. word = input() no matter what I type into the input prompt my tree function will not be called. However if I change: if word == 'Chris' or 'j': to if word == 'Chris': it seems to work.

def tree(pine):
    return 'Hello' + pine

def app():
    word = input()
    if word == 'Chris' or 'j':
        print('Welcome ' + word + ' it is nice today! ', end='')
        print('It is so sunny')
    else:
        print(tree('lplp'))

app()

Body:
The problem lies with

    if word == 'Chris' or 'j':

If we break down this statement, you're evaluating two conditions:

word == 'Chris'

'j'

So Python is a funny language because pretty much any kind of object can be evaluated as a boolean. This means when you check if 'j', that actually comes out as True instead of some sort of error because Python does a lot of stuff behind the scenes.

To fix the issue you just want to make sure you're checking that word == "j".

Just to get you started, for example, here are some common python boolean evals:

>>> bool("")
False
>>> bool("j")
True
>>> bool(0)
False
>>> bool(69)
True
>>> bool([])
False
>>> bool(["hello", "world"])
True
>>> class Foo:

    def __init__(self):
        self.x = "y"

>>> bool(Foo())
True
>>> bool(None)
False


问:
Detect cycles in a genealogy graph during a Depth-first search
I'm loading horse genealogical data recursively.
For some wrong sets of data my recursion never stops... and that is because  there are cycles in the data.

How can I detect those cycles to stop recurring?

I thought of while recurring maintain a hashTable with all "visited" horses.
But that will find some false positives, because a horse CAN be twice in a tree.

What cannot happen is that a horse appear as a father or grandfather or great grandfather of ITSELF.

答:
Maintain a stack of all elements leading up to the root of the tree.

Every time you advance down the tree, scan the stack for the child element. If you find a match, then you've discovered a loop and should skip that child. Otherwise, push the child onto the stack and proceed. Whenever you backtrack up the tree, pop an element out of the stack and discard.

(In the case of genealogical data, a "child" node in the tree is presumably the biological parent of the "parent" node.)

OwnerDisplayName: Romias

ContentLicense: CC BY-SA 3.0

OwnerDisplayName: Matthew

ContentLicense: CC BY-SA 2.5


问:
Pretty Git branch graphs
I've seen some books and articles have some really pretty looking graphs of Git branches and commits. How can I make high-quality printable images of Git history?</p>

答:
For more detailed textual output, try:

```<code>git log --graph --date-order -C -M --pretty=format:"<%h> %ad [%an] %Cgreen%d%Creset %s" --all --date=short
</code>```

You can add an alias in file $HOME/.gitconfig:

```<code>[alias]
    graph = log --graph --date-order -C -M --pretty=format:\"<%h> %ad [%an] %Cgreen%d%Creset %s\" --all --date=short
</code>```

Title: Pretty Git branch graphs

Body:
For more detailed textual output, try:

git log --graph --date-order -C -M --pretty=format:"<%h> %ad [%an] %Cgreen%d%Creset %s" --all --date=short

You can add an alias in file $HOME/.gitconfig:

[alias]
    graph = log --graph --date-order -C -M --pretty=format:\"<%h> %ad [%an] %Cgreen%d%Creset %s\" --all --date=short


问:
I don't know how to use codeblocks win32 gui
I used win32 GUI and managed to make some sort of interface after some googling but i don't know how to make a button do something or to make an integer get value from a textbox in the GUI.

This is the main

```<code>#include <windows.h>
#include <commctrl.h>
#include <stdio.h>
#include "resource.h"

HINSTANCE hInst;

BOOL CALLBACK DlgMain(HWND hwndDlg, UINT uMsg, WPARAM wParam, LPARAM lParam)
{
    switch(uMsg)
    {
    case WM_INITDIALOG:
    {
    }
    return TRUE;

    case WM_CLOSE:
    {
        EndDialog(hwndDlg, 0);
    }
    return TRUE;

    case WM_COMMAND:
    {
        switch(LOWORD(wParam))
        {
        }
    }
    return TRUE;
    }
    return FALSE;
}

int APIENTRY WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nShowCmd)
{
    hInst=hInstance;
    InitCommonControls();
    return DialogBox(hInst, MAKEINTRESOURCE(DLG_MAIN), NULL, (DLGPROC)DlgMain);
}
</code>```

This is the resource.rc

```<code>
#include <windows.h>
#include <commctrl.h>
#include <richedit.h>
#include "resource.h"

//
// Dialog resources
//
LANGUAGE LANG_NEUTRAL, SUBLANG_NEUTRAL
DLG_MAIN DIALOG 0, 0, 125, 64
STYLE DS_3DLOOK | DS_CENTER | DS_MODALFRAME | DS_SHELLFONT | WS_CAPTION | WS_VISIBLE | WS_POPUP | WS_SYSMENU
CAPTION "Numar Factorial"
FONT 8, "Ms Shell Dlg"
{
    EDITTEXT        0, 82, 10, 23, 16, ES_AUTOHSCROLL, WS_EX_LEFT
    LTEXT           "Introdu numarul\r\n", 0, 20, 13, 50, 17, SS_LEFT, WS_EX_LEFT
    PUSHBUTTON      "Confirma\r\n", 0, 40, 34, 45, 14, 0, WS_EX_LEFT
}

//
// Manifest resources
//
LANGUAGE LANG_NEUTRAL, SUBLANG_NEUTRAL
1                  RT_MANIFEST    ".\\manifest.xml"
</code>```

Resource.h

```<code>#ifndef IDC_STATIC
#define IDC_STATIC (-1)
#endif

#define DLG_MAIN                                100
</code>```

manifest.xml

```<code><?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<assembly xmlns="urn:schemas-microsoft-com:asm.v1" manifestVersion="1.0">
  <dependency>
    <dependentAssembly>
      <assemblyIdentity type="win32" name="Microsoft.Windows.Common-Controls" version="6.0.0.0" processorArchitecture="*" publicKeyToken="6595b64144ccf1df" language="*"/>
    </dependentAssembly>
  </dependency>
  <trustInfo xmlns="urn:schemas-microsoft-com:asm.v3">
    <security>
      <requestedPrivileges>
        <requestedExecutionLevel
          level="asInvoker"
          uiAccess="false"/>
      </requestedPrivileges>
    </security>
  </trustInfo>
</assembly>
</code>```

This is the main GUI
It says Factorial number, Insert a number and confirm and i want the program to take a number through that text box and after you hit confirm it returns the factorial of that number.
I need to figure out how to make the buttons do things cause i'm a beginner and my project is due in 2 days.Please help.

答:
You PUSHBUTTON needs a control id.  Instead of this:

```<code>PUSHBUTTON      "Confirma\r\n", 0, 40, 34, 45, 14, 0, WS_EX_LEFT
</code>```

This:

```<code>PUSHBUTTON      "Confirma\r\n", IDC_BUTTON1, 40, 34, 45, 14, 0, WS_EX_LEFT
</code>```

Where IDC_BUTTON1 is an id in your resource.h file.  (e.g. #define IDC_BUTTON1 101)

Give your edit box similar treatment.

```<code>EDITTEXT        IDC_EDIT1, 82, 10, 23, 16, ES_AUTOHSCROLL, WS_EX_LEFT
</code>```

So that you an use GetDlgItemText to fetch the string in that control:

Then you can handle click events in your dialog handler as follows:

```<code>case WM_COMMAND:
{
    switch(LOWORD(wParam))
    {
        case IDC_BUTTON1:
        {
             wchar_t str[200];
             GetDlgItemText(hwndDlg, IDC_EDIT1, str, 200);
             HandleClick(str);
             return TRUE;
        }
    }
}
</code>```

Body:
I used win32 GUI and managed to make some sort of interface after some googling but i don't know how to make a button do something or to make an integer get value from a textbox in the GUI.

This is the main

#include <windows.h>
#include <commctrl.h>
#include <stdio.h>
#include "resource.h"

HINSTANCE hInst;

BOOL CALLBACK DlgMain(HWND hwndDlg, UINT uMsg, WPARAM wParam, LPARAM lParam)
{
    switch(uMsg)
    {
    case WM_INITDIALOG:
    {
    }
    return TRUE;

    case WM_CLOSE:
    {
        EndDialog(hwndDlg, 0);
    }
    return TRUE;

    case WM_COMMAND:
    {
        switch(LOWORD(wParam))
        {
        }
    }
    return TRUE;
    }
    return FALSE;
}

int APIENTRY WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nShowCmd)
{
    hInst=hInstance;
    InitCommonControls();
    return DialogBox(hInst, MAKEINTRESOURCE(DLG_MAIN), NULL, (DLGPROC)DlgMain);
}

This is the resource.rc

#include <windows.h>
#include <commctrl.h>
#include <richedit.h>
#include "resource.h"

//
// Dialog resources
//
LANGUAGE LANG_NEUTRAL, SUBLANG_NEUTRAL
DLG_MAIN DIALOG 0, 0, 125, 64
STYLE DS_3DLOOK | DS_CENTER | DS_MODALFRAME | DS_SHELLFONT | WS_CAPTION | WS_VISIBLE | WS_POPUP | WS_SYSMENU
CAPTION "Numar Factorial"
FONT 8, "Ms Shell Dlg"
{
    EDITTEXT        0, 82, 10, 23, 16, ES_AUTOHSCROLL, WS_EX_LEFT
    LTEXT           "Introdu numarul\r\n", 0, 20, 13, 50, 17, SS_LEFT, WS_EX_LEFT
    PUSHBUTTON      "Confirma\r\n", 0, 40, 34, 45, 14, 0, WS_EX_LEFT
}

//
// Manifest resources
//
LANGUAGE LANG_NEUTRAL, SUBLANG_NEUTRAL
1                  RT_MANIFEST    ".\\manifest.xml"

Resource.h

#ifndef IDC_STATIC
#define IDC_STATIC (-1)
#endif

#define DLG_MAIN                                100

manifest.xml

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<assembly xmlns="urn:schemas-microsoft-com:asm.v1" manifestVersion="1.0">
  <dependency>
    <dependentAssembly>
      <assemblyIdentity type="win32" name="Microsoft.Windows.Common-Controls" version="6.0.0.0" processorArchitecture="*" publicKeyToken="6595b64144ccf1df" language="*"/>
    </dependentAssembly>
  </dependency>
  <trustInfo xmlns="urn:schemas-microsoft-com:asm.v3">
    <security>
      <requestedPrivileges>
        <requestedExecutionLevel
          level="asInvoker"
          uiAccess="false"/>
      </requestedPrivileges>
    </security>
  </trustInfo>
</assembly>

This is the main GUI
It says Factorial number, Insert a number and confirm and i want the program to take a number through that text box and after you hit confirm it returns the factorial of that number.
I need to figure out how to make the buttons do things cause i'm a beginner and my project is due in 2 days.Please help.

Body:
You PUSHBUTTON needs a control id.  Instead of this:

PUSHBUTTON      "Confirma\r\n", 0, 40, 34, 45, 14, 0, WS_EX_LEFT

This:

PUSHBUTTON      "Confirma\r\n", IDC_BUTTON1, 40, 34, 45, 14, 0, WS_EX_LEFT

Where IDC_BUTTON1 is an id in your resource.h file.  (e.g. #define IDC_BUTTON1 101)

Give your edit box similar treatment.

EDITTEXT        IDC_EDIT1, 82, 10, 23, 16, ES_AUTOHSCROLL, WS_EX_LEFT

So that you an use GetDlgItemText to fetch the string in that control:

Then you can handle click events in your dialog handler as follows:

case WM_COMMAND:
{
    switch(LOWORD(wParam))
    {
        case IDC_BUTTON1:
        {
             wchar_t str[200];
             GetDlgItemText(hwndDlg, IDC_EDIT1, str, 200);
             HandleClick(str);
             return TRUE;
        }
    }
}


问:
Upgrading Node JS and ERR_REQUIRE_ESM: Must use import to load ES Module: 'inheritsloose.js' of Babel Runtime
The following error is emitted in my Node JS/React JS application after upgrading Node JS to v.12. I'm currently using @babel/core 7.10.1. How should this error be resolved?

Here is my babel.config.js:

```<code>module.exports = {
  presets: [
    [
      '@babel/preset-env',
      {
        targets: {
          node: 'current',
        },
      },
    ],
    '@babel/preset-react',
    '@babel/preset-typescript',
  ],
  plugins: [
    '@babel/plugin-proposal-class-properties',
    ['@babel/plugin-proposal-decorators', { legacy: true }],
    '@babel/plugin-proposal-export-default-from',
    '@babel/plugin-proposal-export-namespace-from',
    '@babel/plugin-syntax-dynamic-import',
    '@babel/plugin-transform-react-constant-elements',
    '@babel/plugin-transform-react-inline-elements',
  ],
  ignore: ['node_modules', 'build'],
};
</code>```

答:
Try to remove "type": "module" from package.json.

I've spend many hours with no luck and finally found this commend in discussion:

https://github.com/manuelbieh/geolib/issues/208#issuecomment-556994420

You have ignore: ['node_modules', 'build'], maybe, that's the reason?

Body:
The following error is emitted in my Node JS/React JS application after upgrading Node JS to v.12. I'm currently using @babel/core 7.10.1. How should this error be resolved?

Here is my babel.config.js:

module.exports = {
  presets: [
    [
      '@babel/preset-env',
      {
        targets: {
          node: 'current',
        },
      },
    ],
    '@babel/preset-react',
    '@babel/preset-typescript',
  ],
  plugins: [
    '@babel/plugin-proposal-class-properties',
    ['@babel/plugin-proposal-decorators', { legacy: true }],
    '@babel/plugin-proposal-export-default-from',
    '@babel/plugin-proposal-export-namespace-from',
    '@babel/plugin-syntax-dynamic-import',
    '@babel/plugin-transform-react-constant-elements',
    '@babel/plugin-transform-react-inline-elements',
  ],
  ignore: ['node_modules', 'build'],
};


问:
Extracting a value from python variable
When I run the following code I get an output containing a value (1.11113) that I want to use within the code (after this first section). The full outputI get is shown after the code. Basically what I'm trying to do is extract a real time forex (stock) value to use in an order. This order would be placed after this initial code within the same python module. Thanks for your help.

```<code>import json
from oandapyV20.contrib.requests import MarketOrderRequest
from oandapyV20.contrib.requests import TakeProfitDetails, StopLossDetails
import oandapyV20.endpoints.orders as orders
import oandapyV20
import oandapyV20.endpoints.pricing as pricing
from exampleauth import exampleAuth
import argparse
from oandapyV20 import API
from oandapyV20.exceptions import V20Error
import oandapyV20.endpoints.instruments as instruments
from oandapyV20.definitions.instruments import CandlestickGranularity
import re
import oandapyV20.endpoints.pricing as pricing

# pricef=float(price)
# parser.add_argument('--price', choices=price, default='M', help='Mid/Bid/Ask')
accountID, access_token = exampleAuth()
api = oandapyV20.API(access_token=access_token)

params = {"instruments": "EUR_USD"}
r = pricing.PricingInfo(accountID=accountID, params=params)
rv = api.request(r)

print(rv)
</code>```

OUTPUT

```<code>{'prices': [{'asks': [{'liquidity': 10000000, 'price': '1.11132'}],
             'bids': [{'liquidity': 10000000, 'price': '1.11113'}],
             'closeoutAsk': '1.11132',
             'closeoutBid': '1.11113',
             'instrument': 'EUR_USD',
             'quoteHomeConversionFactors': {'negativeUnits': '1.00000000',
                                            'positiveUnits': '1.00000000'},
             'status': 'tradeable',
             'time': '2020-05-31T23:02:34.271983628Z',
             'tradeable': True,
             'type': 'PRICE',
             'unitsAvailable': {'default': {'long': '3852555',
                                            'short': '3852555'},
                                'openOnly': {'long': '3852555',
                                             'short': '3852555'},
                                'reduceFirst': {'long': '3852555',
                                                'short': '3852555'},
                                'reduceOnly': {'long': '0', 'short': '0'}}}],
 'time': '2020-05-31T23:02:40.672716661Z'}
</code>```

答:
Looks like you want:

```<code>rv['prices'][0]['bids'][0]['price']
</code>```

at least for this case.  It might not be that you always want the first price entry or the first bid entry, in which case you might want to do some sort of sorting or filtering on whatever criteria you want to use to pick the right entry from among more than one.

Title: Extracting a value from python variable

Body:
When I run the following code I get an output containing a value (1.11113) that I want to use within the code (after this first section). The full outputI get is shown after the code. Basically what I'm trying to do is extract a real time forex (stock) value to use in an order. This order would be placed after this initial code within the same python module. Thanks for your help.

import json
from oandapyV20.contrib.requests import MarketOrderRequest
from oandapyV20.contrib.requests import TakeProfitDetails, StopLossDetails
import oandapyV20.endpoints.orders as orders
import oandapyV20
import oandapyV20.endpoints.pricing as pricing
from exampleauth import exampleAuth
import argparse
from oandapyV20 import API
from oandapyV20.exceptions import V20Error
import oandapyV20.endpoints.instruments as instruments
from oandapyV20.definitions.instruments import CandlestickGranularity
import re
import oandapyV20.endpoints.pricing as pricing

# pricef=float(price)
# parser.add_argument('--price', choices=price, default='M', help='Mid/Bid/Ask')
accountID, access_token = exampleAuth()
api = oandapyV20.API(access_token=access_token)

params = {"instruments": "EUR_USD"}
r = pricing.PricingInfo(accountID=accountID, params=params)
rv = api.request(r)

print(rv)

OUTPUT

{'prices': [{'asks': [{'liquidity': 10000000, 'price': '1.11132'}],
             'bids': [{'liquidity': 10000000, 'price': '1.11113'}],
             'closeoutAsk': '1.11132',
             'closeoutBid': '1.11113',
             'instrument': 'EUR_USD',
             'quoteHomeConversionFactors': {'negativeUnits': '1.00000000',
                                            'positiveUnits': '1.00000000'},
             'status': 'tradeable',
             'time': '2020-05-31T23:02:34.271983628Z',
             'tradeable': True,
             'type': 'PRICE',
             'unitsAvailable': {'default': {'long': '3852555',
                                            'short': '3852555'},
                                'openOnly': {'long': '3852555',
                                             'short': '3852555'},
                                'reduceFirst': {'long': '3852555',
                                                'short': '3852555'},
                                'reduceOnly': {'long': '0', 'short': '0'}}}],
 'time': '2020-05-31T23:02:40.672716661Z'}

Body:
Looks like you want:

rv['prices'][0]['bids'][0]['price']

at least for this case.  It might not be that you always want the first price entry or the first bid entry, in which case you might want to do some sort of sorting or filtering on whatever criteria you want to use to pick the right entry from among more than one.


问:
How to join strings between parentheses in a list of strings
```<code>poke_list = [... 'Charizard', '(Mega', 'Charizard', 'X)', '78', '130', ...] #1000+ values
</code>```

Is it possible to merge strings that start with '(' and end with ')' and then reinsert it into the same list or a new list?

My desired output poke_list = [... 'Charizard (Mega Charizard X)', '78', '130', ...]

答:
Another way to do it, slightly shorter than other solution

```<code>poke_list = ['Bulbasaur', 'Charizard', '(Mega', 'Charizard', 'X)', '78', 'Pikachu', '(Raichu)', '130']
fixed = []
acc = fixed
for x in poke_list:
    if x[0] == '(':
        acc = [fixed.pop()]
    acc.append(x)
    if x[-1] == ')':
        fixed.append(' '.join(acc))
        acc = fixed
if not acc is fixed:
    fixed.append(' '.join(acc))
print(fixed)
</code>```

Also notice that this solution assumes that the broken list doesn't start with a parenthesis to fix, and also manage the case where an item has both opening and closing parenthesis (case excluded in other solution)

The idea is to either append values to main list (fixed) or to some inner list which will be joined later if we have detected opening parenthesis. If the inner list was never closed when exiting the loop (likely illegal) we append it anyway to the fixed list when exiting the loop.

This way of doing things if very similar to the transformation of a flat expression containing parenthesis to a hierarchy of lists. The code would of course be slightly different and should manage more than one level of inner list.

Body:
poke_list = [... 'Charizard', '(Mega', 'Charizard', 'X)', '78', '130', ...] #1000+ values

Is it possible to merge strings that start with '(' and end with ')' and then reinsert it into the same list or a new list?

My desired output poke_list = [... 'Charizard (Mega Charizard X)', '78', '130', ...]

Body:
Another way to do it, slightly shorter than other solution

poke_list = ['Bulbasaur', 'Charizard', '(Mega', 'Charizard', 'X)', '78', 'Pikachu', '(Raichu)', '130']
fixed = []
acc = fixed
for x in poke_list:
    if x[0] == '(':
        acc = [fixed.pop()]
    acc.append(x)
    if x[-1] == ')':
        fixed.append(' '.join(acc))
        acc = fixed
if not acc is fixed:
    fixed.append(' '.join(acc))
print(fixed)

Also notice that this solution assumes that the broken list doesn't start with a parenthesis to fix, and also manage the case where an item has both opening and closing parenthesis (case excluded in other solution)

The idea is to either append values to main list (fixed) or to some inner list which will be joined later if we have detected opening parenthesis. If the inner list was never closed when exiting the loop (likely illegal) we append it anyway to the fixed list when exiting the loop.

This way of doing things if very similar to the transformation of a flat expression containing parenthesis to a hierarchy of lists. The code would of course be slightly different and should manage more than one level of inner list.


问:
How to make a window come up on button click?
So basically my goal is to code my own ReCaptcha. To make that possible, I'd like a window to come up once I clicked a button to send a form or something like this. In best case it looks like this, but with my own content inside. Is it possible to do this with just one js-script, or with adding a few divs?</p>

答:
I think you can use jquery modal.

check the following link https://jquerymodal.com/

official docs can be found at

https://jqueryui.com/dialog/


问:
SQL query, three tables
So let's same I'm trying to find actors who are in two movies together (for the purpose of a degrees of separation page). I have databases as such (this is just some made up data):

actors

```<code>id     first_name     last_name    gender
17     brad           pitt         m
2      kevin          bacon        m
</code>```

movies

```<code>id     name               year
20     benjamin button    2008
</code>```

roles

```<code>a_id    m_id     role
17      20       Mr. Benjamin Button
</code>```

So I want to return the names of the movies which both actors are in. I have the first and last names of two actors.

I'm having a lot of trouble getting this to work. What I'm having trouble with, specifically, is the SELECT part

```<code>SELECT name FROM movies JOIN . . .
</code>```

I'm starting with first_name and last_name values for each

答:
```<code>select m.name,group_concat(concat_ws(' ',a.first_name,a.last_name) order by a.last_name) as actors
from actors as a
inner join roles as r on a.id = r.a_id
inner join movies as m on m.id = r.m_id
where r.a_id in (2,17)
group by r.m_id
having count(r.a_id) = 2
order by m.name
</code>```

Title: SQL query, three tables

Body:
So let's same I'm trying to find actors who are in two movies together (for the purpose of a degrees of separation page). I have databases as such (this is just some made up data):

actors

id     first_name     last_name    gender
17     brad           pitt         m
2      kevin          bacon        m

movies

id     name               year
20     benjamin button    2008

roles

a_id    m_id     role
17      20       Mr. Benjamin Button

So I want to return the names of the movies which both actors are in. I have the first and last names of two actors.

I'm having a lot of trouble getting this to work. What I'm having trouble with, specifically, is the SELECT part

SELECT name FROM movies JOIN . . .

I'm starting with first_name and last_name values for each


问:
Attempting to pass a string to a constructed function
still floundering around in my attempts to understand functions. How would I go about constructing a function with values I want to pass to it?</p>

```<code>var box = $('#box1');

function pushCard(arg1) {
  if (this.style.opacity == 0.5) {
    this.style.opacity = 1;
  }
  else {
    this.style.opacity = 0.5;
    window.alert(arg1);
  }
}

box.click(pushCard('String'));
</code>```

答:
tl;dr: be aware of the difference between functions / function results and when functions are passed as values / when they're called (and their result is passed)

The culprit is with this line:

box.click(pushCard('String'));
```

<p>You're calling <code>box.click()</code> with "something". JavaScript needs to evaluate expressions before passing them as function arguments. </p>

<p>In this case, you instruct JavaScrip to run <code>box.click(pushCard('String'))</code> = call <code>box.click</code> with value of <code>pushCard('String')</code> as first parameter.</p>

<p>In order to do this, JavaScript first needs to evaluate <code>pushCard('String')</code> by running <code>pushCard</code> with value <code>'String'</code> as first parameter (this doesn't need more evaluation since it's already a value).</p>

<p>The result of <code>pushCard('String')</code> is <code>undefined</code> (you're returning nothing from that function). So in effect, it's the equivalent of <code>box.click(undefined)</code>.</p>

<p>This is what you want:</p>

<pre class="lang-js prettyprint-override"><code>box.click(function() {pushCard('String')});
</code>```

(or with ES6 arrow functions: box.click(() => pushCard('String'));)

In this case, you're assigning box.click() a function. This is what jQuery .click()` expects, a click handler which will run (be evaluated) then the click happens, not when the click handler is assigned.

In JavaScript, you can pass functions as values, and they are evaluated when explicitly called:

```<code>function test() {
   alert('I have been called');
}

function delay_it(handler) {
   setTimeout(function() {
      handler(); // ⇽ call given function
   }, 1000);
   // shorter: setTimeout(handler, 1000);
}

// Wrong (we're calling test() by ourselves and passing the result (undefined) to delay_it
delay_it(test());

// Correct (we're giving test as function to delay_it, delay_it will call the function)
delay_it(test);
</code>```

Body:
still floundering around in my attempts to understand functions. How would I go about constructing a function with values I want to pass to it?

var box = $('#box1');

function pushCard(arg1) {
  if (this.style.opacity == 0.5) {
    this.style.opacity = 1;
  }
  else {
    this.style.opacity = 0.5;
    window.alert(arg1);
  }
}

box.click(pushCard('String'));

Body:
tl;dr: be aware of the difference between functions / function results and when functions are passed as values / when they're called (and their result is passed)

The culprit is with this line:

box.click(pushCard('String'));

You're calling box.click() with "something". JavaScript needs to evaluate expressions before passing them as function arguments.

In this case, you instruct JavaScrip to run box.click(pushCard('String')) = call box.click with value of pushCard('String') as first parameter.

In order to do this, JavaScript first needs to evaluate pushCard('String') by running pushCard with value 'String' as first parameter (this doesn't need more evaluation since it's already a value).

The result of pushCard('String') is undefined (you're returning nothing from that function). So in effect, it's the equivalent of box.click(undefined).

This is what you want:

box.click(function() {pushCard('String')});

(or with ES6 arrow functions: box.click(() => pushCard('String'));)

In this case, you're assigning box.click() a function. This is what jQuery .click()` expects, a click handler which will run (be evaluated) then the click happens, not when the click handler is assigned.

In JavaScript, you can pass functions as values, and they are evaluated when explicitly called:

function test() {
   alert('I have been called');
}

function delay_it(handler) {
   setTimeout(function() {
      handler(); // ⇽ call given function
   }, 1000);
   // shorter: setTimeout(handler, 1000);
}

// Wrong (we're calling test() by ourselves and passing the result (undefined) to delay_it
delay_it(test());

// Correct (we're giving test as function to delay_it, delay_it will call the function)
delay_it(test);


答:
Your output is a dictionary with a number of nested lists and dictionaries.

To access a value from a dictionary, you use the same syntax as when accessing members of a list, only that the key does not have to be a number, but can be any data type, commonly Strings. So rv['time'] in your case would yield '2020-05-31T23:02:40.672716661Z'.

Since the number 1.11113 appears twice in the dictionary, here are the two pointers that would access the corresponding field:

rv['prices'][0]['bids'][0]['price']

and

rv['prices'][0]['closeoutBid']

This will be in String format, so to use it as a number, you would have to convert it using float()

Also notice the occasional [0] to access the first element of a list.

Title: Extracting a value from python variable


问:
question about windows forms checkbox
```<code>private void frmSearch_Load(object sender, EventArgs e)
{
    // TODO: This line of code loads data into the 'bookdatabaseDataSet.Dist_Year' table. You can move, or remove it, as needed.
    this.dist_YearTableAdapter.Fill(this.bookdatabaseDataSet.Dist_Year);
    // TODO: This line of code loads data into the 'bookdatabaseDataSet.Dist_Auth' table. You can move, or remove it, as needed.
    this.dist_AuthTableAdapter.Fill(this.bookdatabaseDataSet.Dist_Auth);
    // TODO: This line of code loads data into the 'bookdatabaseDataSet.Book' table. You can move, or remove it, as needed.
    this.bookTableAdapter.Fill(this.bookdatabaseDataSet.Book);
}

private void button1_Click(object sender, EventArgs e)
{
    Form f4 = new Confirm();
    f4.Show();
    Hide();
}

private void button2_Click(object sender, EventArgs e)
{
    if (MessageBox.Show("Are you sure you want to Exit?", "Exit", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
    {
        Application.Exit();
    }
}
</code>```

<p>my question is:
I want from the form to give me error message if I didn't check any of the check boxes. what is the correct code for it? and where should I right it? and thanks a lot for your concern.
form of windows application </p>

答:
I guess you want to ensure at least one checkbox is checked when button1 is clicked, right? If so, place it at the beginning of button1_Click event.

```<code>private void button1_Click(object sender, EventArgs e)
{
    if (!checkbox1.Checked && !checkbox2.Checked && !checkbox100.Checked)
    {
        MessageBox.Show("Please select a checkbox.", this.Text, MessageBoxButtons.OK, MessageBoxIcon.Warning);
        checkbox1.Focus();
    }
    else
    {
        Form f4 = new Confirm();
        f4.Show();
        Hide();
     }
}
</code>```

Title: question about windows forms checkbox

Body:
private void frmSearch_Load(object sender, EventArgs e)
{
    // TODO: This line of code loads data into the 'bookdatabaseDataSet.Dist_Year' table. You can move, or remove it, as needed.
    this.dist_YearTableAdapter.Fill(this.bookdatabaseDataSet.Dist_Year);
    // TODO: This line of code loads data into the 'bookdatabaseDataSet.Dist_Auth' table. You can move, or remove it, as needed.
    this.dist_AuthTableAdapter.Fill(this.bookdatabaseDataSet.Dist_Auth);
    // TODO: This line of code loads data into the 'bookdatabaseDataSet.Book' table. You can move, or remove it, as needed.
    this.bookTableAdapter.Fill(this.bookdatabaseDataSet.Book);
}

private void button1_Click(object sender, EventArgs e)
{
    Form f4 = new Confirm();
    f4.Show();
    Hide();
}

private void button2_Click(object sender, EventArgs e)
{
    if (MessageBox.Show("Are you sure you want to Exit?", "Exit", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
    {
        Application.Exit();
    }
}

my question is:
I want from the form to give me error message if I didn't check any of the check boxes. what is the correct code for it? and where should I right it? and thanks a lot for your concern.
form of windows application

Body:
I guess you want to ensure at least one checkbox is checked when button1 is clicked, right? If so, place it at the beginning of button1_Click event.

private void button1_Click(object sender, EventArgs e)
{
    if (!checkbox1.Checked && !checkbox2.Checked && !checkbox100.Checked)
    {
        MessageBox.Show("Please select a checkbox.", this.Text, MessageBoxButtons.OK, MessageBoxIcon.Warning);
        checkbox1.Focus();
    }
    else
    {
        Form f4 = new Confirm();
        f4.Show();
        Hide();
     }
}


问:
Rendering in Rails erb of a each_with_index loop through a JSONB array results in duplicates
I am trying to render the following in a view but the outcome (day and array) is duplicated.  This seems to work in a console and removing the time helpers does not help.  I suspect an ERB thing.

The business_hours are stored as JSONB.

Any hints of what I have missed appreciated.

```<code>company.schedules.last.business_hours returns

=> {"monday_opens_at"=>"08:00:00", "sunday_opens_at"=>"09:00:00", "monday_closes_at"=>"20:00:00", "sunday_closes_at"=>"18:00:00"}

<table class="table table-sm table-borderless text-sm mb-0">
        <% if company.schedules.last.business_hours? %>
          <% I18n.t('date.day_names').each do |day| %>
            <% %w[opens_at closes_at].each_with_object([]) do |time_type, to_return| %>
              <% @hours = to_return << company.schedules.last.business_hours["#{day.downcase}_#{time_type}"]
                  @hours.compact.tap do |hours| %>
                    <tr>
                      <th class="pl-0"><%= "#{day}" %></th>
                      <td class="pl-0 pr-0 text-right"><%= "#{time_helper(hours)}" %></td>
                    </tr>
                <% end %>
              <% end %>
            <% end %>
            <% else %>
            <p> no data available</p>
        <% end %>
      </table>
</code>```

答:
The to_return parameter on the each_with_object loop is cumulative. When time_type is opens_at, you attribute the business hours to to_return with << and then you set @hours with the contents of to_return.

In the second run, when time_type is closes_at, you are setting @hours with the contents of to_return, which will be the business hours from the first loop plus the business hours from the second (because of the <<). That may be causing the duplication.

Also, we should investigate the tap, it should work with a simple each in there.

Body:
I am trying to render the following in a view but the outcome (day and array) is duplicated.  This seems to work in a console and removing the time helpers does not help.  I suspect an ERB thing.

The business_hours are stored as JSONB.

Any hints of what I have missed appreciated.

company.schedules.last.business_hours returns

=> {"monday_opens_at"=>"08:00:00", "sunday_opens_at"=>"09:00:00", "monday_closes_at"=>"20:00:00", "sunday_closes_at"=>"18:00:00"}

        <% if company.schedules.last.business_hours? %>
          <% I18n.t('date.day_names').each do |day| %>
            <% %w[opens_at closes_at].each_with_object([]) do |time_type, to_return| %>
              <% @hours = to_return << company.schedules.last.business_hours["#{day.downcase}_#{time_type}"]
                  @hours.compact.tap do |hours| %>

                      <%= "#{day}" %>
                      <%= "#{time_helper(hours)}" %>

                <% end %>
              <% end %>
            <% end %>
            <% else %>

 no data available

        <% end %>


问:
Print multiple PDF and rendered HTML
I have a requirement to print multiple PDF and rendered html from my web application. Is it possible to show print preview to user and then print in one go or do I need to print them one after another?

Here is short example of what I want to print where I want to print content in first paragraph followed by pdf and followed by next paragraph.

```<code><html>
<body>
<p>
This is my paragraph<br />
This is my paragraph<br />
This is my paragraph<br />This is my paragraph<br />This is my paragraph<br />This is my paragraph<br />
</p>
<iframe  src="http://www.africau.edu/images/default/sample.pdf" style="width:718px; height:700px;" frameborder="0"></iframe>
<p>
This is my paragraph<br />
This is my paragraph<br />
This is my paragraph<br />This is my paragraph<br />This is my paragraph<br />This is my paragraph<br />
</p>
</body>
</code>```

答:
Yes it is possible but you will have to tweak my code a bit to suit your needs.

I will modify your HTML page by adding some id Attributes just to make it easy for javascript to select them:

```<code><html>
<body>
<p id ='first_paragraph'>
This is my paragraph<br />
This is my paragraph<br />
This is my paragraph<br />This is my paragraph<br />This is my paragraph<br />This is my paragraph<br />
</p>
<iframe id='first_ifame' src="http://www.africau.edu/images/default/sample.pdf" style="width:718px; height:700px;" frameborder="0"></iframe>

<p id= "second_paragraph">
This is my paragraph<br />
This is my paragraph<br />
This is my paragraph<br />This is my paragraph<br />This is my paragraph<br />This is my paragraph<br />
</p>
</body>
</html>
</code>```

Now i will use javascript to re-order the contents of the parent window by manipulating the DOM.

```<code><script>

 pages =[] // initiate an empty list here

function printPage() {

var p1 = document.getElementById('first_paragraph');
// get the first_paragraph and
// then push its innerHTML into the list
   pages.push(p1.innerHTML);

var frame1 = document.getElementById('first_ifame');
// get the first_iframe and
// then push its innerHTML into the list
   pages.push(frame1.contentWindow.document.body.innerHTML);

var p2 = document.getElementById('second_paragraph');
// get the second_paragraph and
// then push its innerHTML into the list
   pages.push(p2.innerHTML);

if (pages && pages.length) {

// this if statement, just checks to ensure our list is not empty before running the code.

// here is the magic, we now set the parent window to be equal to all the concatenated innerHTML
window.content.document.body.innerHTML = pages;
// then we print this new window that contains all the iframes
window.print();
}
else {
// do nothing
}

}
</script>
</code>```

With this solution you even avoid the problem of the iframe being cut off if it exceeds one page.
Secondly, you get only one print dialogue box even if you have multiple iframes.

Remember that in your parent page HTML you will have the code below to call the printPage function.

```<code><input type="submit" value="Print All"
  onclick="javascript:printPage()"
 />
</code>```

Title: Print multiple PDF and rendered HTML

Body:
I have a requirement to print multiple PDF and rendered html from my web application. Is it possible to show print preview to user and then print in one go or do I need to print them one after another?

Here is short example of what I want to print where I want to print content in first paragraph followed by pdf and followed by next paragraph.

This is my paragraph

This is my paragraph

This is my paragraph
This is my paragraph
This is my paragraph
This is my paragraph

This is my paragraph

This is my paragraph

This is my paragraph
This is my paragraph
This is my paragraph
This is my paragraph

Body:
Yes it is possible but you will have to tweak my code a bit to suit your needs.

I will modify your HTML page by adding some id Attributes just to make it easy for javascript to select them:

<html>
<body>
<p id ='first_paragraph'>
This is my paragraph<br />
This is my paragraph<br />
This is my paragraph<br />This is my paragraph<br />This is my paragraph<br />This is my paragraph<br />
</p>
<iframe id='first_ifame' src="http://www.africau.edu/images/default/sample.pdf" style="width:718px; height:700px;" frameborder="0"></iframe>

<p id= "second_paragraph">
This is my paragraph<br />
This is my paragraph<br />
This is my paragraph<br />This is my paragraph<br />This is my paragraph<br />This is my paragraph<br />
</p>
</body>
</html>

Now i will use javascript to re-order the contents of the parent window by manipulating the DOM.

<script>

 pages =[] // initiate an empty list here

function printPage() {

var p1 = document.getElementById('first_paragraph');
// get the first_paragraph and
// then push its innerHTML into the list
   pages.push(p1.innerHTML);

var frame1 = document.getElementById('first_ifame');
// get the first_iframe and
// then push its innerHTML into the list
   pages.push(frame1.contentWindow.document.body.innerHTML);

var p2 = document.getElementById('second_paragraph');
// get the second_paragraph and
// then push its innerHTML into the list
   pages.push(p2.innerHTML);

if (pages && pages.length) {

// this if statement, just checks to ensure our list is not empty before running the code.

// here is the magic, we now set the parent window to be equal to all the concatenated innerHTML
window.content.document.body.innerHTML = pages;
// then we print this new window that contains all the iframes
window.print();
}
else {
// do nothing
}

}
</script>

With this solution you even avoid the problem of the iframe being cut off if it exceeds one page.
Secondly, you get only one print dialogue box even if you have multiple iframes.

Remember that in your parent page HTML you will have the code below to call the printPage function.

<input type="submit" value="Print All"
  onclick="javascript:printPage()"
 />


问:
CoreNFC Text message produces double byte chars only?
I am successfully interfacing (reading & writing) to an NDEF tag. The tag is an NXP electronic tag on my proto board which I can read out with I2C protocol. I am working with plain text messages only.

Writing to the tag, though successful, generates double byte character text only. Creating a text message is done with:

```<code>guard let testRecord = NFCNDEFPayload.wellKnownTypeTextPayload(
  string: String(describing: "blah blah".cString(using: String.Encoding.utf8)),
  locale: .current)
else { return }
</code>```

and is written to the tag with:

```<code>let myMessage = NFCNDEFMessage.init(records: [testRecord])
tag.writeNDEF(myMessage)
</code>```

The data arrives in the tag but is encoded (so it seems) as two bytes. Specifically, each character in the string "blah blah" is preceded with \x00, resulting into \x00 \b \x00 \l \x00 \a etc.

I thought that .utf8 encoding would drop to just standard ASCII (single byte) if one uses only characters within the ASCII set.

How can I make sure the NDEF message is encoded with single character ASCII?

答: For anyone landing here, the short answer is; yes, NFCNDEFPayload.wellKnownTypeTextPayload() encodes strings as utf16 only (nice job documenting this Apple!). To solve this, you need to go a layer down by constructing your own payload. Check out this answer: NFC NDEF writing on IOS Encoding</p>

Body:
I am successfully interfacing (reading & writing) to an NDEF tag. The tag is an NXP electronic tag on my proto board which I can read out with I2C protocol. I am working with plain text messages only.

Writing to the tag, though successful, generates double byte character text only. Creating a text message is done with:

guard let testRecord = NFCNDEFPayload.wellKnownTypeTextPayload(
  string: String(describing: "blah blah".cString(using: String.Encoding.utf8)),
  locale: .current)
else { return }

and is written to the tag with:

let myMessage = NFCNDEFMessage.init(records: [testRecord])
tag.writeNDEF(myMessage)

The data arrives in the tag but is encoded (so it seems) as two bytes. Specifically, each character in the string "blah blah" is preceded with \x00, resulting into \x00 \b \x00 \l \x00 \a etc.

I thought that .utf8 encoding would drop to just standard ASCII (single byte) if one uses only characters within the ASCII set.

How can I make sure the NDEF message is encoded with single character ASCII?


问:
Receiving an excel file from an HTTP POST request and embedding it into a Weebly website
I have a sensor recording data every minute and updating an excel/csv file with the results, done in python. I then use requests.post to create an HTTP request sending the file to a Weebly website. I believe I need to use JavaScript on the website to receive the excel file and embed it into the website. I have been stuck on this part for a few days since I have never used JavaScript before. The question is: How can I create a JavaScript code to receive the file and embed it into the Weebly website?

From the research I have done thus far it appears that I need to use an XMLHttpRequest GET to request the data being sent from python, I am a little confused though because it requires a url. Through more research it looks like I may need to set up a server to send it to and request it from although I am not sure if that is necessary or how to do it.

```<code>import requests
with open('/home/pi/Images_for_Python/2/100001.csv','rb') as f:
    r = requests.post("http://www.greeniethegenie123.weebly.com", files={'/home/pi/Images_for_Python/2/100001.csv':f})
print(r.text)
</code>```

答: If anyone else is having the same problem I have found an alternative solution through Amazon Web Services (AWS). They have a setup that works quite well for this called AWS IoT Analytics. It made this a trivial problem due to its python module that connects directly to the data server!</p>

Body:
I have a sensor recording data every minute and updating an excel/csv file with the results, done in python. I then use requests.post to create an HTTP request sending the file to a Weebly website. I believe I need to use JavaScript on the website to receive the excel file and embed it into the website. I have been stuck on this part for a few days since I have never used JavaScript before. The question is: How can I create a JavaScript code to receive the file and embed it into the Weebly website?

From the research I have done thus far it appears that I need to use an XMLHttpRequest GET to request the data being sent from python, I am a little confused though because it requires a url. Through more research it looks like I may need to set up a server to send it to and request it from although I am not sure if that is necessary or how to do it.

import requests
with open('/home/pi/Images_for_Python/2/100001.csv','rb') as f:
    r = requests.post("http://www.greeniethegenie123.weebly.com", files={'/home/pi/Images_for_Python/2/100001.csv':f})
print(r.text)


问:
Unable to create a C# console application in VS Code terminal
When I try to create a new C# project in VScode,I got aerror. How can I fix it?

This is my command:

PS C:\Users\lau\Documents\code\c#> dotnet new console

And this is the error message：

Template "Console Application" could not be created. Error while
  processing file
  /content/ConsoleApplication-CSharp/Company.ConsoleApplication1.csproj
  System.IO.FileNotFoundException: Could not find file
  'C:\Users\lau\Documents\code\c#\c#.csproj'. File name:
  'C:\Users\lau\Documents\code\c#\c#.csproj'    at
  System.IO.FileStream.ValidateFileHandle(SafeFileHandle fileHandle)
  at System.IO.FileStream.CreateFileOpenHandle(FileMode mode, FileShare
  share, FileOptions options)    at
  System.IO.FileStream..ctor(String path, FileMode mode, FileAccess
  access, FileShare share, Int32 bufferSize, FileOptions options)
  at System.IO.FileStream..ctor(String path, FileMode mode, FileAccess
  access, FileShare share, Int32 bufferSize)    at
  System.IO.File.Create(String path)    at
  Microsoft.TemplateEngine.Utils.PhysicalFileSystem.CreateFile(String
  path)    at
  Microsoft.TemplateEngine.Core.Util.Orchestrator.ProcessFile(IFile
  sourceFile, String sourceRel, String targetDir, IGlobalRunSpec spec,
  IProcessor fallback, IEnumerable1 fileGlobProcessors, IReadOnlyList1
  locOperations)

答: I had same problem, and fixed it creating directory again from root or creating directory in C:\, the problem is permissions associated to directory


问:
Rhino Mocks: How to stub a generic method to catch an anonymous type?
We need to stub a generic method which will be called using an anonymous type as the type parameter. Consider:

```<code>interface IProgressReporter
{
    T Report<T>(T progressUpdater);
}

// Unit test arrange:
Func<object, object> returnArg = (x => x);   // we wish to return the argument
_reporter.Stub(x => x.Report<object>(null).IgnoreArguments().Do(returnArg);
</code>```

This would work if the actual call to .Report<T>() in the method under test was done with object as the type parameter, but in actuality, the method is called with T being an anonymous type. This type is not available outside of the method under test. As a result, the stub is never called.

Is it possible to stub a generic method without specifying the type parameter?

答:
I'm not clear on your use case but you might be able to use a helper method to setup the Stub for each test.  I don't have RhinoMocks so have been unable to verify if this will work

```<code>private void HelperMethod<T>()
{
  Func<object, object> returnArg = (x => x); // or use T in place of object if thats what you require
  _reporter.Stub(x => x.Report<T>(null)).IgnoreArguments().Do(returnArg);
}
</code>```

Then in your test do:

```<code>public void MyTest()
{
   HelperMethod<yourtype>();
   // rest of your test code
}
</code>```

Body:
We need to stub a generic method which will be called using an anonymous type as the type parameter. Consider:

interface IProgressReporter
{
    T Report<T>(T progressUpdater);
}

// Unit test arrange:
Func<object, object> returnArg = (x => x);   // we wish to return the argument
_reporter.Stub(x => x.Report<object>(null).IgnoreArguments().Do(returnArg);

This would work if the actual call to .Report<T>() in the method under test was done with object as the type parameter, but in actuality, the method is called with T being an anonymous type. This type is not available outside of the method under test. As a result, the stub is never called.

Is it possible to stub a generic method without specifying the type parameter?

Body:
I'm not clear on your use case but you might be able to use a helper method to setup the Stub for each test.  I don't have RhinoMocks so have been unable to verify if this will work

private void HelperMethod<T>()
{
  Func<object, object> returnArg = (x => x); // or use T in place of object if thats what you require
  _reporter.Stub(x => x.Report<T>(null)).IgnoreArguments().Do(returnArg);
}

Then in your test do:

public void MyTest()
{
   HelperMethod<yourtype>();
   // rest of your test code
}


问:
Time complexity for 2 nested loops
If I'm taking input through 2 nested For-loops  like this

```<code>cin>>x;

for(i=0;i<x;i++)
{
   cin>>y;

for(j=0;j<y;j++)

}
</code>```

The complexity of the Outer loop is O(X)
but I'm confused about the Time complexity of the inner loop as the Y is variable.

答:
The complexity of the outer loop is not O(x), because the time it takes to run the outer loop depends on the value of y entered.

Let's say we have a sequence y1,y2,...,yn of inputs for y. Then the first loop would take y1 operations and the second iteration would take y2 operations and so on for each of the x iterations.

Now let Y be the max of this sequence of inputs, then each iteration of the outer loop would take at most Y operations. So we have that for x iterations each taking at most Y operations we get O(xY).

It is possible to specify further to a possibly smaller class of functions but it's important to remember that if f < g then O(f) is contained in O(g). And that when we say a function is O(f) we just mean it is inside the class O(f).

Considering in this case the input is not determined using the max would be a worst case scenario.

Also it would be more accurate if the input was outside all the loops as input isn't a constant operation most of the time. (This is trivial though, just have the y be input from a file or something and then use that to make an array.)

Title: Time complexity for 2 nested loops

Body:
If I'm taking input through 2 nested For-loops  like this

cin>>x;

for(i=0;i<x;i++)
{
   cin>>y;

for(j=0;j<y;j++)

}

The complexity of the Outer loop is O(X)
but I'm confused about the Time complexity of the inner loop as the Y is variable.


问:
CodePipeline with Terraform and Beanstalk
I'm trying to create a pipeline to deploy on Beanstalk but I constantly get an error in the deploy section of the pipeline:

```<code>Insufficient permissions
The provided role does not have sufficient permissions to access
Elastic Beanstalk: Access Denied
</code>```

What am I missing?

```<code>/************************************************
 * Code Build
 ***********************************************/

resource "aws_codebuild_project" "project-name-codebuild" {
  name = "${var.project}-codebuild"
  build_timeout = "15"
  service_role = "${aws_iam_role.project-name-codebuild-role.arn}"

  artifacts {
    type = "CODEPIPELINE"
  }

  environment {
    compute_type = "BUILD_GENERAL1_SMALL"
    type = "LINUX_CONTAINER"
    image = "aws/codebuild/java:openjdk-8"
  }

  source {
    type = "CODEPIPELINE"
  }

  tags {
    Name = "${var.project}"
    Environment = "${var.environment}"
  }
}

resource "aws_ecr_repository" "project-name-ecr-repository" {
  name = "${var.project}-ecr-repository"
}

resource "aws_iam_role" "project-name-codebuild-role" {
  name = "${var.project}-codebuild-role"

  assume_role_policy = <<EOF
{
      "Version": "2012-10-17",
      "Statement": [
        {
          "Effect": "Allow",
          "Principal": {
            "Service": "codebuild.amazonaws.com"
          },
          "Action": "sts:AssumeRole"
        }
      ]
    }
EOF
}

resource "aws_iam_role_policy" "project-name-codebuild-role-policy" {
  role = "${aws_iam_role.project-name-codebuild-role.id}"

  policy = <<POLICY
{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Effect": "Allow",
      "Resource": [
        "*"
      ],
      "Action": [
        "logs:CreateLogGroup",
        "logs:CreateLogStream",
        "logs:PutLogEvents"
      ]
    }
  ]
}
POLICY
}

resource "aws_iam_role_policy_attachment" "project-name-codebuild-role-policy-bucket" {
  policy_arn = "${aws_iam_policy.project-name-code-pipeline-bucket-access.arn}"
  role = "${aws_iam_role.project-name-codebuild-role.name}"
}

/************************************************
 * Code Pipeline
 ***********************************************/

resource "aws_codepipeline" "project-name-code-pipeline" {
  name = "${var.project}-code-pipeline"
  role_arn = "${aws_iam_role.project-name-code-pipeline-role.arn}"

  artifact_store {
    location = "${aws_s3_bucket.project-name-code-pipeline-bucket.bucket}"
    type = "S3"
  }

  stage {
    name = "Source"

    action {
      name = "Source"
      category = "Source"
      owner = "ThirdParty"
      provider = "GitHub"
      version = "1"
      output_artifacts = [
        "source"]

      configuration {
        Owner = "Owner"
        Repo = "project-name"
        Branch = "master"
        OAuthToken = "${var.github-token}"
      }
    }
  }

  stage {
    name = "Build-Everything"

    action {
      name = "Build"
      category = "Build"
      owner = "AWS"
      provider = "CodeBuild"
      input_artifacts = [
        "source"]
      output_artifacts = [
        "build"]
      version = "1"

      configuration {
        ProjectName = "${aws_codebuild_project.project-name-codebuild.name}"
      }
    }
  }

  stage {
    name = "Deploy"

    action {
      name = "Deploy"
      category = "Deploy"
      owner = "AWS"
      provider = "ElasticBeanstalk"
      input_artifacts = [
        "build"]
      version = "1"

      configuration {
        ApplicationName = "${aws_elastic_beanstalk_application.project-name.name}"
        EnvironmentName = "${aws_elastic_beanstalk_environment.project-name-environment.name}"
      }
    }
  }
}

resource "aws_s3_bucket" "project-name-code-pipeline-bucket" {
  bucket = "${var.project}-code-pipeline-bucket"
  acl = "private"
}

resource "aws_iam_policy" "project-name-code-pipeline-bucket-access" {
  name = "${var.project}-code-pipeline-bucket-access"

  policy = <<POLICY
{
  "Version": "2012-10-17",
  "Statement": [
      {
        "Effect":"Allow",
        "Resource": [
          "${aws_s3_bucket.project-name-code-pipeline-bucket.arn}",
          "${aws_s3_bucket.project-name-code-pipeline-bucket.arn}/*"
        ],
        "Action": [
          "s3:CreateBucket",
          "s3:GetAccelerateConfiguration",
          "s3:GetBucketAcl",
          "s3:GetBucketCORS",
          "s3:GetBucketLocation",
          "s3:GetBucketLogging",
          "s3:GetBucketNotification",
          "s3:GetBucketPolicy",
          "s3:GetBucketRequestPayment",
          "s3:GetBucketTagging",
          "s3:GetBucketVersioning",
          "s3:GetBucketWebsite",
          "s3:GetLifecycleConfiguration",
          "s3:GetObject",
          "s3:GetObjectAcl",
          "s3:GetObjectTagging",
          "s3:GetObjectTorrent",
          "s3:GetObjectVersion",
          "s3:GetObjectVersionAcl",
          "s3:GetObjectVersionTagging",
          "s3:GetObjectVersionTorrent",
          "s3:GetReplicationConfiguration",
          "s3:ListAllMyBuckets",
          "s3:ListBucket",
          "s3:ListBucketMultipartUploads",
          "s3:ListBucketVersions",
          "s3:ListMultipartUploadParts",
          "s3:PutObject"
        ]
      }
  ]
}
POLICY
}

resource "aws_iam_role" "project-name-code-pipeline-role" {
  name = "${var.project}-code-pipeline-role"

  assume_role_policy = <<EOF
{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Effect": "Allow",
      "Principal": {
        "Service": "codepipeline.amazonaws.com"
      },
      "Action": "sts:AssumeRole"
    }
  ]
}
EOF
}

resource "aws_iam_role_policy" "project-name-code-pipeline-role-policy" {
  name = "${var.project}-code-pipeline-role-policy"
  role = "${aws_iam_role.project-name-code-pipeline-role.id}"

  policy = <<EOF
{
    "Statement": [
        {
            "Action": [
                "s3:GetObject",
                "s3:GetObjectVersion",
                "s3:GetBucketVersioning"
            ],
            "Resource": "*",
            "Effect": "Allow"
        },
        {
            "Action": [
                "s3:PutObject"
            ],
            "Resource": [
                "arn:aws:s3:::codepipeline*",
                "arn:aws:s3:::elasticbeanstalk*"
            ],
            "Effect": "Allow"
        },
        {
            "Action": [
                "codedeploy:CreateDeployment",
                "codedeploy:GetApplicationRevision",
                "codedeploy:GetDeployment",
                "codedeploy:GetDeploymentConfig",
                "codedeploy:RegisterApplicationRevision"
            ],
            "Resource": "*",
            "Effect": "Allow"
        },
        {
            "Action": [
                "elasticbeanstalk:CreateApplicationVersion",
                "elasticbeanstalk:DescribeApplicationVersions",
                "elasticbeanstalk:DescribeEnvironments",
                "elasticbeanstalk:DescribeEvents",
                "elasticbeanstalk:UpdateEnvironment",
                "autoscaling:DescribeAutoScalingGroups",
                "autoscaling:DescribeLaunchConfigurations",
                "autoscaling:DescribeScalingActivities",
                "autoscaling:ResumeProcesses",
                "autoscaling:SuspendProcesses",
                "cloudformation:GetTemplate",
                "cloudformation:DescribeStackResource",
                "cloudformation:DescribeStackResources",
                "cloudformation:DescribeStackEvents",
                "cloudformation:DescribeStacks",
                "cloudformation:UpdateStack",
                "ec2:DescribeInstances",
                "ec2:DescribeImages",
                "ec2:DescribeAddresses",
                "ec2:DescribeSubnets",
                "ec2:DescribeVpcs",
                "ec2:DescribeSecurityGroups",
                "ec2:DescribeKeyPairs",
                "elasticloadbalancing:DescribeLoadBalancers",
                "rds:DescribeDBInstances",
                "rds:DescribeOrderableDBInstanceOptions",
                "sns:ListSubscriptionsByTopic"
            ],
            "Resource": "*",
            "Effect": "Allow"
        },
        {
            "Action": [
                "lambda:invokefunction",
                "lambda:listfunctions"
            ],
            "Resource": "*",
            "Effect": "Allow"
        },
        {
            "Action": [
                "s3:ListBucket",
                "s3:GetBucketPolicy",
                "s3:GetObjectAcl",
                "s3:PutObjectAcl",
                "s3:DeleteObject"
            ],
            "Resource": "arn:aws:s3:::elasticbeanstalk*",
            "Effect": "Allow"
        }
    ],
    "Version": "2012-10-17"
}
EOF
}

resource "aws_iam_role_policy_attachment" "project-name-code-pipeline-role-policy-attachment" {
  policy_arn = "${aws_iam_policy.project-name-code-pipeline-bucket-access.arn}"
  role = "${aws_iam_role.project-name-code-pipeline-role.name}"
}
</code>```

答:
Came across the same problem,
the issue is that you need to enable s3 access to "arn:aws:s3:::elasticbeanstalk*"

Agree that error message is kind of obscure

Body:
I'm trying to create a pipeline to deploy on Beanstalk but I constantly get an error in the deploy section of the pipeline:

Insufficient permissions
The provided role does not have sufficient permissions to access
Elastic Beanstalk: Access Denied

What am I missing?

/************************************************
 * Code Build
 ***********************************************/

resource "aws_codebuild_project" "project-name-codebuild" {
  name = "${var.project}-codebuild"
  build_timeout = "15"
  service_role = "${aws_iam_role.project-name-codebuild-role.arn}"

  artifacts {
    type = "CODEPIPELINE"
  }

  environment {
    compute_type = "BUILD_GENERAL1_SMALL"
    type = "LINUX_CONTAINER"
    image = "aws/codebuild/java:openjdk-8"
  }

  source {
    type = "CODEPIPELINE"
  }

  tags {
    Name = "${var.project}"
    Environment = "${var.environment}"
  }
}

resource "aws_ecr_repository" "project-name-ecr-repository" {
  name = "${var.project}-ecr-repository"
}

resource "aws_iam_role" "project-name-codebuild-role" {
  name = "${var.project}-codebuild-role"

  assume_role_policy = <<EOF
{
      "Version": "2012-10-17",
      "Statement": [
        {
          "Effect": "Allow",
          "Principal": {
            "Service": "codebuild.amazonaws.com"
          },
          "Action": "sts:AssumeRole"
        }
      ]
    }
EOF
}

resource "aws_iam_role_policy" "project-name-codebuild-role-policy" {
  role = "${aws_iam_role.project-name-codebuild-role.id}"

  policy = <<POLICY
{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Effect": "Allow",
      "Resource": [
        "*"
      ],
      "Action": [
        "logs:CreateLogGroup",
        "logs:CreateLogStream",
        "logs:PutLogEvents"
      ]
    }
  ]
}
POLICY
}

resource "aws_iam_role_policy_attachment" "project-name-codebuild-role-policy-bucket" {
  policy_arn = "${aws_iam_policy.project-name-code-pipeline-bucket-access.arn}"
  role = "${aws_iam_role.project-name-codebuild-role.name}"
}

/************************************************
 * Code Pipeline
 ***********************************************/

resource "aws_codepipeline" "project-name-code-pipeline" {
  name = "${var.project}-code-pipeline"
  role_arn = "${aws_iam_role.project-name-code-pipeline-role.arn}"

  artifact_store {
    location = "${aws_s3_bucket.project-name-code-pipeline-bucket.bucket}"
    type = "S3"
  }

  stage {
    name = "Source"

    action {
      name = "Source"
      category = "Source"
      owner = "ThirdParty"
      provider = "GitHub"
      version = "1"
      output_artifacts = [
        "source"]

      configuration {
        Owner = "Owner"
        Repo = "project-name"
        Branch = "master"
        OAuthToken = "${var.github-token}"
      }
    }
  }

  stage {
    name = "Build-Everything"

    action {
      name = "Build"
      category = "Build"
      owner = "AWS"
      provider = "CodeBuild"
      input_artifacts = [
        "source"]
      output_artifacts = [
        "build"]
      version = "1"

      configuration {
        ProjectName = "${aws_codebuild_project.project-name-codebuild.name}"
      }
    }
  }

  stage {
    name = "Deploy"

    action {
      name = "Deploy"
      category = "Deploy"
      owner = "AWS"
      provider = "ElasticBeanstalk"
      input_artifacts = [
        "build"]
      version = "1"

      configuration {
        ApplicationName = "${aws_elastic_beanstalk_application.project-name.name}"
        EnvironmentName = "${aws_elastic_beanstalk_environment.project-name-environment.name}"
      }
    }
  }
}

resource "aws_s3_bucket" "project-name-code-pipeline-bucket" {
  bucket = "${var.project}-code-pipeline-bucket"
  acl = "private"
}

resource "aws_iam_policy" "project-name-code-pipeline-bucket-access" {
  name = "${var.project}-code-pipeline-bucket-access"

  policy = <<POLICY
{
  "Version": "2012-10-17",
  "Statement": [
      {
        "Effect":"Allow",
        "Resource": [
          "${aws_s3_bucket.project-name-code-pipeline-bucket.arn}",
          "${aws_s3_bucket.project-name-code-pipeline-bucket.arn}/*"
        ],
        "Action": [
          "s3:CreateBucket",
          "s3:GetAccelerateConfiguration",
          "s3:GetBucketAcl",
          "s3:GetBucketCORS",
          "s3:GetBucketLocation",
          "s3:GetBucketLogging",
          "s3:GetBucketNotification",
          "s3:GetBucketPolicy",
          "s3:GetBucketRequestPayment",
          "s3:GetBucketTagging",
          "s3:GetBucketVersioning",
          "s3:GetBucketWebsite",
          "s3:GetLifecycleConfiguration",
          "s3:GetObject",
          "s3:GetObjectAcl",
          "s3:GetObjectTagging",
          "s3:GetObjectTorrent",
          "s3:GetObjectVersion",
          "s3:GetObjectVersionAcl",
          "s3:GetObjectVersionTagging",
          "s3:GetObjectVersionTorrent",
          "s3:GetReplicationConfiguration",
          "s3:ListAllMyBuckets",
          "s3:ListBucket",
          "s3:ListBucketMultipartUploads",
          "s3:ListBucketVersions",
          "s3:ListMultipartUploadParts",
          "s3:PutObject"
        ]
      }
  ]
}
POLICY
}

resource "aws_iam_role" "project-name-code-pipeline-role" {
  name = "${var.project}-code-pipeline-role"

  assume_role_policy = <<EOF
{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Effect": "Allow",
      "Principal": {
        "Service": "codepipeline.amazonaws.com"
      },
      "Action": "sts:AssumeRole"
    }
  ]
}
EOF
}

resource "aws_iam_role_policy" "project-name-code-pipeline-role-policy" {
  name = "${var.project}-code-pipeline-role-policy"
  role = "${aws_iam_role.project-name-code-pipeline-role.id}"

  policy = <<EOF
{
    "Statement": [
        {
            "Action": [
                "s3:GetObject",
                "s3:GetObjectVersion",
                "s3:GetBucketVersioning"
            ],
            "Resource": "*",
            "Effect": "Allow"
        },
        {
            "Action": [
                "s3:PutObject"
            ],
            "Resource": [
                "arn:aws:s3:::codepipeline*",
                "arn:aws:s3:::elasticbeanstalk*"
            ],
            "Effect": "Allow"
        },
        {
            "Action": [
                "codedeploy:CreateDeployment",
                "codedeploy:GetApplicationRevision",
                "codedeploy:GetDeployment",
                "codedeploy:GetDeploymentConfig",
                "codedeploy:RegisterApplicationRevision"
            ],
            "Resource": "*",
            "Effect": "Allow"
        },
        {
            "Action": [
                "elasticbeanstalk:CreateApplicationVersion",
                "elasticbeanstalk:DescribeApplicationVersions",
                "elasticbeanstalk:DescribeEnvironments",
                "elasticbeanstalk:DescribeEvents",
                "elasticbeanstalk:UpdateEnvironment",
                "autoscaling:DescribeAutoScalingGroups",
                "autoscaling:DescribeLaunchConfigurations",
                "autoscaling:DescribeScalingActivities",
                "autoscaling:ResumeProcesses",
                "autoscaling:SuspendProcesses",
                "cloudformation:GetTemplate",
                "cloudformation:DescribeStackResource",
                "cloudformation:DescribeStackResources",
                "cloudformation:DescribeStackEvents",
                "cloudformation:DescribeStacks",
                "cloudformation:UpdateStack",
                "ec2:DescribeInstances",
                "ec2:DescribeImages",
                "ec2:DescribeAddresses",
                "ec2:DescribeSubnets",
                "ec2:DescribeVpcs",
                "ec2:DescribeSecurityGroups",
                "ec2:DescribeKeyPairs",
                "elasticloadbalancing:DescribeLoadBalancers",
                "rds:DescribeDBInstances",
                "rds:DescribeOrderableDBInstanceOptions",
                "sns:ListSubscriptionsByTopic"
            ],
            "Resource": "*",
            "Effect": "Allow"
        },
        {
            "Action": [
                "lambda:invokefunction",
                "lambda:listfunctions"
            ],
            "Resource": "*",
            "Effect": "Allow"
        },
        {
            "Action": [
                "s3:ListBucket",
                "s3:GetBucketPolicy",
                "s3:GetObjectAcl",
                "s3:PutObjectAcl",
                "s3:DeleteObject"
            ],
            "Resource": "arn:aws:s3:::elasticbeanstalk*",
            "Effect": "Allow"
        }
    ],
    "Version": "2012-10-17"
}
EOF
}

resource "aws_iam_role_policy_attachment" "project-name-code-pipeline-role-policy-attachment" {
  policy_arn = "${aws_iam_policy.project-name-code-pipeline-bucket-access.arn}"
  role = "${aws_iam_role.project-name-code-pipeline-role.name}"
}


问:
why importing CSSRulePlugin in Next.js results in error?
I am trying to use GSAP library in my Next.js project i downloaded the npm version of the library
from react jsap.

but when i import it like this:

```<code>import { gsap } from "gsap";
import { CSSRulePlugin } from "gsap/CSSRulePlugin";
</code>```

it throws an error, the error seems to be caused by CSSRulePlugIn since when i remove it from imports everything is fine.

the error:

答:
apparently this error occurs because GSAP tries to access the window element of the client browser but since i was using it in Next.js (SSR) so it would result in that error since there was no window to get a hold of.

so i ended up solving the problem by importing CSSRulePlugin only after making sure that the code runs in the client side, and for that i imported it inside useEffect method and it worked.

here is the code in my case:

```<code>  useEffect(() => {
      const GSAP = require("gsap/CSSRulePlugin");
      const { CSSRulePlugin } = GSAP;
      gsap.registerPlugin(CSSRulePlugin);
      // do whatever you want to do with the plugin, its Working now...
      // for example
      let imageReveal = CSSRulePlugin.getRule(".container:after");
  }, []);
</code>```

Body:
I am trying to use GSAP library in my Next.js project i downloaded the npm version of the library
from react jsap.

but when i import it like this:

import { gsap } from "gsap";
import { CSSRulePlugin } from "gsap/CSSRulePlugin";

it throws an error, the error seems to be caused by CSSRulePlugIn since when i remove it from imports everything is fine.

the error:

Body:
apparently this error occurs because GSAP tries to access the window element of the client browser but since i was using it in Next.js (SSR) so it would result in that error since there was no window to get a hold of.

so i ended up solving the problem by importing CSSRulePlugin only after making sure that the code runs in the client side, and for that i imported it inside useEffect method and it worked.

here is the code in my case:

  useEffect(() => {
      const GSAP = require("gsap/CSSRulePlugin");
      const { CSSRulePlugin } = GSAP;
      gsap.registerPlugin(CSSRulePlugin);
      // do whatever you want to do with the plugin, its Working now...
      // for example
      let imageReveal = CSSRulePlugin.getRule(".container:after");
  }, []);


问:
How to rename JPG files with running order using Python
I quite new in Python programming and i try to rename 100 files with ".jpg" extention, located in specific folder using pyhthon.

I need that the files will be renamed by running order start from number 1. This is the code i start writing:

```<code>import os,glob,fnmatch

os.chdir(r"G:\desktop\Project\test")
for files in glob.glob("*.jpg"):
    print files
</code>```

When i run it, i get:

```<code>>>>
er3.jpg
IMG-20160209-ssdeWA0000.jpg
IMG-20160209-WA0000.jpg
sd4.jpg
tyu2.jpg
uj7.jpg
we3.jpg
yh7.jpg
>>>
</code>```

so the code, till now is OK.

For example my folder is:

and i need that all the files name will be:
1,2,3,4 - with running order names. Is it possible with python 2.7?

答:
```<code>import os
from os import path
os.chdir("//Users//User1//Desktop//newd//pics")

for file in os.listdir():
    name,ext=path.splitext(file)
    if ext == '.jpeg':
        dst= '{}.jpg'.format(name)
        os.rename(file,dst)
</code>```

Body:
I quite new in Python programming and i try to rename 100 files with ".jpg" extention, located in specific folder using pyhthon.

I need that the files will be renamed by running order start from number 1. This is the code i start writing:

import os,glob,fnmatch

os.chdir(r"G:\desktop\Project\test")
for files in glob.glob("*.jpg"):
    print files

When i run it, i get:

>>>
er3.jpg
IMG-20160209-ssdeWA0000.jpg
IMG-20160209-WA0000.jpg
sd4.jpg
tyu2.jpg
uj7.jpg
we3.jpg
yh7.jpg
>>>

so the code, till now is OK.

For example my folder is:

and i need that all the files name will be:
1,2,3,4 - with running order names. Is it possible with python 2.7?


问:
Create multiple files with Powershell?
From this answer I can create multiple files a.txt, b.txt, ... , z.txt. in Bash with:

```<code>touch {a..z}.txt
</code>```

Or 152 with:

```<code>touch {{a..z},{A..Z},{0..99}}.txt
</code>```

How can I do this in Powershell?
I know New-Item a.txt, but If I want multiple files as above?

For curiosity, what are the equivalent commands in Command Prompt (cmd.exe)?

答:
Very simple, take a look:

```<code>("Text1.txt","Text2.txt", "Text3.txt") | foreach { New-Item -Path "X" -Name "$_.txt" }
</code>```

You will replace X of course with the path where you want the files to be created.

If further explanation is required, let me know.

Title: Create multiple files with Powershell?

Body:
From this answer I can create multiple files a.txt, b.txt, ... , z.txt. in Bash with:

touch {a..z}.txt

Or 152 with:

touch {{a..z},{A..Z},{0..99}}.txt

How can I do this in Powershell?
I know New-Item a.txt, but If I want multiple files as above?

For curiosity, what are the equivalent commands in Command Prompt (cmd.exe)?

Body:
Very simple, take a look:

("Text1.txt","Text2.txt", "Text3.txt") | foreach { New-Item -Path "X" -Name "$_.txt" }

You will replace X of course with the path where you want the files to be created.

If further explanation is required, let me know.


问:
Django Queryset How to add field using reverse foreign key
I have below two models,

```<code>class Person(models.Model):
    name = models.CharField(unique=True, max_length=45)
    nationality = models.TextField(blank=True, null=True)
    created_at = models.DateTimeField(auto_now_add=True, blank=True, null=True)

class UserOption(DFModel):
    user = models.ForeignKey('User', on_delete=models.CASCADE)
    option = models.CharField(max_length=40)
    person = models.ForeignKey('Person', on_delete=models.PROTECT, null=True)
    status = models.BooleanField(default=False)
</code>```

Below is the viewset

```<code>class PersonViewSet(viewsets.ModelViewSet):
    queryset = apis_models.Person.objects.all()
    serializer_class = apis_serializers.PersonSerializer
    permission_classes = [HasPermPage]
</code>```

In above Person view I need to add useroption value associated with it for current logged in user.
UserOption model has User as well as Person.

```<code>{
  "id": 151,
  "name": "Emma Watson",
  "nationality": "USA",
  ”option”: “True”.   ##This is what needs to be added
}
</code>```

This is really very complicated and I did not find any answer yet. Please advise.

答:
You can annotate the queryset with an extra attribute:

```<code>from django.db.models import Exists, OuterRef

class PersonViewSet(viewsets.ModelViewSet):
    model = apis_models.Person
    serializer_class = apis_serializers.PersonSerializer
    permission_classes = [HasPermPage]

    def get_queryset(self, *args, **kwargs):
        return super().get_queryset(*args, **kwargs).annotate(
            <b>option=</b>Exists(
                apis_models.UserOption.objects.filter(
                    user_id=self.request.user,
                    person_id=OuterRef('pk'),
                    option='monitor'
                )
            <b>)</b>
        )</code>```

In the serializer, you should add the option field:

```<code>class PersonSerializer(serializers.ModelSerializer):
    <b>option</b> = serializers.BooleanField(<b>read_only=True</b>)

    class Meta:
        model = apis_models.Person
        fields = ('id', 'name', 'nationality', <b>'option'</b>)</code>```

Body:
I have below two models,

class Person(models.Model):
    name = models.CharField(unique=True, max_length=45)
    nationality = models.TextField(blank=True, null=True)
    created_at = models.DateTimeField(auto_now_add=True, blank=True, null=True)

class UserOption(DFModel):
    user = models.ForeignKey('User', on_delete=models.CASCADE)
    option = models.CharField(max_length=40)
    person = models.ForeignKey('Person', on_delete=models.PROTECT, null=True)
    status = models.BooleanField(default=False)

Below is the viewset

class PersonViewSet(viewsets.ModelViewSet):
    queryset = apis_models.Person.objects.all()
    serializer_class = apis_serializers.PersonSerializer
    permission_classes = [HasPermPage]

In above Person view I need to add useroption value associated with it for current logged in user.
UserOption model has User as well as Person.

{
  "id": 151,
  "name": "Emma Watson",
  "nationality": "USA",
  ”option”: “True”.   ##This is what needs to be added
}

This is really very complicated and I did not find any answer yet. Please advise.

Body:
You can annotate the queryset with an extra attribute:

from django.db.models import Exists, OuterRef

class PersonViewSet(viewsets.ModelViewSet):
    model = apis_models.Person
    serializer_class = apis_serializers.PersonSerializer
    permission_classes = [HasPermPage]

    def get_queryset(self, *args, **kwargs):
        return super().get_queryset(*args, **kwargs).annotate(
            option=Exists(
                apis_models.UserOption.objects.filter(
                    user_id=self.request.user,
                    person_id=OuterRef('pk'),
                    option='monitor'
                )
            )
        )

In the serializer, you should add the option field:

class PersonSerializer(serializers.ModelSerializer):
    option = serializers.BooleanField(read_only=True)

    class Meta:
        model = apis_models.Person
        fields = ('id', 'name', 'nationality', 'option')


问:
jquery creating repeteable inner divs dynamically
this is a little bit complicated question. I want to achieve the following behaviour (creating sections dynamically): I'm sending the whole example: E.g. I have parent div and child div inside this parrent. In each div can be some placed some controls (inputs, buttons,...). I have following requirements:

each section can be repeteable (i mean creating it dynamically) max times (maxRepetition)

sections can be nested inside another section (in this example there are only two levels of immersion: parent->child, but it can be also parent->child1->child2->...) and each of these sections must accept requirement 1.

I have spend a lot of time how to achieve this, but not sucesfully. If somebody can help me I will very gratefull.

```<code><html><head>
<title></title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5/jquery.min.js">
</script>

<style type="text/css">
      .border
      {
        border-style:solid;
        border-width:1px;
        border-color:black;
      }
</style>

</head>

<body>
<div id="main">
<div id="parent">
    <table class="border" width=300>
        <tbody>
            <tr>
                <td>
                    <span><input id="field1" type="text" width="100"></span>
                    <p>
                    <div id="child" >
                        <table class="border" width=200>
                            <tbody>
                                <tr>
                                    <td>
                                        <span><input id="field2" type="text" width="100"></span>
                                        <p>
                                    </td>
                                </tr>
                            </tbody>
                        </table>
                    </div>

                    <span id="addSection_child"  onClick="addSection('child', 2)">Add</span>
                    <span id="removeSection_child" onClick="removeSection('child', this)">Remove</span>

                    <p>
                                                                                </td>
            </tr>
        </tbody>
    </table>
</div>
<span id="addSection_parent"  onClick="addSection('parent', 2)">Add</span>
<span id="removeSection_parent" onClick="removeSection('parent', this)">Remove</span>

</div>

<script type="text/javascript">

   function addSection(layoutRowId, maxRepetition)
   {
        var parentDivId = $("#" + layoutRowId).parent().closest('div').attr("id");
        var sectionCount = $("div#" + parentDivId + " div[id = " + layoutRowId + "]").length;

        if (sectionCount > maxRepetition)
            return;

        var layoutRowIdSelector = "#" + layoutRowId;
        $(layoutRowIdSelector).prepend('</p>').clone().insertAfter(layoutRowIdSelector);
   }

   function removeSection(layoutRowId, currentDiv)
   {
        var parentDivId = $(currentDiv).parent().closest('div').attr("id");

        var sectionCount = $("div#" + parentDivId + " div[id ^= " + layoutRowId + "]").length;

        if (sectionCount == 1)
            return;

        var sectionToBeRemovedId = $("#" + parentDivId + " div").filter(":last");

        sectionToBeRemovedId.remove();
   }

</script>
</body>
</html>
</code>```

答:
instead of reading the html of sections you can make a template for parent section and a template for child section then adding action to get html of parent/child template with new IDs then append it to your page. like the following

```<code><div id="main">
    <div id="parent1">
        <table class="border" width="300">
            <tbody>
                <tr>
                    <td>
                        <span>
                            <input id="field1" type="text" width="100"></span>
                        <p>
                            <div id="child1">
                                <table class="border" width="200">
                                    <tbody>
                                        <tr>
                                            <td>
                                                <span>
                                                    <input id="field2" type="text" width="100"></span>
                                                <p>
                                            </td>
                                        </tr>
                                    </tbody>
                                </table>
                            </div> <span id="removeSection_child1" onclick="removeChildSection('1')">Remove child</span>
                            <p>
                    </td>
                </tr>
            </tbody>
        </table>
        <span id="addSection_child1" name="addSection_child" onclick="addChildSection('1')">
                                Add child</span>
    </div>
</div>
<div id="childTemplate" style="display: none">
    <div id="child#index#">
        <table class="border" width="200">
            <tbody>
                <tr>
                    <td>
                        <span>
                            <input id="field1#index#" type="text" width="100"></span>
                        <p>
                    </td>
                </tr>
            </tbody>
        </table><span id="removeSection_child#index#" onclick="removeChildSection('#index#')">
            Remove child</span>
    </div>
    <span id="addSection_child#index#" name="addSection_child#index#" onclick="addChildSection('#parentIndex#')">
        Add child</span>
</div>
<script type="text/javascript">

    function addChildSection(parentIndex) {
        var childTempHtml = $('#childTemplate').html();
        var newIndex = Guid();
        var newHtml = childTempHtml.replace(/#Index#/gi, newIndex);
        newHtml = newHtml.replace(/#parentIndex#/gi, parentIndex);

        var parent = $('#parent' + parentIndex);
        parent.append(newHtml);
    }
    function removeChildSection(index) {
        var childToDelete = $('#child' + index).remove();
        var removespan = $('#removeSection_child' + index).remove();
    }
    function S4() {
        return (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1);
    }
    function Guid() {
        return (S4() + S4() + "-" + S4() + "-" + S4() + "-" + S4() + "-" + S4() + S4() + S4());
    }
</script>
</code>```

you may find the result doesn't like you want but you can use the same technique.

Body:
this is a little bit complicated question. I want to achieve the following behaviour (creating sections dynamically): I'm sending the whole example: E.g. I have parent div and child div inside this parrent. In each div can be some placed some controls (inputs, buttons,...). I have following requirements:

each section can be repeteable (i mean creating it dynamically) max times (maxRepetition)

sections can be nested inside another section (in this example there are only two levels of immersion: parent->child, but it can be also parent->child1->child2->...) and each of these sections must accept requirement 1.

I have spend a lot of time how to achieve this, but not sucesfully. If somebody can help me I will very gratefull.

<title></title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">

                    <input id="field1" type="text" width="100">

                                        <input id="field2" type="text" width="100">

                    Add
                    Remove

Add
Remove

Body:
instead of reading the html of sections you can make a template for parent section and a template for child section then adding action to get html of parent/child template with new IDs then append it to your page. like the following

<div id="main">
    <div id="parent1">
        <table class="border" width="300">
            <tbody>
                <tr>
                    <td>
                        <span>
                            <input id="field1" type="text" width="100"></span>
                        <p>
                            <div id="child1">
                                <table class="border" width="200">
                                    <tbody>
                                        <tr>
                                            <td>
                                                <span>
                                                    <input id="field2" type="text" width="100"></span>
                                                <p>
                                            </td>
                                        </tr>
                                    </tbody>
                                </table>
                            </div> <span id="removeSection_child1" onclick="removeChildSection('1')">Remove child</span>
                            <p>
                    </td>
                </tr>
            </tbody>
        </table>
        <span id="addSection_child1" name="addSection_child" onclick="addChildSection('1')">
                                Add child</span>
    </div>
</div>
<div id="childTemplate" style="display: none">
    <div id="child#index#">
        <table class="border" width="200">
            <tbody>
                <tr>
                    <td>
                        <span>
                            <input id="field1#index#" type="text" width="100"></span>
                        <p>
                    </td>
                </tr>
            </tbody>
        </table><span id="removeSection_child#index#" onclick="removeChildSection('#index#')">
            Remove child</span>
    </div>
    <span id="addSection_child#index#" name="addSection_child#index#" onclick="addChildSection('#parentIndex#')">
        Add child</span>
</div>
<script type="text/javascript">

    function addChildSection(parentIndex) {
        var childTempHtml = $('#childTemplate').html();
        var newIndex = Guid();
        var newHtml = childTempHtml.replace(/#Index#/gi, newIndex);
        newHtml = newHtml.replace(/#parentIndex#/gi, parentIndex);

        var parent = $('#parent' + parentIndex);
        parent.append(newHtml);
    }
    function removeChildSection(index) {
        var childToDelete = $('#child' + index).remove();
        var removespan = $('#removeSection_child' + index).remove();
    }
    function S4() {
        return (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1);
    }
    function Guid() {
        return (S4() + S4() + "-" + S4() + "-" + S4() + "-" + S4() + "-" + S4() + S4() + S4());
    }
</script>

you may find the result doesn't like you want but you can use the same technique.


问:
How to access the elements of global 2d arrays in C?
I am new to C. I declared a 2D global array:

```<code>int allhospitalsdata[4][3] = {{1,100,0},{2,200,0},{3,300,0},{4,400,0}};
</code>```

Then I try to access the value at some index like that:

```<code>if (allhospitalsdata[hospitalid][3]<allhospitalsdata[hospitalid][2])
  {
      //do something
  }
  else
  {
      //do another thing
  }
</code>```

When testing the condition, it always goes to the else block. Why?

答:
Because you're accessing the 4th element of allhospitalsdata[hospitalid], which only contains three elements. In fact, C doesn't prevent you from accessing an array at an invalid index. You have to take care of that yourself. What happens is that in allhospitalsdata[hospitalid][3] (which isn't part of your array!) there is stored something undefined, which, by observing the if condition, is probably greater than or equal to zero. That's why it goes into the else block.

Please note that arrays in C are always zero-indexed, thus allhospitalsdata[0] refers to the data of the first hospital.

I don't know what you're trying to achieve, but imagine the 2D array as a table with rows and columns. For a[x][y], x is used to access a row while y is used to access a column in that row.

If something else has been your question, then please clarify.

Body:
I am new to C. I declared a 2D global array:

int allhospitalsdata[4][3] = {{1,100,0},{2,200,0},{3,300,0},{4,400,0}};

Then I try to access the value at some index like that:

if (allhospitalsdata[hospitalid][3]<allhospitalsdata[hospitalid][2])
  {
      //do something
  }
  else
  {
      //do another thing
  }

When testing the condition, it always goes to the else block. Why?


问:
Why each data type has two choices in pgAdmin 4?
Using pgAdmin 4, defining data type for a table column discover each type has two choices, what's the difference?
for example char has two choices.

答:
Because Postgres does not work like programming data structures. It is not keeping them on memory but disk. So each data structure has a single and fixed length array value. See for more information: https://stackoverflow.com/a/42484838/13638824

Edit for your question (It was too long to be comment):

Writing data structures to a memory and disk is totally different. Memory is dynamic and writing to it is very cheap so it can handle changes in data very fast. But writing to disk is not cheap, when database systems decide to write a data they are trying to be efficient as possible. They are usually using fixed sized allocations in background to improve performance. When you define a Text dbms will not create a string. It will write it to disk as expandable data structure to ensure flexibility and performance. But if you use char[] the length will be predefined so it will be more performant.

TL;DR;

For memory data structures:
char[] == string.
But for DBMS char[] == fixed size byte array and text == flexible size byte array.