问:
Data driven tests. reading parameters from a .json or .yaml file using Selenium Python
I create a framework using Selenium and Python.
My data driven framework consists of 2 files so far:
    The 1st file- Setup.py contains class Actions()
    that consist of all possible functions that I will use
    in my framework, such as:

```<code>def __init__():
def setup():
def tearDown():
def click():
def sendKeys():
</code>```

My click and sendKeys functions have a minimum of 2 parameters.
    They take the first parameter such us :id_for_element,
    xp_for_element, or css_for_element, slicing words until
    they get the 1st two characters and find element by either
    id, xp or any other way. Then they use the 2nd parameter to
    specify  an element's value, and 3rd parameter to specify
    a value for send_keys() function. All of these functions
    are now working, but so far value hardcoded in my test file.

setup.py file:

```<code>from   selenium import webdriver
from   selenium.webdriver.common.by import By
from   selenium.webdriver.common.keys import Keys
from   selenium.webdriver.support.ui import Select
from   selenium.common.exceptions import NoSuchElementException
from   selenium.common.exceptions import NoAlertPresentException

class Actions(object):

    def __init__(self,driver=None):
        if driver != None:
            self.driver = driver

    def setUp(self, browserName):
        if browserName == 'Chrome':
            self.driver = webdriver.Chrome()
            self.driver.delete_all_cookies()
            self.driver.maximize_window()
        elif browserName == 'Safari':
            self.driver = webdriver.Safari()
            self.driver.delete_all_cookies()
            self.driver.maximize_window()
        elif browserName == 'Firefox':
            self.driver = webdriver.Firefox()
            self.driver.delete_all_cookies()
            self.driver.maximize_window()
        self.driver.implicitly_wait(30)

    def tearDown(self, browserName):
        self.driver.quit()

    def webPage(self):
        self.driver.get('https://www.yahoo.com')

    def click(self, elemLocator, elemValue):
        elp = elemLocator
        flp = slice(0,2)
        if elp[flp] == 'id':#return by ID
            try:
                self.driver.find_element_by_id(elemValue).click()
            except:
                pass
        elif elp[flp] == 'xp':#return by XPATH
            try:
                self.driver.find_element_by_xpath(elemValue).click()
            except:
                pass

    def sendKeys(self, elemLocator, elemValue, messageValue):
        elp = elemLocator
        flp = slice(0,2)
        if elp[flp] == 'id':#return by ID
            try:
                self.driver.find_element_by_id(elemValue).click()
                self.driver.find_element_by_id(elemValue).clear()
                self.driver.find_element_by_id(elemValue).send_keys(messageValue)
            except:
                pass

        elif elp[flp] == 'xp':#return by XPATH
            try:
                self.driver.find_element_by_xpath(elemValue).click()
                self.driver.find_element_by_xpath(elemValue).clear()
                self.driver.find_element_by_xpath(elemValue).send_keys(messageValue)
            except:
                pass

#test.py file

    from Setup import Actions

class test_case_1: #find element by id

    action = Actions(object)
    action.setUp('Chrome')
    action.webPage()
    action.click('id_of_yahoo_logo', 'uh-logo')
    action.tearDown('Chrome')

class test_case_2: #find element by xpath

    action = Actions(object)
    action.setUp('Chrome')
    action.webPage()
    action.click('xp_of signIn_button', '//*[@id="uh-signin"]')
    action.tearDown('Chrome')

class test_case_3: #login to email

    action = Actions(object)
    action.setUp('Chrome')
    action.webPage()
    action.click('xp_of signIn_button', '//*[@id="uh-signin"]')
    action.sendKeys('id_username_login_inp_field','login-username','deniska')
    action.click('id_of submit_button', 'login-signin')
    action.tearDown('Chrome')
</code>```

Instead I am trying to pass value for parameters from another
    file as described by the best practices for data driven testing
    framework. My next step is to create a data.json file that
    I will use to map out all elements of the DOM in the following
    format: "id_login_button":"some id value", "xp_input_field":"some
    xp value" etc. Can someone, please, help me figure out
    how to implement this technique?

答:
Here is the simple approach if you want to use the json as your uiRepo.

sample.json:

```<code>{
    "id_of_yahoo_logo":"uh-logo",
    "xp_of_signIn_button":"//*[@id='uh-signin']",
    "id_username_login_inp_field":"New York",
    "id_of_submit_button":"login-signin"
}
</code>```

test.py

```<code># you have to just specify the name as shown below
action.click('xp_of_signIn_button)
</code>```

Reading value in Actions.py:

```<code>import json

#parse json
with open('sample.json') as f:
    uiRepo = json.load(f)

# update the generic methods to get the property form json
print(uiRepo['id_of_yahoo_logo'])
</code>```

Edit 1:setup.py Un-Tested updates

```<code>from   selenium import webdriver
from   selenium.webdriver.common.by import By
from   selenium.webdriver.common.keys import Keys
from   selenium.webdriver.support.ui import Select
from   selenium.common.exceptions import NoSuchElementException
from   selenium.common.exceptions import NoAlertPresentException
import json

class Actions(object):
    # initialize uiRepo
    uiRepo = None
    def __init__(self,driver=None):
        if driver != None:
            self.driver = driver
            # load the uiRepo from json when you init the driver
            with open('sample.json') as repo:
                uiRepo = json.load(repo)

    def setUp(self, browserName):
        browserName = browserName.lower()
        if browserName == 'chrome':
            self.driver = webdriver.Chrome()
        elif browserName == 'safari':
            self.driver = webdriver.Safari()
        elif browserName == 'firefox':
            self.driver = webdriver.Firefox()
        self.driver.delete_all_cookies() #< === moved this line
        self.driver.maximize_window() #< === moved this line
        self.driver.implicitly_wait(30)

    def tearDown(self): #< === Removed browser here as you don't need browser name while closing it.
        self.driver.quit()

    def webPage(self,url): #< === Added url as param, rather hard code
        self.driver.get(url)

    # new method to get the element based on the jsonKey
    def getElement(self, jsonKey):
        locatorStrategy = jsonKey[:2]  # <=== getting first 2 chars to figure out if it's id/xp
        locator = uiRepo[jsonKey]  # < == getting value from json
        ele = None
        try:
            if locatorStrategy == 'id':  # return by ID
                ele =  self.driver.find_element_by_id(locator).click()  # <=== using the locator got from json
            elif locatorStrategy == 'xp':  # return by XPATH
                ele =  self.driver.find_element_by_xpath(locator).click()
        except:
            pass
        # if you want you can add additional logic something like highlighting the element
        return ele

    def click(self, jsonKey): # < ==== updated method to accept only jsonElementName (Removed the element value param)
        ele = self.findElement(jsonKey)
        ele.click()
</code>```

Body:
I create a framework using Selenium and Python.
My data driven framework consists of 2 files so far:
    The 1st file- Setup.py contains class Actions()
    that consist of all possible functions that I will use
    in my framework, such as:

def __init__():
def setup():
def tearDown():
def click():
def sendKeys():

My click and sendKeys functions have a minimum of 2 parameters.
    They take the first parameter such us :id_for_element,
    xp_for_element, or css_for_element, slicing words until
    they get the 1st two characters and find element by either
    id, xp or any other way. Then they use the 2nd parameter to
    specify  an element's value, and 3rd parameter to specify
    a value for send_keys() function. All of these functions
    are now working, but so far value hardcoded in my test file.

setup.py file:

from   selenium import webdriver
from   selenium.webdriver.common.by import By
from   selenium.webdriver.common.keys import Keys
from   selenium.webdriver.support.ui import Select
from   selenium.common.exceptions import NoSuchElementException
from   selenium.common.exceptions import NoAlertPresentException

class Actions(object):

    def __init__(self,driver=None):
        if driver != None:
            self.driver = driver

    def setUp(self, browserName):
        if browserName == 'Chrome':
            self.driver = webdriver.Chrome()
            self.driver.delete_all_cookies()
            self.driver.maximize_window()
        elif browserName == 'Safari':
            self.driver = webdriver.Safari()
            self.driver.delete_all_cookies()
            self.driver.maximize_window()
        elif browserName == 'Firefox':
            self.driver = webdriver.Firefox()
            self.driver.delete_all_cookies()
            self.driver.maximize_window()
        self.driver.implicitly_wait(30)

    def tearDown(self, browserName):
        self.driver.quit()

    def webPage(self):
        self.driver.get('https://www.yahoo.com')

    def click(self, elemLocator, elemValue):
        elp = elemLocator
        flp = slice(0,2)
        if elp[flp] == 'id':#return by ID
            try:
                self.driver.find_element_by_id(elemValue).click()
            except:
                pass
        elif elp[flp] == 'xp':#return by XPATH
            try:
                self.driver.find_element_by_xpath(elemValue).click()
            except:
                pass

    def sendKeys(self, elemLocator, elemValue, messageValue):
        elp = elemLocator
        flp = slice(0,2)
        if elp[flp] == 'id':#return by ID
            try:
                self.driver.find_element_by_id(elemValue).click()
                self.driver.find_element_by_id(elemValue).clear()
                self.driver.find_element_by_id(elemValue).send_keys(messageValue)
            except:
                pass

        elif elp[flp] == 'xp':#return by XPATH
            try:
                self.driver.find_element_by_xpath(elemValue).click()
                self.driver.find_element_by_xpath(elemValue).clear()
                self.driver.find_element_by_xpath(elemValue).send_keys(messageValue)
            except:
                pass

#test.py file

    from Setup import Actions

class test_case_1: #find element by id

    action = Actions(object)
    action.setUp('Chrome')
    action.webPage()
    action.click('id_of_yahoo_logo', 'uh-logo')
    action.tearDown('Chrome')

class test_case_2: #find element by xpath

    action = Actions(object)
    action.setUp('Chrome')
    action.webPage()
    action.click('xp_of signIn_button', '//*[@id="uh-signin"]')
    action.tearDown('Chrome')

class test_case_3: #login to email

    action = Actions(object)
    action.setUp('Chrome')
    action.webPage()
    action.click('xp_of signIn_button', '//*[@id="uh-signin"]')
    action.sendKeys('id_username_login_inp_field','login-username','deniska')
    action.click('id_of submit_button', 'login-signin')
    action.tearDown('Chrome')

Instead I am trying to pass value for parameters from another
    file as described by the best practices for data driven testing
    framework. My next step is to create a data.json file that
    I will use to map out all elements of the DOM in the following
    format: "id_login_button":"some id value", "xp_input_field":"some
    xp value" etc. Can someone, please, help me figure out
    how to implement this technique?

Body:
Here is the simple approach if you want to use the json as your uiRepo.

sample.json:

{
    "id_of_yahoo_logo":"uh-logo",
    "xp_of_signIn_button":"//*[@id='uh-signin']",
    "id_username_login_inp_field":"New York",
    "id_of_submit_button":"login-signin"
}

test.py

# you have to just specify the name as shown below
action.click('xp_of_signIn_button)

Reading value in Actions.py:

import json

#parse json
with open('sample.json') as f:
    uiRepo = json.load(f)

# update the generic methods to get the property form json
print(uiRepo['id_of_yahoo_logo'])

Edit 1:setup.py Un-Tested updates

from   selenium import webdriver
from   selenium.webdriver.common.by import By
from   selenium.webdriver.common.keys import Keys
from   selenium.webdriver.support.ui import Select
from   selenium.common.exceptions import NoSuchElementException
from   selenium.common.exceptions import NoAlertPresentException
import json

class Actions(object):
    # initialize uiRepo
    uiRepo = None
    def __init__(self,driver=None):
        if driver != None:
            self.driver = driver
            # load the uiRepo from json when you init the driver
            with open('sample.json') as repo:
                uiRepo = json.load(repo)

    def setUp(self, browserName):
        browserName = browserName.lower()
        if browserName == 'chrome':
            self.driver = webdriver.Chrome()
        elif browserName == 'safari':
            self.driver = webdriver.Safari()
        elif browserName == 'firefox':
            self.driver = webdriver.Firefox()
        self.driver.delete_all_cookies() #< === moved this line
        self.driver.maximize_window() #< === moved this line
        self.driver.implicitly_wait(30)

    def tearDown(self): #< === Removed browser here as you don't need browser name while closing it.
        self.driver.quit()

    def webPage(self,url): #< === Added url as param, rather hard code
        self.driver.get(url)

    # new method to get the element based on the jsonKey
    def getElement(self, jsonKey):
        locatorStrategy = jsonKey[:2]  # <=== getting first 2 chars to figure out if it's id/xp
        locator = uiRepo[jsonKey]  # < == getting value from json
        ele = None
        try:
            if locatorStrategy == 'id':  # return by ID
                ele =  self.driver.find_element_by_id(locator).click()  # <=== using the locator got from json
            elif locatorStrategy == 'xp':  # return by XPATH
                ele =  self.driver.find_element_by_xpath(locator).click()
        except:
            pass
        # if you want you can add additional logic something like highlighting the element
        return ele

    def click(self, jsonKey): # < ==== updated method to accept only jsonElementName (Removed the element value param)
        ele = self.findElement(jsonKey)
        ele.click()


来源: stackexchange

问:
tortoise svn always merging 45 extra files
When we do our branching and merging with svn, we always have the same thing happen.

We get a latest copy of the trunk.

Create a branch and switch.

Make some small change on one file in the branch.

Merge branch back into trunk.

At this point, we'll have our one file that needs to be comittied, plus the same 45 extra files. This happens on every single branch and merge, and its always the same 45 extra files. I have no idea how to fix the problem, but its extremely annoying.

Has anyone ever seen this before?

UPDATE: When I do the commit, the files that I actually changed have their Text Status as modified and their property status as blank. The "45 files" are all Text Status normal, Property Status modified.

答:
Read the detailed article at http://www.collab.net/community/subversion/articles/merge-info.html

It's long but worthwhile. Note in particular the suggestions in the "Parting Thoughts" section at the end, which include hints for reducing mergeinfo noise.

Also, instead of using svn propdel to clean up unwanted mergeinfo, consider using svn merge with the --record-only option.

ContentLicense: CC BY-SA 2.5

ContentLicense: CC BY-SA 3.0


问:
Why does this acquire and release memory fence not give a consistent value?
im just exploring the use of acquire and release memory fences and  dont understand why i get the value output to zero sometimes and not the value of 2 all the time

I ran the program a number of times , and assumed the atomic store before the release barrier and the atomic load after the acquire barrier would ensure the values always would synchronise

```<code>#include <iostream>
#include <thread>
#include <atomic>

std::atomic<int>x;

void write()
{

    x.store(2,std::memory_order_relaxed);

    std::atomic_thread_fence(std::memory_order_release);

}

void read()
{

    std::atomic_thread_fence(std::memory_order_acquire);

    // THIS DOES NOT GIVE THE EXPECTED VALUE OF 2 SOMETIMES
    std::cout<<x.load(std::memory_order_relaxed)<<std::endl;

}

int main()
{

std::thread t1(write);
std::thread t2(read);
t1.join();
t2.join();
return 0;
}
</code>```

the atomic varible x gives a value of 0 sometimes

答:
The reasons is simple: your fences accomplish exactly nothing and cannot have any use here anyway because there is no write that the fence would make visible (on the release side) to the acquiring side.

The simple answer is that the reading thread can run first and obviously will not see any write if it does.

The longer answer is that when your code has a race, as any code that uses either mutexes or atomics in a non trivial way, it must be prepared for any race outcome! So you has to make sure that not reading the value written by a write will not break your code.

ADDITIONAL EXPLANATION

A way to explain rel/ack semantics is:

release means "I have accomplished something" and I set that atomic object to some value to publish that claim;

acquire means "have you accomplished something?" and I read that atomic object to see if it contains the claim.

So release before you have accomplished anything is meaningless and an acquire that throws away the information containing the claim, as in (void)x.load(memory_order_acquire) is generally meaningless as there is no knowledge (in general) of what was acquired, which is to say of what was accomplished. (The exception to that rule is when a thread had relaxed loads or RMW operations.)

ContentLicense: CC BY-SA 4.0

Body:
im just exploring the use of acquire and release memory fences and  dont understand why i get the value output to zero sometimes and not the value of 2 all the time

I ran the program a number of times , and assumed the atomic store before the release barrier and the atomic load after the acquire barrier would ensure the values always would synchronise

#include <iostream>
#include <thread>
#include <atomic>

std::atomic<int>x;

void write()
{

    x.store(2,std::memory_order_relaxed);

    std::atomic_thread_fence(std::memory_order_release);

}

void read()
{

    std::atomic_thread_fence(std::memory_order_acquire);

    // THIS DOES NOT GIVE THE EXPECTED VALUE OF 2 SOMETIMES
    std::cout<<x.load(std::memory_order_relaxed)<<std::endl;

}

int main()
{

std::thread t1(write);
std::thread t2(read);
t1.join();
t2.join();
return 0;
}

the atomic varible x gives a value of 0 sometimes


问:
How do you use gcc to generate assembly code in Intel syntax?
The gcc -S option will generate assembly code in AT&T syntax, is there a way to generate files in Intel syntax?  Or is there a way to convert between the two?

答:
The

```<code>gcc -S -masm=intel test.c
</code>```

Does work with me. But i can tell another way, although this has nothing to do with running gcc.
Compile the executable or the object code file and then disassemble the object code in Intel asm syntax with objdump as below:

```<code> objdump -d --disassembler-options=intel a.out
</code>```

This might help.

OwnerDisplayName: hyperlogic

Body:
The

gcc -S -masm=intel test.c

Does work with me. But i can tell another way, although this has nothing to do with running gcc.
Compile the executable or the object code file and then disassemble the object code in Intel asm syntax with objdump as below:

 objdump -d --disassembler-options=intel a.out

This might help.


问:
Check if two rows in pandas DataFrame has same set of values regard & regardless of column order
I have two dataframe with same index but different column names. Number of columns are the same. I want to check, index by index, 1) whether they have same set of values regardless of column order, and 2) whether they have same set of values regarding column order.

ind = ['aaa', 'bbb', 'ccc']
df1 = pd.DataFrame({'old1': ['A','A','A'], 'old2': ['B','B','B'], 'old3': ['C','C','C']}, index=ind)
df2 = pd.DataFrame({'new1': ['A','A','A'], 'new2': ['B','C','B'], 'new3': ['C','B','D']}, index=ind)
```

<p>This is the output I need.</p>

```     OpX   OpY
-------------
aaa  True  True
bbb  False True
ccc  False False
```

Could anyone help me with OpX and OpY?

答:
Here's a solution that is performant and should scale. First, align the DataFrames on the index so you can compare them easily.

```<code>df3 = df2.set_axis(df1.columns, axis=1, inplace=False)
df4, df5 = df1.align(df3)
</code>```

For req 1, simply call DataFrame.equals (or just use the == op):

```<code>u = (df4 == df5).all(axis=1)
u

aaa     True
bbb    False
ccc    False
dtype: bool
</code>```

Req 2 is slightly more complex, sort them along the first axis, then compare.

```<code>v = pd.Series((np.sort(df4) == np.sort(df5)).all(axis=1), index=u.index)
v

aaa     True
bbb     True
ccc    False
dtype: bool
</code>```

Concatenate the results,

```<code>pd.concat([u, v], axis=1, keys=['X', 'Y'])

         X      Y
aaa   True   True
bbb  False   True
ccc  False  False
</code>```

Body:
I have two dataframe with same index but different column names. Number of columns are the same. I want to check, index by index, 1) whether they have same set of values regardless of column order, and 2) whether they have same set of values regarding column order.

ind = ['aaa', 'bbb', 'ccc']
df1 = pd.DataFrame({'old1': ['A','A','A'], 'old2': ['B','B','B'], 'old3': ['C','C','C']}, index=ind)
df2 = pd.DataFrame({'new1': ['A','A','A'], 'new2': ['B','C','B'], 'new3': ['C','B','D']}, index=ind)

This is the output I need.

     OpX   OpY
-------------
aaa  True  True
bbb  False True
ccc  False False

Could anyone help me with OpX and OpY?

Body:
Here's a solution that is performant and should scale. First, align the DataFrames on the index so you can compare them easily.

df3 = df2.set_axis(df1.columns, axis=1, inplace=False)
df4, df5 = df1.align(df3)

For req 1, simply call DataFrame.equals (or just use the == op):

u = (df4 == df5).all(axis=1)
u

aaa     True
bbb    False
ccc    False
dtype: bool

Req 2 is slightly more complex, sort them along the first axis, then compare.

v = pd.Series((np.sort(df4) == np.sort(df5)).all(axis=1), index=u.index)
v

aaa     True
bbb     True
ccc    False
dtype: bool

Concatenate the results,

pd.concat([u, v], axis=1, keys=['X', 'Y'])

         X      Y
aaa   True   True
bbb  False   True
ccc  False  False


问:
UnicodeDecodeError: 'utf8' codec can't decode byte 0x9c
I have a socket server that is supposed to receive UTF-8 valid characters from clients.

The problem is some clients (mainly hackers) are sending all the wrong kind of data over it.

I can easily distinguish the genuine client, but I am logging to files all the data sent so I can analyze it later.

Sometimes I get characters like this œ that cause the UnicodeDecodeError error.

I need to be able to make the string UTF-8 with or without those characters.

Update:

For my particular case the socket service was an MTA and thus I only expect to receive ASCII commands such as:

```<code>EHLO example.com
MAIL FROM: <john.doe@example.com>
...
</code>```

I was logging all of this in JSON.

Then some folks out there without good intentions decided to send all kind of junk.

That is why for my specific case it is perfectly OK to strip the non ASCII characters.

答:
the first,Using get_encoding_type to get the files type of encode:

```<code>import os
from chardet import detect

# get file encoding type
def get_encoding_type(file):
    with open(file, 'rb') as f:
        rawdata = f.read()
    return detect(rawdata)['encoding']
</code>```

the second, opening the files with the type:

```<code>open(current_file, 'r', encoding = get_encoding_type, errors='ignore')
</code>```

Body:
I have a socket server that is supposed to receive UTF-8 valid characters from clients.

The problem is some clients (mainly hackers) are sending all the wrong kind of data over it.

I can easily distinguish the genuine client, but I am logging to files all the data sent so I can analyze it later.

Sometimes I get characters like this œ that cause the UnicodeDecodeError error.

I need to be able to make the string UTF-8 with or without those characters.

Update:

For my particular case the socket service was an MTA and thus I only expect to receive ASCII commands such as:

EHLO example.com
MAIL FROM: <john.doe@example.com>
...

I was logging all of this in JSON.

Then some folks out there without good intentions decided to send all kind of junk.

That is why for my specific case it is perfectly OK to strip the non ASCII characters.

Body:
the first,Using get_encoding_type to get the files type of encode:

import os
from chardet import detect

# get file encoding type
def get_encoding_type(file):
    with open(file, 'rb') as f:
        rawdata = f.read()
    return detect(rawdata)['encoding']

the second, opening the files with the type:

open(current_file, 'r', encoding = get_encoding_type, errors='ignore')


问:
Array.Find failing if not finding string in Array
I'm using an array.find below and it works to return BreakdownPalletID when the itemScan value is found in the array. If it's not found my application returns a
'Cannot read property breakdownPalletID of undefined'. The user enters the itemScan so I want to have this behavoir and then to signify to the user that that string was not found. How can I handle this undefined error?</p>

```<code> let palletID = this.transferPalletBreakdownData.Sku.find(x => x.sku == this.itemScan).breakdownPalletID
      console.log(palletID);
</code>```

答:
Array.prototype.find() method will return null if an item does not exist else it will return the expected item. So just add null checks it's enough to get rid of the error.

```<code> const itemFound = this.transferPalletBreakdownData.Sku.find(x => x.sku == this.itemScan)

let palletID = itemFound && itemFound.breakdownPalletID
console.log(palletID);
</code>```

You want more than one item based on criteria matched then we need to used filter instead of a find().

```<code>const matches = this.transferPalletBreakdownData.Sku.filter(x => x.sku == this.itemScan)

const items = matches.map(item => itemFound.breakdownPalletID)

console.log(items)
</code>```

Body:
I'm using an array.find below and it works to return BreakdownPalletID when the itemScan value is found in the array. If it's not found my application returns a
'Cannot read property breakdownPalletID of undefined'. The user enters the itemScan so I want to have this behavoir and then to signify to the user that that string was not found. How can I handle this undefined error?

 let palletID = this.transferPalletBreakdownData.Sku.find(x => x.sku == this.itemScan).breakdownPalletID
      console.log(palletID);

Body:
Array.prototype.find() method will return null if an item does not exist else it will return the expected item. So just add null checks it's enough to get rid of the error.

 const itemFound = this.transferPalletBreakdownData.Sku.find(x => x.sku == this.itemScan)

let palletID = itemFound && itemFound.breakdownPalletID
console.log(palletID);

You want more than one item based on criteria matched then we need to used filter instead of a find().

const matches = this.transferPalletBreakdownData.Sku.filter(x => x.sku == this.itemScan)

const items = matches.map(item => itemFound.breakdownPalletID)

console.log(items)


问:
Convert curl --form to C#
I'm working with an external api and want to upload file using multipart/form-data. The working solution in curl is: curl --form file=@./fileName.mp4 "http://page.com"

According to https://curl.olsh.me/. The code I'm looking for is:

```<code>using (var httpClient = new HttpClient())
{
    using (var request = new HttpRequestMessage(new HttpMethod("POST"), "http://page.com/"))
        {
            var multipartContent = new MultipartFormDataContent();
            multipartContent.Add(new  ByteArrayContent(File.ReadAllBytes("./fileName.mp4")), "file", Path.GetFileName("./fileName.mp4"));
        request.Content = multipartContent;

        var response = await httpClient.SendAsync(request);
    }
}
</code>```

However it doesn't work. The headers and the file is different so I'm getting an error.

The code I've written and 'works', but the attachment is not valid, because encoding bytes to string is incorrect.

```<code>var webClient = new HttpClient();
            webClient.DefaultRequestHeaders.ExpectContinue = true;
            string boundary = "------------------------" + DateTime.Now.Ticks.ToString("x");
            var fileData = Encoding.ASCII.GetString(System.IO.File.ReadAllBytes(pathToFile));
            var package = string.Format("--{0}\r\nContent-Disposition: form-data; name=\"file\"; filename=\"{1}\"\r\nContent-Type: {2}\r\n\r\n{3}\r\n--{0}--\r\n", boundary, "fileName", "application/octet-stream", fileData);
            var content = new StringContent(package);
            content.Headers.Remove("Content-Type");
            content.Headers.Add("Content-Type", "multipart/form-data; boundary=" + boundary);
            content.Headers.Remove("Content-Length");
            content.Headers.Add("Content-Length", package.Length.ToString());
await webClient.PostAsync(address, content);
</code>```

Edit:
The headers from curl request:

```<code>POST http://page.com/ HTTP/1.1
Host: page.com
User-Agent: curl/7.55.1
Accept: */*
Connection: Keep-Alive
Content-Length: 1703578
Expect: 100-continue
Content-Type: multipart/form-data; boundary=------------------------1a538744c5619c1e

--------------------------1a538744c5619c1e
Content-Disposition: form-data; name="file"; filename="cst.mp4"
Content-Type: application/octet-stream
</code>```

The headers from the 1st example code:

```<code>POST http://page.com/ HTTP/1.1
Content-Type: multipart/form-data; boundary="735b20d4-4de4-46fb-8293-2c2e996ce180"
Content-Length: 1703552
Host: page.com

--735b20d4-4de4-46fb-8293-2c2e996ce180
Content-Disposition: form-data; name=file; filename=cst.mp4; filename*=utf-8''cst.mp4
</code>```

答:
I think the file size difference is a red herring here.

A common practice for web servers is to deny requests that don't specify a user agent. Try adding a user agent (or even spoofing the curl agent) as below:

```<code>webClient.DefaultRequestHeaders.Add("User-Agent", "curl/7.55.1");
</code>```

Title: Convert curl --form to C#

Body:
I'm working with an external api and want to upload file using multipart/form-data. The working solution in curl is: curl --form file=@./fileName.mp4 "http://page.com"

According to https://curl.olsh.me/. The code I'm looking for is:

using (var httpClient = new HttpClient())
{
    using (var request = new HttpRequestMessage(new HttpMethod("POST"), "http://page.com/"))
        {
            var multipartContent = new MultipartFormDataContent();
            multipartContent.Add(new  ByteArrayContent(File.ReadAllBytes("./fileName.mp4")), "file", Path.GetFileName("./fileName.mp4"));
        request.Content = multipartContent;

        var response = await httpClient.SendAsync(request);
    }
}

However it doesn't work. The headers and the file is different so I'm getting an error.

The code I've written and 'works', but the attachment is not valid, because encoding bytes to string is incorrect.

var webClient = new HttpClient();
            webClient.DefaultRequestHeaders.ExpectContinue = true;
            string boundary = "------------------------" + DateTime.Now.Ticks.ToString("x");
            var fileData = Encoding.ASCII.GetString(System.IO.File.ReadAllBytes(pathToFile));
            var package = string.Format("--{0}\r\nContent-Disposition: form-data; name=\"file\"; filename=\"{1}\"\r\nContent-Type: {2}\r\n\r\n{3}\r\n--{0}--\r\n", boundary, "fileName", "application/octet-stream", fileData);
            var content = new StringContent(package);
            content.Headers.Remove("Content-Type");
            content.Headers.Add("Content-Type", "multipart/form-data; boundary=" + boundary);
            content.Headers.Remove("Content-Length");
            content.Headers.Add("Content-Length", package.Length.ToString());
await webClient.PostAsync(address, content);

Edit:
The headers from curl request:

POST http://page.com/ HTTP/1.1
Host: page.com
User-Agent: curl/7.55.1
Accept: */*
Connection: Keep-Alive
Content-Length: 1703578
Expect: 100-continue
Content-Type: multipart/form-data; boundary=------------------------1a538744c5619c1e

--------------------------1a538744c5619c1e
Content-Disposition: form-data; name="file"; filename="cst.mp4"
Content-Type: application/octet-stream

The headers from the 1st example code:

POST http://page.com/ HTTP/1.1
Content-Type: multipart/form-data; boundary="735b20d4-4de4-46fb-8293-2c2e996ce180"
Content-Length: 1703552
Host: page.com

--735b20d4-4de4-46fb-8293-2c2e996ce180
Content-Disposition: form-data; name=file; filename=cst.mp4; filename*=utf-8''cst.mp4

Body:
I think the file size difference is a red herring here.

A common practice for web servers is to deny requests that don't specify a user agent. Try adding a user agent (or even spoofing the curl agent) as below:

webClient.DefaultRequestHeaders.Add("User-Agent", "curl/7.55.1");


答:
Try out the following code.</p>

```<code>const sku = this.transferPalletBreakdownData.Sku.find(x => x.sku == this.itemScan);
if (sku) {
  console.log(sku.breakdownPalletID);
} else {
  console.log('No SKU');
}
</code>```

Title: Array.Find failing if not finding string in Array

Body:
Try out the following code.

const sku = this.transferPalletBreakdownData.Sku.find(x => x.sku == this.itemScan);
if (sku) {
  console.log(sku.breakdownPalletID);
} else {
  console.log('No SKU');
}


问:
Why the dimension of output LSTM layer can be either 2 dimension or 3 dimension?
why the dimension of LSTM output is 2 or 3 but the dimension of LSTM input is always 3 dimension?</p>

答: The dimension of LSTM input has to be described with (sample_number, unit_number, feature_number). The dimension of LSTM output has to be 3 when the task is many-to-many and you are using TimeDistributed layer, because return_sequence has to be true which means you are getting all hidden states values instead of only the last value as the default.


问:
How do I get this javascript to run every second?
How do I get this javascript to run every second?

source code:

```<code><script type="text/javascript">
$(function() {
    //More Button
    $('.more').live("click",function()  {
        var ID = $(this).attr("id");
        if(ID) {
            $("#more"+ID).html('<img src="moreajax.gif" />');

            $.ajax({
                type: "POST",
                url: "ajax_more.php",
                data: "lastmsg="+ ID,
                cache: false,
                success: function(html){
                    $("ol#updates").prepend(html);
                    $("#more"+ID).remove();
                }
            });
        } else {
            $(".morebox").html('no posts to display');
        }

        return false;

    });
});

</script>
</code>```

答:
Use setInterval:

```<code>$(function(){
setInterval(oneSecondFunction, 1000);
});

function oneSecondFunction() {
// stuff you want to do every second
}
</code>```

Here's an article on the difference between setTimeout and setInterval.  Both will provide the functionality you need, they just require different implementations.

Body:
Use setInterval:

$(function(){
setInterval(oneSecondFunction, 1000);
});

function oneSecondFunction() {
// stuff you want to do every second
}

Here's an article on the difference between setTimeout and setInterval.  Both will provide the functionality you need, they just require different implementations.


问:
when i want change get become post it not work well
i have problem when i want to change Get become Post.

when i use Get i can get the data

but when use post i cannot get the data please help me

i have change the web.php or routes become Post but i cannot get my data when i use post

i have change get become post in my web.php in my laravel. but the result not the same

this is my code in laravel

```<code>public function getHistoryEvent(Request $request) {
$consumer_data = array();
$consumer_data['consumer_key'] = request()->header('consumer-key');
$consumer_data['consumer_secret'] = request()->header('consumer-secret');
$consumer_data['consumer_nonce']      = request()->header('consumer-nonce');
$consumer_data['consumer_device_id']  = request()->header('consumer-device-id');
$consumer_data['consumer_url'] = __FUNCTION__;
$authController = new AppSettingController();
$authenticate = $authController->apiAuthenticate($consumer_data);

        if($authenticate==1 || $authenticate==0){
        $event = DB::table('u_history_events')
                    ->select('u_history_events.history_events_id','u_history_events.events_image','u_history_events.events_description','u_history_events.date_create')
                    ->where('u_history_events.events_id',$request->events_id)
                    ->where('u_history_events.kode_customers',$request->kode_customer)
                    ->get();

            $responseData = array('success'=>'1', 'data'=>$event,  'message'=>"Success.");
        }else{
            $responseData = array('success'=>'0', 'data'=>array(),  'message'=>"Unauthenticated call.");
        }
        $orderResponse = json_encode($responseData);
        print $orderResponse;

    }
</code>```

when use get i can get this data the result are :

```<code>{"success": "1",
    "data": [
        {"history_events_id": 2,
            "events_image": "",
            "events_description": "",
            "date_create": "2019-05-11 10:59:01"
        },
        {
            "history_events_id": 3,
            "events_image": "",
            "events_description": "",
            "date_create": "2019-05-11 11:59:35"
        }
       }
</code>```

but when i use post i only get

```<code>{"success":"1","data":[],"message":"Success."}
</code>```

答:
I am no Laravel expert, but according to the docs, looks like you have to explicitly define a route for the POST verb to your controller's method:

```<code>Route::post($uri, $callback);
</code>```

Or according to Controllers docs:

```<code>// change <your path here> and <your method name> to your desired path and
// method names
Route::get('<your path here>', 'AppSettingController@<your method name>');
</code>```

I also recommend you to read MDN's An overview of HTTP.

Body:
i have problem when i want to change Get become Post.

when i use Get i can get the data

but when use post i cannot get the data please help me

i have change the web.php or routes become Post but i cannot get my data when i use post

i have change get become post in my web.php in my laravel. but the result not the same

this is my code in laravel

public function getHistoryEvent(Request $request) {
$consumer_data = array();
$consumer_data['consumer_key'] = request()->header('consumer-key');
$consumer_data['consumer_secret'] = request()->header('consumer-secret');
$consumer_data['consumer_nonce']      = request()->header('consumer-nonce');
$consumer_data['consumer_device_id']  = request()->header('consumer-device-id');
$consumer_data['consumer_url'] = __FUNCTION__;
$authController = new AppSettingController();
$authenticate = $authController->apiAuthenticate($consumer_data);

        if($authenticate==1 || $authenticate==0){
        $event = DB::table('u_history_events')
                    ->select('u_history_events.history_events_id','u_history_events.events_image','u_history_events.events_description','u_history_events.date_create')
                    ->where('u_history_events.events_id',$request->events_id)
                    ->where('u_history_events.kode_customers',$request->kode_customer)
                    ->get();

            $responseData = array('success'=>'1', 'data'=>$event,  'message'=>"Success.");
        }else{
            $responseData = array('success'=>'0', 'data'=>array(),  'message'=>"Unauthenticated call.");
        }
        $orderResponse = json_encode($responseData);
        print $orderResponse;

    }

when use get i can get this data the result are :

{"success": "1",
    "data": [
        {"history_events_id": 2,
            "events_image": "",
            "events_description": "",
            "date_create": "2019-05-11 10:59:01"
        },
        {
            "history_events_id": 3,
            "events_image": "",
            "events_description": "",
            "date_create": "2019-05-11 11:59:35"
        }
       }

but when i use post i only get

{"success":"1","data":[],"message":"Success."}

Body:
I am no Laravel expert, but according to the docs, looks like you have to explicitly define a route for the POST verb to your controller's method:

Route::post($uri, $callback);

Or according to Controllers docs:

// change <your path here> and <your method name> to your desired path and
// method names
Route::get('<your path here>', 'AppSettingController@<your method name>');

I also recommend you to read MDN's An overview of HTTP.


问:
How to stack correctly monads to finally render to html?
My goal is to feed correctly the html function (as define in Spock-core) with a HtmlT m type (ideally Html ()). In between I am performing some Network.Http.Simple requests. Apparently my knowledge of Haskell is insufficient, I didn't find the way to force the correct monad. As far as I know (and understand the whole sense of monads) there is no way to compose different monads something like (Monad M, Monad N => M a -> (a -> N b) -> N b).

The best I manage to achieve was to set up a HtmlT IO () type but then I get stuck in the conversion function lucid :: HtmlT IO () -> SpockAction dtb sess state ()

Here is my connection function (Auth is a FromJSON data structure to host authorization key and token)

```<code>     connect :: IO Auth
     connect = do
                ...building a http request..
                response <- httpJSON request
                return (getResponseBody response :: Auth)
</code>```

Next this get wired in a getRequest function of type String -> HtmlT IO ()

```<code>    getRequest :: RequestPath -> HtmlT IO ()
    getRequest rpath = do
                    atoken <- liftIO connect
                    request' <- liftIO parseRequest "http://......"
                    let request = { series of set methods
                                    to build the request }
                    response <- httpLBS request
                    liftIO (L8.putStrnLn $ (getResponseBody response))
</code>```

and here we come to the lucid function, Lucid can handle transformation Html () -> SpockAction .... Html () is nothing else than HtmlT Identity () so my first attempt was to feed lucid with HtmlT IO ().

```<code>   lucid :: HtmlT IO () -> SpockAction database session state ()
   lucid document = do
                        txt <- renderTextT document       --> inside IO (?)
                        return html (TL.toStrict txt)     <-- naive attempt to
                                      return to "somewhere" of course stupid..
</code>```

Maybe IO is not the good monad here? When I try the Identity monad (to have a HtmlT Identity ()) so if I define connect as connect :: Identity Auth then naturally it follows that I am asked for a FromJSON instance of Identity (arising from using httpJSON), maybe that's a potential solution once I am in the Identity monad I am able to wire things up and probably finish with a clean Html () type which will be then executed smoothly by my lucid function.

Thank you for any clue or hints, maybe my approach is totally wrong the whole thing I am working on is to query a restAPI website and view the result on a web server run with Spock.

答:
The relevant types:

```<code>document :: HtmlT IO ()
renderTextT :: Monad m => HtmlT m a -> m Text
renderTextT document :: IO Text
<the value you need> :: SpockAction database session state Text
</code>```

Fortunately we have this available: liftIO :: MonadIO m => IO a -> m a

Two steps to getting your lucid function running:

Change txt <- renderTextT document to txt <- liftIO (renderTextT document)

Try to compile your code to make sure liftIO is imported (it probably is already). If not: add import Control.Monad.IO.Class to your import list.

Remove the return from return html (TL.toStrict txt).

The following code is working on my machine:

```<code>lucid :: HtmlT IO () -> SpockAction database session state ()
lucid document = do
  txt <- liftIO (renderTextT document)
  html (TL.toStrict txt)
</code>```

Body:
My goal is to feed correctly the html function (as define in Spock-core) with a HtmlT m type (ideally Html ()). In between I am performing some Network.Http.Simple requests. Apparently my knowledge of Haskell is insufficient, I didn't find the way to force the correct monad. As far as I know (and understand the whole sense of monads) there is no way to compose different monads something like (Monad M, Monad N => M a -> (a -> N b) -> N b).

The best I manage to achieve was to set up a HtmlT IO () type but then I get stuck in the conversion function lucid :: HtmlT IO () -> SpockAction dtb sess state ()

Here is my connection function (Auth is a FromJSON data structure to host authorization key and token)

     connect :: IO Auth
     connect = do
                ...building a http request..
                response <- httpJSON request
                return (getResponseBody response :: Auth)

Next this get wired in a getRequest function of type String -> HtmlT IO ()

    getRequest :: RequestPath -> HtmlT IO ()
    getRequest rpath = do
                    atoken <- liftIO connect
                    request' <- liftIO parseRequest "http://......"
                    let request = { series of set methods
                                    to build the request }
                    response <- httpLBS request
                    liftIO (L8.putStrnLn $ (getResponseBody response))

and here we come to the lucid function, Lucid can handle transformation Html () -> SpockAction .... Html () is nothing else than HtmlT Identity () so my first attempt was to feed lucid with HtmlT IO ().

   lucid :: HtmlT IO () -> SpockAction database session state ()
   lucid document = do
                        txt <- renderTextT document       --> inside IO (?)
                        return html (TL.toStrict txt)     <-- naive attempt to
                                      return to "somewhere" of course stupid..

Maybe IO is not the good monad here? When I try the Identity monad (to have a HtmlT Identity ()) so if I define connect as connect :: Identity Auth then naturally it follows that I am asked for a FromJSON instance of Identity (arising from using httpJSON), maybe that's a potential solution once I am in the Identity monad I am able to wire things up and probably finish with a clean Html () type which will be then executed smoothly by my lucid function.

Thank you for any clue or hints, maybe my approach is totally wrong the whole thing I am working on is to query a restAPI website and view the result on a web server run with Spock.

Body:
The relevant types:

document :: HtmlT IO ()
renderTextT :: Monad m => HtmlT m a -> m Text
renderTextT document :: IO Text
<the value you need> :: SpockAction database session state Text

Fortunately we have this available: liftIO :: MonadIO m => IO a -> m a

Two steps to getting your lucid function running:

Change txt <- renderTextT document to txt <- liftIO (renderTextT document)

Try to compile your code to make sure liftIO is imported (it probably is already). If not: add import Control.Monad.IO.Class to your import list.

Remove the return from return html (TL.toStrict txt).

The following code is working on my machine:

lucid :: HtmlT IO () -> SpockAction database session state ()
lucid document = do
  txt <- liftIO (renderTextT document)
  html (TL.toStrict txt)


问:
"Java exception occurred during rJava bootstrap" when trying to use tabulizer
I'm running Mac OS 10.13.6, and using RStudio 1.1.8, R 3.5.3, Java 11. In case hardware might matter, I'm using a 2013 MacBook Air.

I'm trying to run the extract_table function from the r tabulizer package on the Correlates of War World Religion Codebook, available here. I seem to be getting stuck because of an error with rJava. The rJava library seems to load in RStudio just fine, but when I run the following line:

```<code>lst <- tabulizer::extract_tables("/Users/[me]/Downloads/wrp-codebook-bibliography.pdf", encoding="UTF-8")
</code>```

or try to load the tabulizer library, I receive the following error:

```<code>WARNING: Initial Java 12 release has broken JNI support and does NOT work. Use stable Java 11 (or watch for 12u if avaiable).
ERROR: Java exception occurred during rJava bootstrap - see stderr for Java stack trace.
Exception in thread "main" java.lang.NullPointerException
    at java.base/jdk.internal.reflect.Reflection.verifyMemberAccess(Reflection.java:130)
    at java.base/java.lang.reflect.AccessibleObject.slowVerifyAccess(AccessibleObject.java:673)
    at java.base/java.lang.reflect.AccessibleObject.verifyAccess(AccessibleObject.java:666)
    at java.base/java.lang.reflect.AccessibleObject.checkAccess(AccessibleObject.java:638)
    at java.base/java.lang.reflect.Field.checkAccess(Field.java:1075)
    at java.base/java.lang.reflect.Field.get(Field.java:416)
Error: .onLoad failed in loadNamespace() for 'tabulizerjars', details:
  call: .jcheck(silent = FALSE)
  error: java.lang.NullPointerException.jcall(f, "Ljava/lang/Object;", "get", .jcast(ic, "java/lang/Object"))new("jobjRef", jobj = <pointer: 0x10caa0870>, jclass = "java/lang/NullPointerException")
</code>```

EDIT: the below section has been update for clarity based on a comment received.

At first I thought it was that I needed to switch from Java 12 to Java 11, so I found a helpful post on SO and used the following commands to make that switch, with no instances of RStudio or R running while I did it:

```<code>MacBook-Air:~ $ /usr/libexec/java_home -V
Matching Java Virtual Machines (2):
    12, x86_64: "Java SE 12"    /Library/Java/JavaVirtualMachines/jdk-12.jdk/Contents/Home
    11.0.2, x86_64: "Java SE 11.0.2"    /Library/Java/JavaVirtualMachines/jdk-11.0.2.jdk/Contents/Home

/Library/Java/JavaVirtualMachines/jdk-12.jdk/Contents/Home
MacBook-Air:~ $ export JAVA_HOME=`/usr/libexec/java_home -v 1.6.0_65-b14-462`
</code>```

The problem has persisted since them and when I double-check my version of Java in the terminal, I get this:

```<code>MacBook-Air:~ $ java -version
java version "11.0.2" 2019-01-15 LTS
Java(TM) SE Runtime Environment 18.9 (build 11.0.2+9-LTS)
Java HotSpot(TM) 64-Bit Server VM 18.9 (build 11.0.2+9-LTS, mixed mode)
</code>```

So it looks to me like I'm running 11.

However, I also still have 12 installed:

```<code>MacBook-Air:~ $ /usr/libexec/java_home -V
Matching Java Virtual Machines (2):
    12, x86_64: "Java SE 12"    /Library/Java/JavaVirtualMachines/jdk-12.jdk/Contents/Home
    11.0.2, x86_64: "Java SE 11.0.2"    /Library/Java/JavaVirtualMachines/jdk-11.0.2.jdk/Contents/Home
</code>```

I'm not sure if R is looking at version 12 instead, or how to redirect it, or if there is another issue here all together. Unfortunately, I wasn't able to find anything on google or SO about this error specifically in the context of R and rJava.

Please let me know if I can provide any additional information.

Thanks!

答:
Navigate to /Library/Java/JavaVirtualMachines and remove JDK 12

Reinstall JDK 11.

sudo R CMD javareconf in the terminal.

Body:
I'm running Mac OS 10.13.6, and using RStudio 1.1.8, R 3.5.3, Java 11. In case hardware might matter, I'm using a 2013 MacBook Air.

I'm trying to run the extract_table function from the r tabulizer package on the Correlates of War World Religion Codebook, available here. I seem to be getting stuck because of an error with rJava. The rJava library seems to load in RStudio just fine, but when I run the following line:

lst <- tabulizer::extract_tables("/Users/[me]/Downloads/wrp-codebook-bibliography.pdf", encoding="UTF-8")

or try to load the tabulizer library, I receive the following error:

WARNING: Initial Java 12 release has broken JNI support and does NOT work. Use stable Java 11 (or watch for 12u if avaiable).
ERROR: Java exception occurred during rJava bootstrap - see stderr for Java stack trace.
Exception in thread "main" java.lang.NullPointerException
    at java.base/jdk.internal.reflect.Reflection.verifyMemberAccess(Reflection.java:130)
    at java.base/java.lang.reflect.AccessibleObject.slowVerifyAccess(AccessibleObject.java:673)
    at java.base/java.lang.reflect.AccessibleObject.verifyAccess(AccessibleObject.java:666)
    at java.base/java.lang.reflect.AccessibleObject.checkAccess(AccessibleObject.java:638)
    at java.base/java.lang.reflect.Field.checkAccess(Field.java:1075)
    at java.base/java.lang.reflect.Field.get(Field.java:416)
Error: .onLoad failed in loadNamespace() for 'tabulizerjars', details:
  call: .jcheck(silent = FALSE)
  error: java.lang.NullPointerException.jcall(f, "Ljava/lang/Object;", "get", .jcast(ic, "java/lang/Object"))new("jobjRef", jobj = <pointer: 0x10caa0870>, jclass = "java/lang/NullPointerException")

EDIT: the below section has been update for clarity based on a comment received.

At first I thought it was that I needed to switch from Java 12 to Java 11, so I found a helpful post on SO and used the following commands to make that switch, with no instances of RStudio or R running while I did it:

MacBook-Air:~ $ /usr/libexec/java_home -V
Matching Java Virtual Machines (2):
    12, x86_64: "Java SE 12"    /Library/Java/JavaVirtualMachines/jdk-12.jdk/Contents/Home
    11.0.2, x86_64: "Java SE 11.0.2"    /Library/Java/JavaVirtualMachines/jdk-11.0.2.jdk/Contents/Home

/Library/Java/JavaVirtualMachines/jdk-12.jdk/Contents/Home
MacBook-Air:~ $ export JAVA_HOME=`/usr/libexec/java_home -v 1.6.0_65-b14-462`

The problem has persisted since them and when I double-check my version of Java in the terminal, I get this:

MacBook-Air:~ $ java -version
java version "11.0.2" 2019-01-15 LTS
Java(TM) SE Runtime Environment 18.9 (build 11.0.2+9-LTS)
Java HotSpot(TM) 64-Bit Server VM 18.9 (build 11.0.2+9-LTS, mixed mode)

So it looks to me like I'm running 11.

However, I also still have 12 installed:

MacBook-Air:~ $ /usr/libexec/java_home -V
Matching Java Virtual Machines (2):
    12, x86_64: "Java SE 12"    /Library/Java/JavaVirtualMachines/jdk-12.jdk/Contents/Home
    11.0.2, x86_64: "Java SE 11.0.2"    /Library/Java/JavaVirtualMachines/jdk-11.0.2.jdk/Contents/Home

I'm not sure if R is looking at version 12 instead, or how to redirect it, or if there is another issue here all together. Unfortunately, I wasn't able to find anything on google or SO about this error specifically in the context of R and rJava.

Please let me know if I can provide any additional information.

Thanks!


问:
Is there any alternative for Source Mate tool in Flash Builder?
So I recently discovered this Source Mate tool for Flash builder with all the cool stuff like code fixes, hinting, code completing etc., but I was wondering if there is any free alternative for this tool? Cause I don't think that paying for such tool is worth it when we need to pay a huge money for the Flash Builder Eclipse copy itself..
Should I just go with Flash Develop?</p>

答: You're not forced to buy Flash Builder, Adobe is decent enough to give the Flex SDK away for free, so you can use FlashDevelop or FDT (latter not being that cheap either though, but comparable to SourceMate with the difference that it's a complete IDE).</p>


问:
MySQL: SUM of a column based on a value of another column
I want to have a sum of a column that is based if the value of another column is this/that. Here's my table structure

```<code>id  leave_hours leave_type overtime_hours employee_id
1     7.6          1           0               3
2      5           2           0               3
3      0           0           2.3             3
</code>```

I have this query already but I need to have a column that will only sum if leave type is 1 and if the leave type is 2

```<code>SELECT employee_id, SUM(overtime_hours) AS ot_hrs, SUM(leave_hours if leave_type == 1) AS
       leave_1, SUM(leave_hours if leave_type == 2) AS leave_2
FROM table
GROUP BY employee_id
</code>```

Result should be:

```<code>employee_id  ot_hrs leave_1  leave_2
    3          2.3    7.6       5
</code>```

Thanks for your inputs.

答:
You need to use conditional aggregation to sum the different leave_hours separately:

```<code>SELECT employee_id,
       SUM(overtime_hours) AS ot,
       SUM(CASE WHEN leave_type = 1 THEN leave_hours ELSE 0 END) AS leave_1,
       SUM(CASE WHEN leave_type = 2 THEN leave_hours ELSE 0 END) AS leave_2
FROM `table`
GROUP BY employee_id
</code>```

Output:

```<code>employee_id ot      leave_1     leave_2
3           2.3     7.6         5
</code>```

Demo on dbfiddle

Note that if you use floating point numbers to store the hours, you may need to ROUND the results.

Body:
I want to have a sum of a column that is based if the value of another column is this/that. Here's my table structure

id  leave_hours leave_type overtime_hours employee_id
1     7.6          1           0               3
2      5           2           0               3
3      0           0           2.3             3

I have this query already but I need to have a column that will only sum if leave type is 1 and if the leave type is 2

SELECT employee_id, SUM(overtime_hours) AS ot_hrs, SUM(leave_hours if leave_type == 1) AS
       leave_1, SUM(leave_hours if leave_type == 2) AS leave_2
FROM table
GROUP BY employee_id

Result should be:

employee_id  ot_hrs leave_1  leave_2
    3          2.3    7.6       5

Thanks for your inputs.

Body:
You need to use conditional aggregation to sum the different leave_hours separately:

SELECT employee_id,
       SUM(overtime_hours) AS ot,
       SUM(CASE WHEN leave_type = 1 THEN leave_hours ELSE 0 END) AS leave_1,
       SUM(CASE WHEN leave_type = 2 THEN leave_hours ELSE 0 END) AS leave_2
FROM `table`
GROUP BY employee_id

Output:

employee_id ot      leave_1     leave_2
3           2.3     7.6         5

Demo on dbfiddle

Note that if you use floating point numbers to store the hours, you may need to ROUND the results.


问:
Queries related to utilization, distribution and pricing of IP addresses on Azure
I have queries related to utilization, distribution and pricing of IP addresses on Azure.

Taking an example, 10.0.0.0/27. It says, 10.0.0.0 - 10.0.0.31 (32 addresses).

After expanding I found as..

CIDR Range: 10.0.0.0/27
Netmask: 255.255.255.224
Wildcard Bits: 0.0.0.31
First IP: 10.0.0.0
Last IP: 10.0.0.31
Total Host: 32

I assigned 10.0.0.0/27 for both VNet and Subnet on Azure Portal.
After creating the virtual network, I see available address 27.

1) No virtual machine created yet, then why the available addresses are 27?

2) What is the IP range for 27 available addresses?

While creating Gateway Subnet, I see errors like...

The specified address space overlaps with subnet 'Subnet1' which has a range of '10.0.0.0/27'.

Your subnet is not contained within the address space for this virtual network: 10.0.0.0/27.

3) How to calculate and decide the available gateway subnet address space for a virtual network?

4) For using gateway subnet, is it mandatory or recommended to add another subnet before or after creating gateway subnet?

5) Why address space is required for creating a gateway subnet? Is gateway subnet not a fixed or static IP address for creating connection?

6) In case of virtual network, 10.0.0.0/27, is pricing done on the basis of utilized IP addresses only?

7) In case of virtual network, 10.0.0.0/27, if there are some un-utilized IP addresses, are they blocked to me or  my subscription or un-utilized IP addresses can be used by someone else on his azure portal?

I sincerely request to clarify all seven queries.

答:
Azure reserves 5 IP addresses within each subnet. These are x.x.x.0-x.x.x.3 and the last address of the subnet.

```<code>   x.x.x.0 and the last address of the subnet is reserved for protocol conformance.
   x.x.x.1-x.x.x.3 is reserved in each subnet for Azure services.
</code>```

Address space is the super set of subnets. So, your Address space needs to be bigger and should be able to accommodate the IPs which you are defining for the Subnets.

Basic Subnetting would help.

It is not recommended to deploy your workloads on Gateway subnet. So you need other subnets to deploy your workloads.

Gateways does have a Private IP address which it gets from the Gateway subnet. As I mentioned in Point       2, Address space is the super set of subnets.

Only Public IPs are charged. Private IP which you define in Azure VNET is not charged.

Since it is Private IP address, you can create another 10.0.0.0/27 VNET in the same region. VNET provides a isolation and the address which you define is isolated to that VNET.

Body:
Azure reserves 5 IP addresses within each subnet. These are x.x.x.0-x.x.x.3 and the last address of the subnet.

   x.x.x.0 and the last address of the subnet is reserved for protocol conformance.
   x.x.x.1-x.x.x.3 is reserved in each subnet for Azure services.

Address space is the super set of subnets. So, your Address space needs to be bigger and should be able to accommodate the IPs which you are defining for the Subnets.

Basic Subnetting would help.

It is not recommended to deploy your workloads on Gateway subnet. So you need other subnets to deploy your workloads.

Gateways does have a Private IP address which it gets from the Gateway subnet. As I mentioned in Point       2, Address space is the super set of subnets.

Only Public IPs are charged. Private IP which you define in Azure VNET is not charged.

Since it is Private IP address, you can create another 10.0.0.0/27 VNET in the same region. VNET provides a isolation and the address which you define is isolated to that VNET.


问:
How to exec bash script w/o exiting shell
I want to execute a bash script in the current shell, not a subshell/subprocess. I believe using exec allows you to do that.
But if I run:

```<code>exec ./my_script.sh
</code>```

the shell will exit and it will say "process completed". Is there a way to execute a script in the same shell somehow w/o exiting the process.

note the only thing my_script.sh does is:

```<code>export foo=bar
</code>```

but if there was some error in my script, it didn't appear in the console.

答:
you can try . ./my_script.sh.

The first dot stands for the current shell.

Body:
I want to execute a bash script in the current shell, not a subshell/subprocess. I believe using exec allows you to do that.
But if I run:

exec ./my_script.sh

the shell will exit and it will say "process completed". Is there a way to execute a script in the same shell somehow w/o exiting the process.

note the only thing my_script.sh does is:

export foo=bar

but if there was some error in my script, it didn't appear in the console.


答:
You can use setInterval:

```<code>var timer = setInterval( myFunction, 1000);
</code>```

Just declare your function as myFunction or some other name, and then don't bind it to $('.more')'s live event.

Body:
How do I get this javascript to run every second?

source code:

Body:
You can use setInterval:

var timer = setInterval( myFunction, 1000);

Just declare your function as myFunction or some other name, and then don't bind it to $('.more')'s live event.


答:
Use a logical OR operator ||:

```<code>let palletID = (this.transferPalletBreakdownData.Sku.find(x => x.sku == this.itemScan) || {}).breakdownPalletID;
console.log(palletID);
</code>```

Body:
I'm using an array.find below and it works to return BreakdownPalletID when the itemScan value is found in the array. If it's not found my application returns a
'Cannot read property breakdownPalletID of undefined'. The user enters the itemScan so I want to have this behavoir and then to signify to the user that that string was not found. How can I handle this undefined error?

 let palletID = this.transferPalletBreakdownData.Sku.find(x => x.sku == this.itemScan).breakdownPalletID
      console.log(palletID);

Body:
Use a logical OR operator ||:

let palletID = (this.transferPalletBreakdownData.Sku.find(x => x.sku == this.itemScan) || {}).breakdownPalletID;
console.log(palletID);


问:
laravel updating editing database record - getting error when submitting the form
I am using this code to edit database record :

```<code>public function service_edit($id)
{
    $service = Service::find($id);
    return view('Super_Admin/service/.service_edit')->with('service', $service);
}

public function service_update(Request $request, $id)
{
    $service = Service::find($id);
    $input['title_name'] = strtoupper ($request['title_name']);
    $input['link'] = strtoupper ($request['link']);
    $input['note'] = strtoupper ($request['note']);
    $input['image'] = time().'.'.$request->

    image->getClientOriginalExtension();
    $folder1 = public_path('WEBSITE-FILE/SERVICE/1');
    $path1 = $folder1 . $input['image']; // path 1
    $request->image->move($folder1, $input['image']);
    $path2 = public_path('WEBSITE-FILE/SERVICE/2').$input['image'];// path 2
    $path3 = public_path('WEBSITE-FILE/SERVICE/3'). $input['image']; // path 3
    $path4 = public_path('WEBSITE-FILE/SERVICE/4'). $input['image']; // path 4

    \File::copy($path1, $path2);
    \File::copy($path1, $path3);
    \File::copy($path1, $path4);

    $service->save();

    return back()->with('success','UPDATED SUCCESSFULLY .');
}
</code>```

I am facing this error when I submit the form

"Call to a member function save() on array"

答:
change the following line and try</p>

```<code>$input= Service::find($id);
</code>```

Body:
I am using this code to edit database record :

public function service_edit($id)
{
    $service = Service::find($id);
    return view('Super_Admin/service/.service_edit')->with('service', $service);
}

public function service_update(Request $request, $id)
{
    $service = Service::find($id);
    $input['title_name'] = strtoupper ($request['title_name']);
    $input['link'] = strtoupper ($request['link']);
    $input['note'] = strtoupper ($request['note']);
    $input['image'] = time().'.'.$request->

    image->getClientOriginalExtension();
    $folder1 = public_path('WEBSITE-FILE/SERVICE/1');
    $path1 = $folder1 . $input['image']; // path 1
    $request->image->move($folder1, $input['image']);
    $path2 = public_path('WEBSITE-FILE/SERVICE/2').$input['image'];// path 2
    $path3 = public_path('WEBSITE-FILE/SERVICE/3'). $input['image']; // path 3
    $path4 = public_path('WEBSITE-FILE/SERVICE/4'). $input['image']; // path 4

    \File::copy($path1, $path2);
    \File::copy($path1, $path3);
    \File::copy($path1, $path4);

    $service->save();

    return back()->with('success','UPDATED SUCCESSFULLY .');
}

I am facing this error when I submit the form

"Call to a member function save() on array"

Body:
change the following line and try

$input= Service::find($id);


问:
How to make a HTTP POST request when the data parameter includes an ampersand?
I am attempting to access data on lobbying expenditures from the LobbyView API. Per the documentation on their website, I am using a POST request to collect lobbying data for AT&T Inc and Apple Inc. When I run the following code for Apple Inc, the API returns Apple's lobbying data as expected.

```<code>import requests, json
query = {"legal_name": "Apple Inc"}
results = requests.post('https://www.lobbyview.org/public/api/reports', data = json.dumps(query))
print(results.json())
</code>```

But, when I run the same code for AT&T Inc, the API returns nothing.

```<code>import requests, json
query = {"legal_name": "AT&T Inc"}
results = requests.post('https://www.lobbyview.org/public/api/reports', data = json.dumps(query))
print(results.json())
</code>```

I believe the problem is that AT&T Inc includes an ampersand (&) in its name.
How should I adjust my code so that I can make a POST request when the data parameter includes an ampersand (&) (e.g. "AT&T Inc")?

答: You may try either to replace with %26 or with \&</p>

Body:
I am attempting to access data on lobbying expenditures from the LobbyView API. Per the documentation on their website, I am using a POST request to collect lobbying data for AT&T Inc and Apple Inc. When I run the following code for Apple Inc, the API returns Apple's lobbying data as expected.

import requests, json
query = {"legal_name": "Apple Inc"}
results = requests.post('https://www.lobbyview.org/public/api/reports', data = json.dumps(query))
print(results.json())

But, when I run the same code for AT&T Inc, the API returns nothing.

import requests, json
query = {"legal_name": "AT&T Inc"}
results = requests.post('https://www.lobbyview.org/public/api/reports', data = json.dumps(query))
print(results.json())

I believe the problem is that AT&T Inc includes an ampersand (&) in its name.
How should I adjust my code so that I can make a POST request when the data parameter includes an ampersand (&) (e.g. "AT&T Inc")?


问:
map function for objects (instead of arrays)
I have an object:

```<code>myObject = { 'a': 1, 'b': 2, 'c': 3 }
</code>```

I am looking for a native method, similar to Array.prototype.map that would be used as follows:

```<code>newObject = myObject.map(function (value, label) {
    return value * value;
});

// newObject is now { 'a': 1, 'b': 4, 'c': 9 }
</code>```

Does JavaScript have such a map function for objects? (I want this for Node.JS, so I don't care about cross-browser issues.)

答:
ES6:

```<code>Object.prototype.map = function(mapFunc) {
    return Object.keys(this).map((key, index) => mapFunc(key, this[key], index));
}
</code>```

ES2015:

```<code>Object.prototype.map = function (mapFunc) {
    var _this = this;

    return Object.keys(this).map(function (key, index) {
        return mapFunc(key, _this[key], index);
    });
};
</code>```

test in node:

```<code>> a = {foo: "bar"}
{ foo: 'bar' }
> a.map((k,v,i) => v)
[ 'bar' ]
</code>```

Body:
I have an object:

myObject = { 'a': 1, 'b': 2, 'c': 3 }

I am looking for a native method, similar to Array.prototype.map that would be used as follows:

newObject = myObject.map(function (value, label) {
    return value * value;
});

// newObject is now { 'a': 1, 'b': 4, 'c': 9 }

Does JavaScript have such a map function for objects? (I want this for Node.JS, so I don't care about cross-browser issues.)

Body:
ES6:

Object.prototype.map = function(mapFunc) {
    return Object.keys(this).map((key, index) => mapFunc(key, this[key], index));
}

ES2015:

Object.prototype.map = function (mapFunc) {
    var _this = this;

    return Object.keys(this).map(function (key, index) {
        return mapFunc(key, _this[key], index);
    });
};

test in node:

> a = {foo: "bar"}
{ foo: 'bar' }
> a.map((k,v,i) => v)
[ 'bar' ]


问:
Single-sign-on authentication vs authorization
I'm implementing Facebook and Google SSO on my website using custom workflow (redirect urls, parsing on server side etc. - no javascript) and I got to the point I have access_token, token_type and expires_in and from Google also id_token and I am confused what to do next to authenticate the user.
I read a little about authorization vs authentication, and that Facebook and Google SSO is OAuth2 which provides authorization, but not authentication, from which I understand that this way my web application is authorized to do something on behalf of the user, but I cannot be sure the user is the one who I think he is? My main source is this: OAuth Authorization vs Authentication

So, my question is, what should I do to be able to can consider the user logged in.

Thank you

答:
We should never use OAuth2 access token for authentication.
For details, please refer
https://oauth.net/articles/authentication/

The OpenIDConnect, built on top of OAuth2, can be used for authentication.

Google supports OpenIDConnect
https://developers.google.com/identity/protocols/OpenIDConnect

The basic idea is Google will issue the client app (your application) a ID Token after the user has login his Google account. You can then extract user information (e.g. email, unique user id) from this ID token and proceed your login flow.


问:
How to deal with relative path in Junits between Maven and Intellij
I have a maven project with a module

```<code>/myProject
pom.xml
    /myModule
    pom.xml
       /foo
       bar.txt
</code>```

Consider a Junit in myModule which needs to open bar.txt, with maven the basedir is the module directory.

So to open the file bar.txt  :

```<code>  new File("foo/bar.txt")
</code>```

This works well when you execute mvn test BUT when you launch the same junit in intellij, it fails because Intellij sets the basedir in the project directory, not the module directory.

Intellij tries to open myProject/foo/bar.txt instead of myProject/myModule/foo/bar.txt

Is there a way to deal with that ?

答:
Solution inspired by Guillaume :

In Run->Edit configuration->Defaults->JUnit->Working directory set the value $MODULE_DIR$ and Intellij will set the relative path in all junits just like Maven.

Body:
I have a maven project with a module

/myProject
pom.xml
    /myModule
    pom.xml
       /foo
       bar.txt

Consider a Junit in myModule which needs to open bar.txt, with maven the basedir is the module directory.

So to open the file bar.txt  :

  new File("foo/bar.txt")

This works well when you execute mvn test BUT when you launch the same junit in intellij, it fails because Intellij sets the basedir in the project directory, not the module directory.

Intellij tries to open myProject/foo/bar.txt instead of myProject/myModule/foo/bar.txt

Is there a way to deal with that ?


问:
instrumentation test for Room
"I have a room database and it works normally, I want to test it now but my test doesn't work and I don't see any assert when its run.
in this code Im adding a new record and initializing it, then assert if record is added"

```<code>@RunWith(AndroidJUnit4.class)
public class PatientDaoTest {
private PatientDao patientDao;
private PatientDatabase db;
public int patient_db_ID;
public int bed_number;

@Before
public void createDb(){
Context context = ApplicationProvider.getApplicationContext();
db = Room.inMemoryDatabaseBuilder(context, PatientDatabase.class).buil();
patientDao = db.patientDao();}

@After
public void closeDb() throws IOException {
db.close();
}

@Test
public void InsertNewPatient() throws Exception {
PatientRecordEntity newPatient = new PatientRecordEntity();
newPatient.setPatient_db_ID("123456");
newPatient.setPatient_race("chines");
newPatient.setBed_number("123");
newPatient.setReal_bed_number("1234");
newPatient.setRegister_date("5/28/2019");
newPatient.setRegister_time("3:35:02");
newPatient.setPatient_age(12);
newPatient.setPatient_gender(1);

boolean pin = false;
int newRowId = 0;
newRowId = (int) db.patientDao().addNewPatient(newPatient);
if(newRowId == 0){
pin= true;
}

assertTrue("test is true",pin);
}}
</code>```

"It s my Dao query:"

```<code>@Insert
long addNewPatient(PatientRecordEntity newPatient);
</code>```

"and this is that function that use this query of dao. I don't no if my @test is true or not"

```<code>public static int AddPatientToDB() {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd", Locale.getDefault());
String formatedDate = sdf.format(new Date());
sdf = new SimpleDateFormat("HH-mm-ssZ", Locale.getDefault());
String formatedTime = sdf.format(new Date());
PatientRecordEntity newPatient = new PatientRecordEntity();
newPatient.setBed_number(bed_no);
newPatient.setPatient_db_ID(patient_id);
newPatient.setRegister_time(formatedTime);
newPatient.setRegister_date(formatedDate);
int newRowId = 0;
newRowId = (int) pDatabase.patientDao().addNewPatient(newPatient);
current_patient_record_entity = newPatient;
current_patient_record_entity.pid = newRowId;
current_patient_record_entity.sessionID = Repo.currentSessionID;
current_wound_record_entity = new WoundRecordEntity();
current_wound_record_entity.patient_key = (int) newRowId;
current_sample_no = newRowId;

return newRowId;
}
</code>```

答:
"thanks...according to your guide, the test was true and I just modify the assert:"

```<code>boolean pin = false;
int newRowId = 0;
newRowId = (int) patientDao.addNewPatient(newPatient);
newPatient.setPid(newRowId);
if(0 != newRowId){
pin= true;}
assertTrue("addNewPatient is not true",pin);
</code>```

"and the test passed :))"

Title: instrumentation test for Room

Body:
"I have a room database and it works normally, I want to test it now but my test doesn't work and I don't see any assert when its run.
in this code Im adding a new record and initializing it, then assert if record is added"

@RunWith(AndroidJUnit4.class)
public class PatientDaoTest {
private PatientDao patientDao;
private PatientDatabase db;
public int patient_db_ID;
public int bed_number;

@Before
public void createDb(){
Context context = ApplicationProvider.getApplicationContext();
db = Room.inMemoryDatabaseBuilder(context, PatientDatabase.class).buil();
patientDao = db.patientDao();}

@After
public void closeDb() throws IOException {
db.close();
}

@Test
public void InsertNewPatient() throws Exception {
PatientRecordEntity newPatient = new PatientRecordEntity();
newPatient.setPatient_db_ID("123456");
newPatient.setPatient_race("chines");
newPatient.setBed_number("123");
newPatient.setReal_bed_number("1234");
newPatient.setRegister_date("5/28/2019");
newPatient.setRegister_time("3:35:02");
newPatient.setPatient_age(12);
newPatient.setPatient_gender(1);

boolean pin = false;
int newRowId = 0;
newRowId = (int) db.patientDao().addNewPatient(newPatient);
if(newRowId == 0){
pin= true;
}

assertTrue("test is true",pin);
}}

"It s my Dao query:"

@Insert
long addNewPatient(PatientRecordEntity newPatient);

"and this is that function that use this query of dao. I don't no if my @test is true or not"

public static int AddPatientToDB() {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd", Locale.getDefault());
String formatedDate = sdf.format(new Date());
sdf = new SimpleDateFormat("HH-mm-ssZ", Locale.getDefault());
String formatedTime = sdf.format(new Date());
PatientRecordEntity newPatient = new PatientRecordEntity();
newPatient.setBed_number(bed_no);
newPatient.setPatient_db_ID(patient_id);
newPatient.setRegister_time(formatedTime);
newPatient.setRegister_date(formatedDate);
int newRowId = 0;
newRowId = (int) pDatabase.patientDao().addNewPatient(newPatient);
current_patient_record_entity = newPatient;
current_patient_record_entity.pid = newRowId;
current_patient_record_entity.sessionID = Repo.currentSessionID;
current_wound_record_entity = new WoundRecordEntity();
current_wound_record_entity.patient_key = (int) newRowId;
current_sample_no = newRowId;

return newRowId;
}

Body:
"thanks...according to your guide, the test was true and I just modify the assert:"

boolean pin = false;
int newRowId = 0;
newRowId = (int) patientDao.addNewPatient(newPatient);
newPatient.setPid(newRowId);
if(0 != newRowId){
pin= true;}
assertTrue("addNewPatient is not true",pin);

"and the test passed :))"


问:
How to fix no variable echoed in PHP Post request?
I am setting up a new website and want to be able to gather user input on the checkout page and echo the user input on the confirmation page. How do I perform this operation?

This is using html and php. In the past, I've tried using POST method, isset, $_Request functions.

This is the code for Confirmationpage.html.

```<code><!DOCTYPE html>
<html>
  <head>
      <title>Confirmation page</title>
  </head>
  <body>
    <h1>Confirmation page</h1>
    <h2>Order Confirmed!</h2>
    <?php
      // define variables and set to empty values
      $fName = $lName = $email = $phoneNumber = "";

      if ( isset( $_POST['submit'] ) ) {

        $fName = $_POST["fName"];
        $lName = $_POST["lName"];
        $email = $_POST["email"];
        $phoneNumber = $_POST["phoneNumber"];
        echo $fName . " " . $lName;
        echo $email;
      }

      function test_input($data) {

        $data = trim($data);
        $data = stripslashes($data);
        $data = htmlspecialchars($data);
        return $data;

      }
    ?>
  </body>
</html>
</code>```

This is the code for Checkoutpage.html.

```<code><!DOCTYPE html>
<html>
    <head>
        <title>Checkout page</title>
    </head>
    <body>
        <h1>Checkout page</h1>
        <form action="Confirmationpage.html" method="POST">
            <input type="text" name="fName" placeholder="First Name"><br>
            <input type="text" name="lName" placeholder="Last Name"><br>
            <input type="email" name="email" placeholder="Email"><br>
            <input type="number" name="phoneNumber" placeholder="Phone Number">
            <br>
            <input type="submit" value="Confirm" name="submit">
        </form>
    </body>
</html>
</code>```

I expected the first name, last name and email to be echoed in the confirmation page however the actual result is not outputting the first name, last name and email.

答:
try this,

```<code>echo $fName . " " . $lName;
echo '<br>';
echo $email;die;
</code>```

Keep this in mind: your file should be .php

Body:
I am setting up a new website and want to be able to gather user input on the checkout page and echo the user input on the confirmation page. How do I perform this operation?

This is using html and php. In the past, I've tried using POST method, isset, $_Request functions.

This is the code for Confirmationpage.html.

<!DOCTYPE html>

      <title>Confirmation page</title>

Confirmation page

Order Confirmed!

    <?php
      // define variables and set to empty values
      $fName = $lName = $email = $phoneNumber = "";

      if ( isset( $_POST['submit'] ) ) {

        $fName = $_POST["fName"];
        $lName = $_POST["lName"];
        $email = $_POST["email"];
        $phoneNumber = $_POST["phoneNumber"];
        echo $fName . " " . $lName;
        echo $email;
      }

      function test_input($data) {

        $data = trim($data);
        $data = stripslashes($data);
        $data = htmlspecialchars($data);
        return $data;

      }
    ?>

This is the code for Checkoutpage.html.

<!DOCTYPE html>

        <title>Checkout page</title>

Checkout page

        <form action="Confirmationpage.html" method="POST">
            <input type="text" name="fName" placeholder="First Name">

            <input type="text" name="lName" placeholder="Last Name">

            <input type="email" name="email" placeholder="Email">

            <input type="number" name="phoneNumber" placeholder="Phone Number">

            <input type="submit" value="Confirm" name="submit">
        </form>

I expected the first name, last name and email to be echoed in the confirmation page however the actual result is not outputting the first name, last name and email.

Body:
try this,

echo $fName . " " . $lName;
echo '<br>';
echo $email;die;

Keep this in mind: your file should be .php


问:
AZCopy, see errors and failed transfer info
when using AZCopy to download files, how do I get information about what files failed to transfer, and what the error was? All I get is a message stating how many files failed.

```<code>sudo azcopy \
    --source <url> \
    --destination <path> \
    --source-key <key> \
    --include "<something>" \
    --recursive
</code>```

I did see this post AZCopy Get list of failed transfer files, but the --V parameteter isn't recognized.

I also tried

--verbose < path> \

but it's not recognizing the path parameter, either with or without quotation marks.

答:
You should just check the status with azcopy jobs show:

```<code>azcopy jobs show <job-id> --with-status=Failed
</code>```

Body:
when using AZCopy to download files, how do I get information about what files failed to transfer, and what the error was? All I get is a message stating how many files failed.

sudo azcopy \
    --source <url> \
    --destination <path> \
    --source-key <key> \
    --include "<something>" \
    --recursive

I did see this post AZCopy Get list of failed transfer files, but the --V parameteter isn't recognized.

I also tried

--verbose < path> \

but it's not recognizing the path parameter, either with or without quotation marks.

Body:
You should just check the status with azcopy jobs show:

azcopy jobs show <job-id> --with-status=Failed


问:
TensorFlow: numpy.repeat() alternative
I want to compare the predicted values yp from my neural network in a pairwise fashion, and so I was using (back in my old numpy implementation):

```<code>idx = np.repeat(np.arange(len(yp)), len(yp))
jdx = np.tile(np.arange(len(yp)), len(yp))
s = yp[[idx]] - yp[[jdx]]
</code>```

This basically create a indexing mesh which I then use. idx=[0,0,0,1,1,1,...] while jdx=[0,1,2,0,1,2...]. I do not know if there is a simpler manner of doing it...

Anyhow, TensorFlow has a tf.tile(), but it seems to be lacking a tf.repeat().

```<code>idx = np.repeat(np.arange(n), n)
v2 = v[idx]
</code>```

And I get the error:

```<code>TypeError: Bad slice index [  0   0   0 ..., 215 215 215] of type <type 'numpy.ndarray'>
</code>```

It also does not work to use a TensorFlow constant for the indexing:

```<code>idx = tf.constant(np.repeat(np.arange(n), n))
v2 = v[idx]
</code>```

-

```<code>TypeError: Bad slice index Tensor("Const:0", shape=TensorShape([Dimension(46656)]), dtype=int64) of type <class 'tensorflow.python.framework.ops.Tensor'>
</code>```

The idea is to convert my RankNet implementation to TensorFlow.

答:
According to tf api document, tf.keras.backend.repeat_elements() does the same work with np.repeat() . For example,

x = tf.constant([1, 3, 3, 1], dtype=tf.float32)
rep_x = tf.keras.backend.repeat_elements(x, 5, axis=0)
# result: [1. 1. 1. 1. 1. 3. 3. 3. 3. 3. 3. 3. 3. 3. 3. 1. 1. 1. 1. 1.]
```

Title: TensorFlow: numpy.repeat() alternative

Body:
I want to compare the predicted values yp from my neural network in a pairwise fashion, and so I was using (back in my old numpy implementation):

idx = np.repeat(np.arange(len(yp)), len(yp))
jdx = np.tile(np.arange(len(yp)), len(yp))
s = yp[[idx]] - yp[[jdx]]

This basically create a indexing mesh which I then use. idx=[0,0,0,1,1,1,...] while jdx=[0,1,2,0,1,2...]. I do not know if there is a simpler manner of doing it...

Anyhow, TensorFlow has a tf.tile(), but it seems to be lacking a tf.repeat().

idx = np.repeat(np.arange(n), n)
v2 = v[idx]

And I get the error:

TypeError: Bad slice index [  0   0   0 ..., 215 215 215] of type <type 'numpy.ndarray'>

It also does not work to use a TensorFlow constant for the indexing:

idx = tf.constant(np.repeat(np.arange(n), n))
v2 = v[idx]

-

TypeError: Bad slice index Tensor("Const:0", shape=TensorShape([Dimension(46656)]), dtype=int64) of type <class 'tensorflow.python.framework.ops.Tensor'>

The idea is to convert my RankNet implementation to TensorFlow.


问:
TypeScript decorator reports "Unable to resolve signature of class decorator when called as an expression"
```<code>@xxx("xxx")
class A{
    msg:string
    constructor(msg:string) {
        this.msg = msg
    }
    print() {
        console.log(this.msg)
    }
}

function xxx(arg:string) {
    function f(target) {
        function ff(msg: string) {
            return new target(arg + ":" + msg)
        }
        return ff
    }
    return f
}

let a = new A("hellow")
a.print()
</code>```

When compile, it reports:

decorator.ts(1,1): error TS1238: Unable to resolve signature of class decorator when called as an expression.
Type '(msg: string) => any' is not assignable to type 'void'.

But the genrated js executed well. I don't know why it reports an error.

答:
As mentioned by Alex above, the compiler expects your decorator to either be void or return a value that is compatible with A. So you can cast the ff to typeof target.

```<code>function xxx(arg:string) {
    function f(target) {
        function ff(msg: string) {
            return new target(arg + ":" + msg)
        }
        return ff as typeof target
    }
    return f
}
</code>```

Body:
@xxx("xxx")
class A{
    msg:string
    constructor(msg:string) {
        this.msg = msg
    }
    print() {
        console.log(this.msg)
    }
}

function xxx(arg:string) {
    function f(target) {
        function ff(msg: string) {
            return new target(arg + ":" + msg)
        }
        return ff
    }
    return f
}

let a = new A("hellow")
a.print()

When compile, it reports:

decorator.ts(1,1): error TS1238: Unable to resolve signature of class decorator when called as an expression.
Type '(msg: string) => any' is not assignable to type 'void'.

But the genrated js executed well. I don't know why it reports an error.

Body:
As mentioned by Alex above, the compiler expects your decorator to either be void or return a value that is compatible with A. So you can cast the ff to typeof target.

function xxx(arg:string) {
    function f(target) {
        function ff(msg: string) {
            return new target(arg + ":" + msg)
        }
        return ff as typeof target
    }
    return f
}


问:
generic function to generate this sequence: 1 4 3 6 5 8 7 10 9 12 for the first n=100 numbers in R
I am trying to write a generic function in R to generate this sequence: 1 4 3 6 5 8 7 10 9 12 for the first n=100 numbers.

I have tried to generate two vectors, one for odd numbers starting 1 and one for even numbers starting 4 and trying to concatenate c(x[i],y[i])use a loop to generate the sequence.

```<code>x<-seq.int(1,100,2)
y<-seq.int(4,100,2)
seqxy<-c(x,y){
for(i in 1:12){seqxy[i]<-c(x[i],y[i])
}
return(seqxy)
</code>```

}

I get an error message while trying to run the loop.
"Error: object 'seqxy' not found"

答:
You can generate two vectors of length 100, and use elements from each depending on whether the current index is odd or even:

```<code>x = 1:100
y = 3:102

ifelse(seq_along(x) %% 2, x, y)
</code>```

Output:

```<code>[1]   1   4   3   6   5   8   7  10   9  12  11  14 ...
</code>```

Body:
I am trying to write a generic function in R to generate this sequence: 1 4 3 6 5 8 7 10 9 12 for the first n=100 numbers.

I have tried to generate two vectors, one for odd numbers starting 1 and one for even numbers starting 4 and trying to concatenate c(x[i],y[i])use a loop to generate the sequence.

x<-seq.int(1,100,2)
y<-seq.int(4,100,2)
seqxy<-c(x,y){
for(i in 1:12){seqxy[i]<-c(x[i],y[i])
}
return(seqxy)

}

I get an error message while trying to run the loop.
"Error: object 'seqxy' not found"

Body:
You can generate two vectors of length 100, and use elements from each depending on whether the current index is odd or even:

x = 1:100
y = 3:102

ifelse(seq_along(x) %% 2, x, y)

Output:

[1]   1   4   3   6   5   8   7  10   9  12  11  14 ...


问:
C program Changing argv programmatically gives heap corruption error after exit of program only in debug mode in Visual Studio. How to resolve?
I have a large legacy program in which programmatically argv parameter is changed programmatically in program init followed by logic that parses the parameters.

In Release mode the program terminates gracefully.

In Debug mode, the program does all the required computation and gives the correct output. But upon exit gives Heap corruption error:

Error Message:

Microsoft Visual C++ Runtime Library

Debug Error!

Program:
  ...sers\AMD\source\repos\ArgvOverflow\x64\Debug\ArgvOverflow.exe

HEAP CORRUPTION DETECTED: after CRT block (#62) at 0x00000259566FDC90.
  CRT detected that the application wrote to memory after end of heap
  buffer.

Memory allocated at
  minkernel\crts\ucrt\src\appcrt\startup\argv_parsing.cpp(285).

(Press Retry to debug the application)

Abort   Retry   Ignore

Code:

```<code>#include <stdio.h>
int main(int argc, char **argv)
{
       argc = 12;
       argv[1] = "str1";
       argv[2] = "str2";
       argv[3] = "str3";
       argv[4] = "str4";
       argv[5] = "str5";
       argv[6] = "str6";
       argv[7] = "str7";
       argv[8] = "str8";
       argv[9] = "str9";
       argv[10] = "str10";
       argv[11] = "str11";
       printf("Hello world\n");
       return 0;
}
</code>```

I have read several posts about modifying argv, where they claim that such modifications are legal according to C standards. I also tried the suggestion to have the line

```<code>argv[argc] = NULL;
</code>```

This is not solving the problem.

答:
It is totally plausible to have this kind of setup when doing debug.
One work around which worked for me was to set up a dummy argument list when calling the program, then repopulate argv with the desired data once you get into main.

```<code>myprog.exe dummy dummy dummy dummy dummy dummy dummy dummydummy dummydummy dummy
</code>```

and inside your code

```<code>    int main (int argc , char* argv[]){

       argc = 12;
       argv[1] = "str1";
       argv[2] = "str2";
       argv[3] = "str3";
       argv[4] = "str4";
       argv[5] = "str5";
       argv[6] = "str6";
       argv[7] = "str7";
       argv[8] = "str8";
       argv[9] = "str9";
       argv[10] = "str10";
       argv[11] = "str11";
       printf("Hello world\n");
       return 0;
}
</code>```

Body:
I have a large legacy program in which programmatically argv parameter is changed programmatically in program init followed by logic that parses the parameters.

In Release mode the program terminates gracefully.

In Debug mode, the program does all the required computation and gives the correct output. But upon exit gives Heap corruption error:

Error Message:

Microsoft Visual C++ Runtime Library

Debug Error!

Program:
  ...sers\AMD\source\repos\ArgvOverflow\x64\Debug\ArgvOverflow.exe

HEAP CORRUPTION DETECTED: after CRT block (#62) at 0x00000259566FDC90.
  CRT detected that the application wrote to memory after end of heap
  buffer.

Memory allocated at
  minkernel\crts\ucrt\src\appcrt\startup\argv_parsing.cpp(285).

(Press Retry to debug the application)

Abort   Retry   Ignore

Code:

#include <stdio.h>
int main(int argc, char **argv)
{
       argc = 12;
       argv[1] = "str1";
       argv[2] = "str2";
       argv[3] = "str3";
       argv[4] = "str4";
       argv[5] = "str5";
       argv[6] = "str6";
       argv[7] = "str7";
       argv[8] = "str8";
       argv[9] = "str9";
       argv[10] = "str10";
       argv[11] = "str11";
       printf("Hello world\n");
       return 0;
}

I have read several posts about modifying argv, where they claim that such modifications are legal according to C standards. I also tried the suggestion to have the line

argv[argc] = NULL;

This is not solving the problem.

Body:
It is totally plausible to have this kind of setup when doing debug.
One work around which worked for me was to set up a dummy argument list when calling the program, then repopulate argv with the desired data once you get into main.

myprog.exe dummy dummy dummy dummy dummy dummy dummy dummydummy dummydummy dummy

and inside your code

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

       argc = 12;
       argv[1] = "str1";
       argv[2] = "str2";
       argv[3] = "str3";
       argv[4] = "str4";
       argv[5] = "str5";
       argv[6] = "str6";
       argv[7] = "str7";
       argv[8] = "str8";
       argv[9] = "str9";
       argv[10] = "str10";
       argv[11] = "str11";
       printf("Hello world\n");
       return 0;
}


问:
Using a generic OpenID Connect Resource Provider (RP) library
I plan to use Keycloak to secure my Mule REST APIs, but I'm not sure which adapter I can use for integration. As per Keycloak documentation, "Keycloak can be secured by supplied adapters that are usually easier to use and provide better integration with Keycloak. However, if an adapter is not available for your programming language, framework, or platform you might opt to use a generic OpenID Connect Resource Provider (RP) library instead." What exactly is meant by "generic OpenID Connect Resource Provider (RP) library"?</p>

答:
This sentence (in the Keycloak Securing Applications and Services Guide) is incorrect. "OpenID Connect Resource Provider (RP) library" means "OpenID Connect Relying Party (RP) library" such as mod_auth_openidc
, and you can see the libraries on this page.