问:
Extract text from PDF documents and generate structured data
I am able to extract the text from all pages in pdf successfully. But unable to generate in structured data. Guide me if anyone come across such expertise.

Code:

```<code>package pdfboxreadfromfile;

import java.awt.geom.Rectangle2D;
import java.io.File;
import java.io.IOException;
import java.util.List;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDDocumentCatalog;
import org.apache.pdfbox.pdmodel.PDPage;
import org.apache.pdfbox.pdmodel.interactive.form.PDAcroForm;
import org.apache.pdfbox.pdmodel.interactive.form.PDField;
import org.apache.pdfbox.text.PDFTextStripper;
import org.apache.pdfbox.text.PDFTextStripperByArea;

public class PDFBoxReadFromFile {
  public static void main(String[] args) {
    try {
      File file = new File("C:/ma.pdf");
      PDDocument doc = PDDocument.load(file);
      PDFTextStripper pdfTextStripper = new PDFTextStripper();
      pdfTextStripper.setSortByPosition(true);
      pdfTextStripper.setStartPage(1);
      pdfTextStripper.setEndPage(6);
      String text = pdfTextStripper.getText(doc);
      System.out.println(text);
      doc.close();
    } catch (IOException e) {
      e.printStackTrace();
    }
  }
</code>```

Output:

PDF looks like this.
Page 1:

Expected header text is only for reference and need notin print.

Tried the following:

```<code>Pattern p = Pattern.compile("PO...........*?");
Pattern p1 = Pattern.compile("Vendor...........");
Pattern p2 = Pattern.compile("100.....*?");
Pattern p4 = Pattern.compile("Date...............................................*?");
Pattern p5 = Pattern.compile("62...........3*?");
Pattern p6 = Pattern.compile("62710149950...*?");
Pattern p7 = Pattern.compile("627101499504..*?");

Matcher m = p.matcher(text);
Matcher m1 = p1.matcher(text);
Matcher m2 = p2.matcher(text);
Matcher m4 = p4.matcher(text);
Matcher m5 = p5.matcher(text);
Matcher m6 = p6.matcher(text);
Matcher m7 = p7.matcher(text);
m.find();
m1.find();
m2.find();
m4.find();
m5.find();
m6.find();
m7.find();

System.out.println(m.group(0) + "|" + m1.group(0) + "|" + m2.group(0) + "|" + m2.group(0) + "|" + "MAC" + "|" + m4.group(0) + "|" + m5.group(0) + "|");
System.out.println(m.group(0) + "|" + m1.group(0) + "|" + m2.group(0) + "|" + m2.group(0) + "|" + "MAC" + "|" + m4.group(0) + "|" + m6.group(0) + "|");
System.out.println(m.group(0) + "|" + m1.group(0) + "|" + m2.group(0) + "|" + m2.group(0) + "|" + "MAC" + "|" + m4.group(0) + "|" + m7.group(0) + "|");
</code>```

Structured Output. But issue is Quantity against the Barcode alias Product code is not coming.

答: You should search the text for the header line (Barcode, Item number, ...) and then parse each following line by splitting it to columns. The columns are separated by spaces, so you can use the String.split() function.</p>

Body:
I am able to extract the text from all pages in pdf successfully. But unable to generate in structured data. Guide me if anyone come across such expertise.

Code:

package pdfboxreadfromfile;

import java.awt.geom.Rectangle2D;
import java.io.File;
import java.io.IOException;
import java.util.List;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDDocumentCatalog;
import org.apache.pdfbox.pdmodel.PDPage;
import org.apache.pdfbox.pdmodel.interactive.form.PDAcroForm;
import org.apache.pdfbox.pdmodel.interactive.form.PDField;
import org.apache.pdfbox.text.PDFTextStripper;
import org.apache.pdfbox.text.PDFTextStripperByArea;

public class PDFBoxReadFromFile {
  public static void main(String[] args) {
    try {
      File file = new File("C:/ma.pdf");
      PDDocument doc = PDDocument.load(file);
      PDFTextStripper pdfTextStripper = new PDFTextStripper();
      pdfTextStripper.setSortByPosition(true);
      pdfTextStripper.setStartPage(1);
      pdfTextStripper.setEndPage(6);
      String text = pdfTextStripper.getText(doc);
      System.out.println(text);
      doc.close();
    } catch (IOException e) {
      e.printStackTrace();
    }
  }

Output:

PDF looks like this.
Page 1:

Expected header text is only for reference and need notin print.

Tried the following:

Pattern p = Pattern.compile("PO...........*?");
Pattern p1 = Pattern.compile("Vendor...........");
Pattern p2 = Pattern.compile("100.....*?");
Pattern p4 = Pattern.compile("Date...............................................*?");
Pattern p5 = Pattern.compile("62...........3*?");
Pattern p6 = Pattern.compile("62710149950...*?");
Pattern p7 = Pattern.compile("627101499504..*?");

Matcher m = p.matcher(text);
Matcher m1 = p1.matcher(text);
Matcher m2 = p2.matcher(text);
Matcher m4 = p4.matcher(text);
Matcher m5 = p5.matcher(text);
Matcher m6 = p6.matcher(text);
Matcher m7 = p7.matcher(text);
m.find();
m1.find();
m2.find();
m4.find();
m5.find();
m6.find();
m7.find();

System.out.println(m.group(0) + "|" + m1.group(0) + "|" + m2.group(0) + "|" + m2.group(0) + "|" + "MAC" + "|" + m4.group(0) + "|" + m5.group(0) + "|");
System.out.println(m.group(0) + "|" + m1.group(0) + "|" + m2.group(0) + "|" + m2.group(0) + "|" + "MAC" + "|" + m4.group(0) + "|" + m6.group(0) + "|");
System.out.println(m.group(0) + "|" + m1.group(0) + "|" + m2.group(0) + "|" + m2.group(0) + "|" + "MAC" + "|" + m4.group(0) + "|" + m7.group(0) + "|");

Structured Output. But issue is Quantity against the Barcode alias Product code is not coming.


来源: stackexchange

问:
Custom git credential helper fails to authenticate on windows
I have a custom credential helper executable written in C++ on Windows 10. It basically just std::couts the username and password with endl:

```<code>std::cout << "username=myuser" << std::endl;
std::cout << "password=mypassword" << std::endl;
</code>```

The credential helper gets registered:

```<code>[credential "https://github.com/myuser/myrepo.git"]
     helper = C:/Users/myuser/helper/GitCredentialManager.exe
</code>```

The credential helper is called but fails to authenticate for the remote (I tested github and gitlab)

```<code>remote: Invalid username or password. fatal: Authentication failed for 'https://github.com/myuser/myrepo.git'
</code>```

2FA is disabled and I also tried to provide an access token instead of a password.

I also tried to use printf instead of std::cout. I called std::cout.flush()
Is there anything that I am doing wrong / do I miss any windows particularities?
This works perfectly fine on macOS.

答:
You might be missing the protocol line, as seen in the "Under the Hood" section.

```<code>$ git credential fill (1)
protocol=https (2)
host=mygithost
(3)
protocol=https (4)
host=mygithost
username=bob
password=s3cre7
</code>```

Git-credential is then waiting for input on stdin. We provide it with the things we know: the protocol and hostname.

A blank line indicates that the input is complete, and the credential system should answer with what it knows.

But don't forget you also have the Microsoft Git Credential Manager for Mac and Linux, which would handle all that in a secure way.

ContentLicense: CC BY-SA 4.0

Body:
I have a custom credential helper executable written in C++ on Windows 10. It basically just std::couts the username and password with endl:

std::cout << "username=myuser" << std::endl;
std::cout << "password=mypassword" << std::endl;

The credential helper gets registered:

[credential "https://github.com/myuser/myrepo.git"]
     helper = C:/Users/myuser/helper/GitCredentialManager.exe

The credential helper is called but fails to authenticate for the remote (I tested github and gitlab)

remote: Invalid username or password. fatal: Authentication failed for 'https://github.com/myuser/myrepo.git'

2FA is disabled and I also tried to provide an access token instead of a password.

I also tried to use printf instead of std::cout. I called std::cout.flush()
Is there anything that I am doing wrong / do I miss any windows particularities?
This works perfectly fine on macOS.

Body:
You might be missing the protocol line, as seen in the "Under the Hood" section.

$ git credential fill (1)
protocol=https (2)
host=mygithost
(3)
protocol=https (4)
host=mygithost
username=bob
password=s3cre7

Git-credential is then waiting for input on stdin. We provide it with the things we know: the protocol and hostname.

A blank line indicates that the input is complete, and the credential system should answer with what it knows.

But don't forget you also have the Microsoft Git Credential Manager for Mac and Linux, which would handle all that in a secure way.


问:
How can I eliminate spacing between inline elements in CSS?
I have a div with a bunch of image tags inside, here is an example:

```<code><div style="margin: 0; padding: 0; border: 0;">
    <a href="/view/foo1"><img src="foo1.jpg" alt="Foo1" /></a>
    <a href="/view/foo2"><img src="foo2.jpg" alt="Foo2" /></a>
    <a href="/view/foo3"><img src="foo3.jpg" alt="Foo3" /></a>
</div>
</code>```

Because there is whitespace between the tags, browsers will display some whitespace between the images (Chrome decides on 4px). How can I tell the browser to show NO whitespace whatsoever between the images, without placing the > and < directly next to each other? I know letter-spacing applies in addition to what the browser decides to use, so that's useless even with a negative value. Basically I'm going for something like Twitter has at the bottom of their home page. I looked at their code and they're using an unordered list. I could just do that but I'd like the technical explanation for why there appears to be no way to eliminate the white space from between these images.

答:
The spacing causes the images to move as they are inline elements. If you want them to stack up, you could use the unordered list (as twitter does) as this will put each image inside a block element.

Inline elements are displayed inline with text.

ContentLicense: CC BY-SA 3.0

Body:
I have a div with a bunch of image tags inside, here is an example:

Because there is whitespace between the tags, browsers will display some whitespace between the images (Chrome decides on 4px). How can I tell the browser to show NO whitespace whatsoever between the images, without placing the > and < directly next to each other? I know letter-spacing applies in addition to what the browser decides to use, so that's useless even with a negative value. Basically I'm going for something like Twitter has at the bottom of their home page. I looked at their code and they're using an unordered list. I could just do that but I'd like the technical explanation for why there appears to be no way to eliminate the white space from between these images.


问:
Pandas, concentrate values to list in first cell of each column in first row
I need to concentrate values to list in first cell of each column in first row

My data frame:

```<code>df = pd.DataFrame({
    'A':['one','one','two'],
    'B':[2,np.nan,2],
    'C':['main','main','main']
})
print(df)
     A    B     C
0  one  2.0  main
1  one  NaN  main
2  two  2.0  main
</code>```

expected output:

```<code>    A              B           C
0  one,one,two  2.0,2.0  main,main,main
</code>```

for one column, its not problem because I can use tolist() but in ths case i've tried to use :

df=df.apply(lambda x: ','.join(x.dropna().values.tolist()), axis=1)

from this topic:

Concatenate cells into a string with separator pandas python
but in there , it's not a list but a string, anyway I am receiving :
TypeError: ('sequence item 1: expected str instance, float found', 'occurred at index 0')

答:
You can convert the column to string and join:

```<code>df.agg(lambda x: ','.join(x.dropna().astype(str)))
</code>```

Output:

```<code>A       one,one,two
B           2.0,2.0
C    main,main,main
dtype: object
</code>```

To get a dataframe, you can chain that with .to_frame().T:

```<code>df.agg(lambda x: ','.join(x.dropna().astype(str))).to_frame().T
</code>```

gives you

```<code>              A        B               C
0  one,one,two  2.0,2.0  main,main,main
</code>```

Body:
I need to concentrate values to list in first cell of each column in first row

My data frame:

df = pd.DataFrame({
    'A':['one','one','two'],
    'B':[2,np.nan,2],
    'C':['main','main','main']
})
print(df)
     A    B     C
0  one  2.0  main
1  one  NaN  main
2  two  2.0  main

expected output:

    A              B           C
0  one,one,two  2.0,2.0  main,main,main

for one column, its not problem because I can use tolist() but in ths case i've tried to use :

df=df.apply(lambda x: ','.join(x.dropna().values.tolist()), axis=1)

from this topic:

Concatenate cells into a string with separator pandas python
but in there , it's not a list but a string, anyway I am receiving :
TypeError: ('sequence item 1: expected str instance, float found', 'occurred at index 0')

Body:
You can convert the column to string and join:

df.agg(lambda x: ','.join(x.dropna().astype(str)))

Output:

A       one,one,two
B           2.0,2.0
C    main,main,main
dtype: object

To get a dataframe, you can chain that with .to_frame().T:

df.agg(lambda x: ','.join(x.dropna().astype(str))).to_frame().T

gives you

              A        B               C
0  one,one,two  2.0,2.0  main,main,main


问:
Casting to unsigned without specifying a type
```<code>#include <stdio.h>

int main(){
  ssize_t a= -1;
  size_t b = (unsigned)a;
  return 0;
}
</code>```

a is 8 bytes all set to 1, however b becomes a 4 byte number when casted to unsigned without doing a proper (unsigned size_t), why is that? why doesn't it turn into an 8 byte unsigned variable?

答: As @marco-a told you that unsigned is shorthand for unsigned int and both are equivalent. The sizeof(unsigned int) could be 4 byte(commonly) or 8 byte, it's system-dependent. But size_t is an unsigned integral data type which is guaranteed to be big enough to contain the size of the biggest object the host system can handle. Basically the maximum permissible size is dependent on the compiler; if the compiler is 32 bit then it is simply a typedef(i.e., alias) for unsigned int but if the compiler is 64 bit then it would be a typedef for unsigned long long. The size_t data type is never negative.

Body:
#include <stdio.h>

int main(){
  ssize_t a= -1;
  size_t b = (unsigned)a;
  return 0;
}

a is 8 bytes all set to 1, however b becomes a 4 byte number when casted to unsigned without doing a proper (unsigned size_t), why is that? why doesn't it turn into an 8 byte unsigned variable?


问:
Upload dSyms Issue with terminal command
I want to upload dSyms using the following command

```<code>/path/to/Fabric/upload-symbols -a <api-key> -p
<platform> /path/to/dSYMs
</code>```

Firebase console command requires fabric <api-key> which is found in the fabric website which does not exists anymore.

how can I upload my dSyms?

答:
Firebaser here - If you're not using the legacy Fabric Crashlytics SDK and legacy upload-symbols binary, then you won't have an API key. Any apps not using the API key will be using the GoogleServices-Info.plist instead, and this shows you how: https://firebase.google.com/docs/crashlytics/get-deobfuscated-reports?platform=ios#upload-dsyms

/path/to/pods/directory/FirebaseCrashlytics/upload-symbols -gsp /path/to/GoogleService-Info.plist -p ios /path/to/dSYMs

Body:
I want to upload dSyms using the following command

/path/to/Fabric/upload-symbols -a <api-key> -p
<platform> /path/to/dSYMs

Firebase console command requires fabric <api-key> which is found in the fabric website which does not exists anymore.

how can I upload my dSyms?


问:
Python 3.8- what was instead of 'with' statement
```<code>for i in range(0,len(periods)):

        coeffs = []

        for j in range(periods[i],len(prices)-periods[i]):

            x = np.arange(0,periods[i])
            y = detrended.iloc[j-periods[i]:j

  with warnings.catch_warnings():
            warnings.simplefilter('error',OptimizeWarning)

            try:
                res = scipy.optimize.curve_fit(fseries,x,y)

            except (RuntimeError, OptimizeWarning):
                res = np.empty(1,4)
                res[0,:] = np.NAN

            if plot == True:
                xt = np.linspace(0,periods[i],100)
                yt = fseries(xt,res[0][0],res[0][1],res[0][2],res[0][3])

                plt.plot(x,y)
                plt.plot(xt,yt,'r')

                plt.show()

            coeffs = np.append(coeffs,res[0],axis=0)
        warnings.filterwarnings('ignore',category=np.VisibleDeprecationWarning)
</code>```

答:
no need to alternative for 'with' statement
only add 'from future import with_statement' on the first line of the program and then it works


问:
disable form submit button until user checks recaptcha checkbox
I'm trying to disable my form's submit button until the user clicks the Google Recaptcha checkbox 'I am not a robot'

Is there anyway to do this or do I need to download a React component specific to Google Recaptcha?

Here is my simple component that contains the Google Recaptcha:

```<code>const RecaptchaComponent = () => {
    useEffect(() => {
        // Add reCaptcha
        const script = document.createElement("script");
        script.src = "https://www.google.com/recaptcha/api.js"
        document.body.appendChild(script);
    }, [])

    return (
        <div
            className="g-recaptcha"
            data-sitekey="6LeS8_IdfdfLtQzwUgNV4545454lhvglswww14U"
        ></div>
    )
};
</code>```

And here is my form's onSubmit code:

```<code>const GameForm = () => (

<div className="app">

    <Formik
        initialValues={{
            email: "",
            name: "",
            title: ""

        }}

        onSubmit={(values) => {
            //new Promise(resolve => setTimeout(resolve, 500));
            axios({
                method: "POST",
                url: "api/gameform",
                data: JSON.stringify(values),
            });
        }}
    >

        {props => {
            const {
                values,
                isSubmitting,
                handleSubmit,

            } = props;

            return (
                <form onSubmit={handleSubmit}>

                    <div>Your Game</div>

                    <label htmlFor="title">
                        Game Title:
                    </label>
                    <Field
                        id="title"
                        type="text"
                        values={values.title}
                    />

                    <label htmlFor="name">
                        Name:
                    </label>
                    <Field
                        id="name"
                        type="text"
                        value={values.name}
                    />

                    <label htmlFor="email">
                        Email:
                    </label>
                    <Field
                        id="email"
                        name="email"
                        type="email"
                        value={values.email}
                    />

                    <div>
                    <ReCAPTCHA
                        sitekey="6LeS8_IUAAAAAhteegfgwwewqe223"
                        onChange={useCallback(() => setDisableSubmit(false))}
 />
                    </div>
                    <div>
                        <Button type="submit">
                            Submit
                        </Button>
                    </div>
                </form>
            );
        }}
    </Formik>

</div>
);
</code>```

答:
You don't need to use the react component, but it's easier.

```<code>export const MyForm = () => {

   const [disableSubmit,setDisableSubmit] = useState(true);

   return (
     ... rest of your form
     <ReCAPTCHA
         sitekey="6LeS8_IdfdfLtQzwUgNV4545454lhvglswww14U"
         onChange={useCallback(() => setDisableSubmit(false))}
     />
     <button type="submit" disabled={disableSubmit}>Submit</button>
   )

}
</code>```

EDIT:

One of my biggest pet peeves is seeing React tutorials where authors encourage devs to use functions that return JSX instead of just using functional components.

Formik's "children as a function" pattern is gross (react-router-dom does the same thing) - it should be a component:

```<code>const GameForm = () => {
  return <Formik ...your props>{props => <YourForm {...props}/>}</Formik>
}

const YourForm = (props) => {
   const [disableSubmit,setDisableSubmit] = useState(true);

   ... everything inside the child function in `GameForm`
}
</code>```

Body:
I'm trying to disable my form's submit button until the user clicks the Google Recaptcha checkbox 'I am not a robot'

Is there anyway to do this or do I need to download a React component specific to Google Recaptcha?

Here is my simple component that contains the Google Recaptcha:

const RecaptchaComponent = () => {
    useEffect(() => {
        // Add reCaptcha
        const script = document.createElement("script");
        script.src = "https://www.google.com/recaptcha/api.js"
        document.body.appendChild(script);
    }, [])

    return (

    )
};

And here is my form's onSubmit code:

const GameForm = () => (

    <Formik
        initialValues={{
            email: "",
            name: "",
            title: ""

        }}

        onSubmit={(values) => {
            //new Promise(resolve => setTimeout(resolve, 500));
            axios({
                method: "POST",
                url: "api/gameform",
                data: JSON.stringify(values),
            });
        }}
    >

        {props => {
            const {
                values,
                isSubmitting,
                handleSubmit,

            } = props;

            return (
                <form onSubmit={handleSubmit}>

Your Game

                        Game Title:

                    <Field
                        id="title"
                        type="text"
                        values={values.title}
                    />

                        Name:

                    <Field
                        id="name"
                        type="text"
                        value={values.name}
                    />

                        Email:

                    <Field
                        id="email"
                        name="email"
                        type="email"
                        value={values.email}
                    />

                    <ReCAPTCHA
                        sitekey="6LeS8_IUAAAAAhteegfgwwewqe223"
                        onChange={useCallback(() => setDisableSubmit(false))}
 />

                        <Button type="submit">
                            Submit
                        </Button>

                </form>
            );
        }}
    </Formik>

);

Body:
You don't need to use the react component, but it's easier.

export const MyForm = () => {

   const [disableSubmit,setDisableSubmit] = useState(true);

   return (
     ... rest of your form
     <ReCAPTCHA
         sitekey="6LeS8_IdfdfLtQzwUgNV4545454lhvglswww14U"
         onChange={useCallback(() => setDisableSubmit(false))}
     />
     <button type="submit" disabled={disableSubmit}>Submit</button>
   )

}

EDIT:

One of my biggest pet peeves is seeing React tutorials where authors encourage devs to use functions that return JSX instead of just using functional components.

Formik's "children as a function" pattern is gross (react-router-dom does the same thing) - it should be a component:

const GameForm = () => {
  return <Formik ...your props>{props => <YourForm {...props}/>}</Formik>
}

const YourForm = (props) => {
   const [disableSubmit,setDisableSubmit] = useState(true);

   ... everything inside the child function in `GameForm`
}


问:
SQLyog Function: Syntax error when returning values from INNER JOIN
I am writing an SQLyog function to find the status of a client depending on the amount they have spent. The amount they have spent resides in the payment table and all the clients details reside in the clients table.

Edit: Note the function works when the output is just CustStatus, seems like the issue is to do with the inclusion of the other return values.

This is the error I am receiving:

Error Code: 1064 You have an error in your SQL syntax; check the
  manual that corresponds to your MySQL server version for the right
  syntax to use near ' VARCHAR(50), VARCHAR(50), VARCHAR(10)
  DETERMINISTIC

BEGIN  DECLARE k1 INT(11' at line 2

```<code>DROP FUNCTION IF EXISTS DTC_VIP_members $$
CREATE FUNCTION DTC_VIP_members (v1 INT(11))
RETURNS INT(11), VARCHAR(50), VARCHAR(50), VARCHAR(10) DETERMINISTIC
BEGIN
DECLARE k1 INT(11);
DECLARE CustStatus VARCHAR(10);
SELECT SUM(payment.SaleAmt) INTO k1
FROM payment
INNER JOIN clients
ON payment.client_id = clients.client_id
WHERE payment.client_id = v1;
IF k1 >= 300 THEN
    UPDATE clients
    SET clients.CustStatus = 'VIP';
ELSE
    UPDATE clients
    SET clients.CustStatus = 'Non-VIP';
END IF;
RETURN clients.client_id, clients.first_name, clients.last_name, clients.CustStatus;
END $$

DELIMITER ;
</code>```

答:
SOLVED!
Thank you for taking the time to look and reply Slava!
Yes, your approach is a much better design and would probably all my silly SQL syntax errors.
I learnt that with the SQLyog server version I am working on that Functions can only RETURN one value. So my design was flawed from the beginning.

Since the SQLyog function can only return single value “vip” or “non-vip”.
I tried using a select such as to achieve the desired results.
Select firstName, lastName, ….  DTC_VIP_members(….);

Hopefully, this answer helps any other beginners trying to learn SQL from the free version of SQLyog.
Updoots to the left

```<code>   DELIMITER $$

    DROP FUNCTION IF EXISTS `DTC_VIP_members`$$

    CREATE DEFINER=`yadda`@`%` FUNCTION `DTC_VIP_members`(v1 INT(11)) RETURNS VARCHAR(10) CHARSET latin1
        DETERMINISTIC
    BEGIN
        DECLARE k1 INT(11);
        DECLARE CustStatus VARCHAR(10);
        SELECT SUM(SaleAmt) INTO k1
        FROM payment
        WHERE client_id = v1;
        IF k1 >= 300 THEN
            SET CustStatus = 'VIP';
        ELSE
            SET CustStatus = 'Non-VIP';
        END IF;
        RETURN CustStatus;
        END$$

    DELIMITER ;

    --------------------------------------

    SELECT  first_name, last_name, email, mobile_number, `DTC_VIP_members`(client_id)
    FROM clients;
</code>```

Body:
I am writing an SQLyog function to find the status of a client depending on the amount they have spent. The amount they have spent resides in the payment table and all the clients details reside in the clients table.

Edit: Note the function works when the output is just CustStatus, seems like the issue is to do with the inclusion of the other return values.

This is the error I am receiving:

Error Code: 1064 You have an error in your SQL syntax; check the
  manual that corresponds to your MySQL server version for the right
  syntax to use near ' VARCHAR(50), VARCHAR(50), VARCHAR(10)
  DETERMINISTIC

BEGIN  DECLARE k1 INT(11' at line 2

DROP FUNCTION IF EXISTS DTC_VIP_members $$
CREATE FUNCTION DTC_VIP_members (v1 INT(11))
RETURNS INT(11), VARCHAR(50), VARCHAR(50), VARCHAR(10) DETERMINISTIC
BEGIN
DECLARE k1 INT(11);
DECLARE CustStatus VARCHAR(10);
SELECT SUM(payment.SaleAmt) INTO k1
FROM payment
INNER JOIN clients
ON payment.client_id = clients.client_id
WHERE payment.client_id = v1;
IF k1 >= 300 THEN
    UPDATE clients
    SET clients.CustStatus = 'VIP';
ELSE
    UPDATE clients
    SET clients.CustStatus = 'Non-VIP';
END IF;
RETURN clients.client_id, clients.first_name, clients.last_name, clients.CustStatus;
END $$

DELIMITER ;

Body:
SOLVED!
Thank you for taking the time to look and reply Slava!
Yes, your approach is a much better design and would probably all my silly SQL syntax errors.
I learnt that with the SQLyog server version I am working on that Functions can only RETURN one value. So my design was flawed from the beginning.

Since the SQLyog function can only return single value “vip” or “non-vip”.
I tried using a select such as to achieve the desired results.
Select firstName, lastName, ….  DTC_VIP_members(….);

Hopefully, this answer helps any other beginners trying to learn SQL from the free version of SQLyog.
Updoots to the left

   DELIMITER $$

    DROP FUNCTION IF EXISTS `DTC_VIP_members`$$

    CREATE DEFINER=`yadda`@`%` FUNCTION `DTC_VIP_members`(v1 INT(11)) RETURNS VARCHAR(10) CHARSET latin1
        DETERMINISTIC
    BEGIN
        DECLARE k1 INT(11);
        DECLARE CustStatus VARCHAR(10);
        SELECT SUM(SaleAmt) INTO k1
        FROM payment
        WHERE client_id = v1;
        IF k1 >= 300 THEN
            SET CustStatus = 'VIP';
        ELSE
            SET CustStatus = 'Non-VIP';
        END IF;
        RETURN CustStatus;
        END$$

    DELIMITER ;

    --------------------------------------

    SELECT  first_name, last_name, email, mobile_number, `DTC_VIP_members`(client_id)
    FROM clients;


问:
How to fix "unable to find Git in your path " error , despite providing required path
Whenever i try to run a flutter command (in cmd), the following error occurs :

'where' is not recognized as an internal or external command,
  operable program or batch file.

Error: Unable to find git in your PATH.

I found the similar error here
How to solve "Unable to find git in your PATH" on Flutter? and tried everything

things I've done:

included all essential git paths i.e.

C:\Program Files\Git\bin\git.exe;C:\Program Files\Git\cmd;C:\Windows\System32

(did the above step many times , restarted computer and tried again = fail
)

checked flutter bin path

tried running cmd as administrator

tried running command in flutter console

None of the above worked as the error still prevails.

EDIT : I uninstalled Git completely , then reinstalled it (choosing the right options) , checked environment variables and everything , gave the flutter command in cmd , and it still shows the same error! I don't know what to do now .

答:
A path should not include git.exe, only its parent folder.

See my example if simplified PATH:

```<code>set PATH=C:\WINDOWS\system32;C:\WINDOWS;C:\WINDOWS\System32\Wbem;C:\WINDOWS\System32\WindowsPowerShell\v1.0\
set GH=C:\path\to\git
set PATH=%GH%\bin;%GH%\usr\bin;%GH%\mingw64\bin;%PATH%
</code>```

By adding:

```<code>set PATH=C:\Flutter\flutter\bin;%PATH%
</code>```

The OP confirms in the chat that it is working.

Body:
A path should not include git.exe, only its parent folder.

See my example if simplified PATH:

set PATH=C:\WINDOWS\system32;C:\WINDOWS;C:\WINDOWS\System32\Wbem;C:\WINDOWS\System32\WindowsPowerShell\v1.0\
set GH=C:\path\to\git
set PATH=%GH%\bin;%GH%\usr\bin;%GH%\mingw64\bin;%PATH%

By adding:

set PATH=C:\Flutter\flutter\bin;%PATH%

The OP confirms in the chat that it is working.


问:
Script not working on localhost but works in jsfiddle
This jsfiddle works http://jsfiddle.net/y913yh4u/2/ but the code saved locally doesn't work https://pastebin.com/rkiDRfFz

using this says that DataTable isn't a function, even though the script is included.

```<code> $(document).ready(function(){
        $('#myTable').DataTable();
    });
</code>```

LocalHost:

JSFIDDLE:

Any help would be appericated.

答:
JavaScript is attached before the closing body tag.

The browser stops parsing the page when it encounters a script tag. Therefore, so that the user sees the content as early as possible, the connection of scripts is delayed until the very last moment.

Try to do so.

```<code><head>
  <link rel="stylesheet" type="text/css" href="http://ajax.aspnetcdn.com/ajax/jquery.dataTables/1.9.0/css/jquery.dataTables.css">
  <link rel="stylesheet" type="text/css" href="http://ajax.aspnetcdn.com/ajax/jquery.dataTables/1.9.0/css/jquery.dataTables_themeroller.css">
</head>

<body>

  <table id="myTable" class="display" cellspacing="0" width="100%">
    <thead>
      ...
    </thead>
    <tbody>
      ...
    </tbody>
  </table>

  <script type="text/javascript" charset="utf8" src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.7.1.min.js"></script>
  <script type="text/javascript" charset="utf8" src="http://ajax.aspnetcdn.com/ajax/jquery.dataTables/1.9.0/jquery.dataTables.min.js"></script>

</body>
</code>```

Body:
This jsfiddle works http://jsfiddle.net/y913yh4u/2/ but the code saved locally doesn't work https://pastebin.com/rkiDRfFz

using this says that DataTable isn't a function, even though the script is included.

 $(document).ready(function(){
        $('#myTable').DataTable();
    });

LocalHost:

JSFIDDLE:

Any help would be appericated.

Body:
JavaScript is attached before the closing body tag.

The browser stops parsing the page when it encounters a script tag. Therefore, so that the user sees the content as early as possible, the connection of scripts is delayed until the very last moment.

Try to do so.

<head>
  <link rel="stylesheet" type="text/css" href="http://ajax.aspnetcdn.com/ajax/jquery.dataTables/1.9.0/css/jquery.dataTables.css">
  <link rel="stylesheet" type="text/css" href="http://ajax.aspnetcdn.com/ajax/jquery.dataTables/1.9.0/css/jquery.dataTables_themeroller.css">
</head>

<body>

  <table id="myTable" class="display" cellspacing="0" width="100%">
    <thead>
      ...
    </thead>
    <tbody>
      ...
    </tbody>
  </table>

  <script type="text/javascript" charset="utf8" src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.7.1.min.js"></script>
  <script type="text/javascript" charset="utf8" src="http://ajax.aspnetcdn.com/ajax/jquery.dataTables/1.9.0/jquery.dataTables.min.js"></script>

</body>


问:
Create 5 new columns from multiple CSV files
I have 4 CSV files that have 2 columns each.

```<code>User   Number  |  User1   Number1  |  User2    Number2  |  User3   Number3
Sam         3  |  Tim           4  |  Mark          11  |  Jane          3
Tim         6  |  Gab           2  |  Jane          12  |  Moll          5
Ale         8  |  Jane          9  |  Moll           3  |  Mary          5
Jane        2  |  Tj            7  |  Gab            8  |  Kim           3
</code>```

Process

Create 2 new columns holding the User and Number info of all users that only appear once.

Create 2 other columns when names exist in more than one CSV.

Those that appear more than once, have their new number be the addition of their numbers across different CSV's.

Have a column that says which CSV the duplicate name has come from.

Desired Output

```<code>User   Number  |  User1    Number1  |  Which CSV
Sam         3  |  Tim           10  |  User, User1
Ale         8  |  Jane          26  |  User, User1, User2, User3
TJ          7  |  Gab           10  |  User1, User2
Mark       11  |  Moll           8  |  User2, User3
Mary        5  |
Kim         3  |
</code>```

Attempt

usernameandlikes = pd.Series(dict(functools.reduce(operator.add, map(collections.Counter, [dict(zip(df["username"], df["likes"])), dict(zip(df["username2"], df["likes2"]))])))).reset_index()
usernameandlikes.columns = ["lcnames", "lcagg"]
username3_likes3 = usernameandlikes.loc[usernameandlikes['lcnames'].isin(list(set(df["username"]).intersection(set(df["username2"]))))].reset_index(drop=True)
username3_likes4 = usernameandlikes.loc[usernameandlikes['lcnames'].isin(list(set(df["username"]).symmetric_difference(set(df["username2"]))))].reset_index(drop=True)
```

答:
First I would append() all data to one DataFrame with three columns User, Number, File.

In code I use module io only to simulate files.

```<code>csv0 = '''User   Number
Sam         3
Tim         6
Ale         8
Jane        2'''

csv1 = '''User1   Number1
Tim           4
Gab           2
Jane          9
Tj            7'''

csv2 = '''User2    Number2
Mark          11
Jane          12
Moll           3
Gab            8'''

csv3 = '''User3   Number3
Jane          3
Moll          5
Mary          5
Kim           3'''

import pandas as pd
import io

df0 = pd.read_csv(io.StringIO(csv0), sep='\s+')
df0['File'] = 'User'
#print(df0)

df1 = pd.read_csv(io.StringIO(csv1), sep='\s+')
df1.columns = ['User', 'Number']
df1['File'] = 'User1'
#print(df1)

df2 = pd.read_csv(io.StringIO(csv2), sep='\s+')
df2.columns = ['User', 'Number']
df2['File'] = 'User2'
#print(df2)

df3 = pd.read_csv(io.StringIO(csv3), sep='\s+')
df3.columns = ['User', 'Number']
df3['File'] = 'User3'
#print(df3)

df = df0.append([df1, df2, df3]).reset_index(drop=True)
print(df)
</code>```

Results:

```<code>    User  Number   File
0    Sam       3   User
1    Tim       6   User
2    Ale       8   User
3   Jane       2   User
4    Tim       4  User1
5    Gab       2  User1
6   Jane       9  User1
7     Tj       7  User1
8   Mark      11  User2
9   Jane      12  User2
10  Moll       3  User2
11   Gab       8  User2
12  Jane       3  User3
13  Moll       5  User3
14  Mary       5  User3
15   Kim       3  User3
</code>```

And now I can use groupby('User') to select userw which are only once in all data

```<code>print('--- single ---')
df_single = df.groupby('User').filter(lambda x: len(x) == 1)
print(df_single)
</code>```

Result:

```<code>--- single ---
    User  Number   File
0    Sam       3   User
2    Ale       8   User
7     Tj       7  User1
8   Mark      11  User2
14  Mary       5  User3
15   Kim       3  User3
</code>```

The same for users which are many times in data

```<code>print('--- multi ---')
df_multi = df.groupby('User').filter(lambda x: len(x) > 1)
print(df_multi)
</code>```

Result:

```<code>--- multi ---
    User  Number   File
1    Tim       6   User
3   Jane       2   User
4    Tim       4  User1
5    Gab       2  User1
6   Jane       9  User1
9   Jane      12  User2
10  Moll       3  User2
11   Gab       8  User2
12  Jane       3  User3
13  Moll       5  User3
</code>```

And I can use groupby().sum() to sum numbers

```<code>print('--- multi sum ---')
df_multi_sum = df_multi.groupby('User').sum().reset_index()
print(df_multi_sum)
</code>```

Result:

```<code>--- multi sum ---
   User  Number
0   Gab      10
1  Jane      26
2  Moll       8
3   Tim      10
</code>```

And groupby().apply() to create column Which CSV

```<code>print('--- multi sum file ---')
df_multi_sum['Which CSV'] = df_multi.groupby('User').apply(lambda x: ','.join(x['File'])).reset_index()[0]
print(df_multi_sum)
</code>```

Result:

```<code>--- multi sum file ---
   User  Number               Which CSV
0   Gab      10             User1,User2
1  Jane      26  User,User1,User2,User3
2  Moll       8             User2,User3
3   Tim      10              User,User1
</code>```

Body:
I have 4 CSV files that have 2 columns each.

User   Number  |  User1   Number1  |  User2    Number2  |  User3   Number3
Sam         3  |  Tim           4  |  Mark          11  |  Jane          3
Tim         6  |  Gab           2  |  Jane          12  |  Moll          5
Ale         8  |  Jane          9  |  Moll           3  |  Mary          5
Jane        2  |  Tj            7  |  Gab            8  |  Kim           3

Process

Create 2 new columns holding the User and Number info of all users that only appear once.

Create 2 other columns when names exist in more than one CSV.

Those that appear more than once, have their new number be the addition of their numbers across different CSV's.

Have a column that says which CSV the duplicate name has come from.

Desired Output

User   Number  |  User1    Number1  |  Which CSV
Sam         3  |  Tim           10  |  User, User1
Ale         8  |  Jane          26  |  User, User1, User2, User3
TJ          7  |  Gab           10  |  User1, User2
Mark       11  |  Moll           8  |  User2, User3
Mary        5  |
Kim         3  |

Attempt

usernameandlikes = pd.Series(dict(functools.reduce(operator.add, map(collections.Counter, [dict(zip(df["username"], df["likes"])), dict(zip(df["username2"], df["likes2"]))])))).reset_index()
usernameandlikes.columns = ["lcnames", "lcagg"]
username3_likes3 = usernameandlikes.loc[usernameandlikes['lcnames'].isin(list(set(df["username"]).intersection(set(df["username2"]))))].reset_index(drop=True)
username3_likes4 = usernameandlikes.loc[usernameandlikes['lcnames'].isin(list(set(df["username"]).symmetric_difference(set(df["username2"]))))].reset_index(drop=True)

Body:
First I would append() all data to one DataFrame with three columns User, Number, File.

In code I use module io only to simulate files.

csv0 = '''User   Number
Sam         3
Tim         6
Ale         8
Jane        2'''

csv1 = '''User1   Number1
Tim           4
Gab           2
Jane          9
Tj            7'''

csv2 = '''User2    Number2
Mark          11
Jane          12
Moll           3
Gab            8'''

csv3 = '''User3   Number3
Jane          3
Moll          5
Mary          5
Kim           3'''

import pandas as pd
import io

df0 = pd.read_csv(io.StringIO(csv0), sep='\s+')
df0['File'] = 'User'
#print(df0)

df1 = pd.read_csv(io.StringIO(csv1), sep='\s+')
df1.columns = ['User', 'Number']
df1['File'] = 'User1'
#print(df1)

df2 = pd.read_csv(io.StringIO(csv2), sep='\s+')
df2.columns = ['User', 'Number']
df2['File'] = 'User2'
#print(df2)

df3 = pd.read_csv(io.StringIO(csv3), sep='\s+')
df3.columns = ['User', 'Number']
df3['File'] = 'User3'
#print(df3)

df = df0.append([df1, df2, df3]).reset_index(drop=True)
print(df)

Results:

    User  Number   File
0    Sam       3   User
1    Tim       6   User
2    Ale       8   User
3   Jane       2   User
4    Tim       4  User1
5    Gab       2  User1
6   Jane       9  User1
7     Tj       7  User1
8   Mark      11  User2
9   Jane      12  User2
10  Moll       3  User2
11   Gab       8  User2
12  Jane       3  User3
13  Moll       5  User3
14  Mary       5  User3
15   Kim       3  User3

And now I can use groupby('User') to select userw which are only once in all data

print('--- single ---')
df_single = df.groupby('User').filter(lambda x: len(x) == 1)
print(df_single)

Result:

--- single ---
    User  Number   File
0    Sam       3   User
2    Ale       8   User
7     Tj       7  User1
8   Mark      11  User2
14  Mary       5  User3
15   Kim       3  User3

The same for users which are many times in data

print('--- multi ---')
df_multi = df.groupby('User').filter(lambda x: len(x) > 1)
print(df_multi)

Result:

--- multi ---
    User  Number   File
1    Tim       6   User
3   Jane       2   User
4    Tim       4  User1
5    Gab       2  User1
6   Jane       9  User1
9   Jane      12  User2
10  Moll       3  User2
11   Gab       8  User2
12  Jane       3  User3
13  Moll       5  User3

And I can use groupby().sum() to sum numbers

print('--- multi sum ---')
df_multi_sum = df_multi.groupby('User').sum().reset_index()
print(df_multi_sum)

Result:

--- multi sum ---
   User  Number
0   Gab      10
1  Jane      26
2  Moll       8
3   Tim      10

And groupby().apply() to create column Which CSV

print('--- multi sum file ---')
df_multi_sum['Which CSV'] = df_multi.groupby('User').apply(lambda x: ','.join(x['File'])).reset_index()[0]
print(df_multi_sum)

Result:

--- multi sum file ---
   User  Number               Which CSV
0   Gab      10             User1,User2
1  Jane      26  User,User1,User2,User3
2  Moll       8             User2,User3
3   Tim      10              User,User1


问:
Check that text is visible Selenium + Java
Here is HTML:

```<code><select size="1" id="F_21__3" class="c3" style="position: absolute; left: 127px; top: 173px; width: 148px; height: 14px; font-style: normal; font-weight: normal; text-decoration: none; text-shadow: none; font-stretch: normal;" disabled="disabled">
    <option value="I" des="Item">Item</option>
    <option value="S" des="Service">Service</option>
</select>
</code>```

How to check that text "Service" is visible with Selenium + Java?

答:
It's not important if the field is disabled or enabled. You just find the correct selector and after that you can check it very easy.

```<code>String actualText = driver.findElemeny(By.cssSelector("yourSelector")).getAttribut("value");
Assert.assertEqual(actualText, "Service");
</code>```

or more simple (but only if Service don't appear in another place on your page).

```<code>boolean presence = false;
if(driver.getPageSource().contains("Service")){
System.out.println("Text is present");
presence = true;
}else{
System.out.println("Text is absent");}

Assert.assertTrue(presence);
</code>```

Body:
Here is HTML:

<select size="1" id="F_21__3" class="c3" style="position: absolute; left: 127px; top: 173px; width: 148px; height: 14px; font-style: normal; font-weight: normal; text-decoration: none; text-shadow: none; font-stretch: normal;" disabled="disabled">
    <option value="I" des="Item">Item</option>
    <option value="S" des="Service">Service</option>
</select>

How to check that text "Service" is visible with Selenium + Java?

Body:
It's not important if the field is disabled or enabled. You just find the correct selector and after that you can check it very easy.

String actualText = driver.findElemeny(By.cssSelector("yourSelector")).getAttribut("value");
Assert.assertEqual(actualText, "Service");

or more simple (but only if Service don't appear in another place on your page).

boolean presence = false;
if(driver.getPageSource().contains("Service")){
System.out.println("Text is present");
presence = true;
}else{
System.out.println("Text is absent");}

Assert.assertTrue(presence);


问:
How to programmatically schedule sale dates in Woocommerce
Im trying to schedule the sale period in woocommerce when a post is saved (published).

I have tried both methods below but neither of them are working. The code is being called at the right time, just not updating the post meta.

Neither methods are updating the sale schedule.

```<code>add_action('save_post_product', array($this, 'knpv_new_product_from_draft'), 10, 2);
add_action('edit_post_product', array($this, 'knpv_new_product_from_draft'), 10, 2);
public function knpv_new_product_from_draft($post_id, $post){

    //Get todays date and the date 15 days from now
    $datefrom = strtotime(date('Y-m-d'));
    $dateto = strtotime(date('Y-m-d', strtotime('+15 days',$datefrom)));

    //Method 1
    $product = wc_get_product($post_id);

    if( !empty(get_post_meta($post_id, '_sale_price', true)) ){
        $product->set_date_on_sale_from( $datefrom );
        $product->set_date_on_sale_to( $dateto );
    }

    $product->save();

    //Method 2
    $var = update_post_meta($post_id, '_sale_price_dates_from', $datefrom);
    $var2 = update_post_meta($post_id, '_sale_price_dates_to',   $dateto);

}
</code>```

答:
The reason this wasn't working was because the meta was being updated after the save_post action had finished. So I was updating the meta, then the empty values from the form were also updating them and clearing them. </p>

<p>So I did it like this. </p>

```<code>add_action('save_post_product', array($this, 'knpv_new_product_from_draft'), 10, 2);
add_action('edit_post_product', array($this, 'knpv_new_product_from_draft'), 10, 2);
public function knpv_new_product_from_draft($post_id, $post){
  //If the post is being published.
  if (get_post_status($post_id) == 'publish') {

    //Set the values from the posted form data.
    $_POST['_sale_price_dates_from'] = date('Y-m-d');
    $_POST['_sale_price_dates_to'] = date('Y-m-d', strtotime($datefrom.' +15 days'));

  }
}
</code>```

Body:
Im trying to schedule the sale period in woocommerce when a post is saved (published).

I have tried both methods below but neither of them are working. The code is being called at the right time, just not updating the post meta.

Neither methods are updating the sale schedule.

add_action('save_post_product', array($this, 'knpv_new_product_from_draft'), 10, 2);
add_action('edit_post_product', array($this, 'knpv_new_product_from_draft'), 10, 2);
public function knpv_new_product_from_draft($post_id, $post){

    //Get todays date and the date 15 days from now
    $datefrom = strtotime(date('Y-m-d'));
    $dateto = strtotime(date('Y-m-d', strtotime('+15 days',$datefrom)));

    //Method 1
    $product = wc_get_product($post_id);

    if( !empty(get_post_meta($post_id, '_sale_price', true)) ){
        $product->set_date_on_sale_from( $datefrom );
        $product->set_date_on_sale_to( $dateto );
    }

    $product->save();

    //Method 2
    $var = update_post_meta($post_id, '_sale_price_dates_from', $datefrom);
    $var2 = update_post_meta($post_id, '_sale_price_dates_to',   $dateto);

}

Body:
The reason this wasn't working was because the meta was being updated after the save_post action had finished. So I was updating the meta, then the empty values from the form were also updating them and clearing them.

So I did it like this.

add_action('save_post_product', array($this, 'knpv_new_product_from_draft'), 10, 2);
add_action('edit_post_product', array($this, 'knpv_new_product_from_draft'), 10, 2);
public function knpv_new_product_from_draft($post_id, $post){
  //If the post is being published.
  if (get_post_status($post_id) == 'publish') {

    //Set the values from the posted form data.
    $_POST['_sale_price_dates_from'] = date('Y-m-d');
    $_POST['_sale_price_dates_to'] = date('Y-m-d', strtotime($datefrom.' +15 days'));

  }
}


问:
Why I can't bind the background color in different platform?
Here is XAML:

```<code><?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             xmlns:d="http://xamarin.com/schemas/2014/forms/design"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
             mc:Ignorable="d"
             x:Class="App1.MainPage">

    <BoxView>
        <BoxView.BackgroundColor>
            <OnPlatform x:TypeArguments="Color">
                <On Platform="Android" Value="{Binding First}"></On>
                <On Platform="iOS" Value="{Binding Second}"></On>
            </OnPlatform>
        </BoxView.BackgroundColor>
    </BoxView>
</ContentPage>
</code>```

Here is code-behind:

```<code>using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Xamarin.Forms;

namespace App1
{
    // Learn more about making custom code visible in the Xamarin.Forms previewer
    // by visiting https://aka.ms/xamarinforms-previewer
    [DesignTimeVisible(false)]
    public partial class MainPage : ContentPage
    {
        public MainPage()
        {
            InitializeComponent();
            this.BindingContext = this;
        }
        public Color First {
            get {
                return Color.FromHex("#575757");
            }
        }
        public Color Second
        {
            get
            {
                return Color.FromHex("#ffffff");
            }
        }
    }
}
</code>```

After I ran the program, it reports an error:
Specified cast is not valid.

What's the problem with it?

答:
I had to dug a bit into the docs to find it. OnPlatform can't take bindable values for the Color property.

From OnPlatform markup extension docs:

The XAML parser expects that values of the correct type will be provided to properties consuming the OnPlatform markup extension. If type conversion is necessary, the OnPlatform markup extension will attempt to perform it using the default converters provided by Xamarin.Forms. However, there are some type conversions that can't be performed by the default converters and in these cases the Converter property should be set to an IValueConverter implementation.

When you open the tag <BoxView.BackgroundColor>, the xaml analyzer will expect a value of type Color, like you have defined it in the next row. After that, you are passing a value that extends BindingBase class and is returning a value of this type. There is a cast conflict with the bindable value and the Color object that the parser expects out of the box.

What is happening behind the scenes is (look at the comments):

<BoxView>
    <BoxView.BackgroundColor>
        <OnPlatform x:TypeArguments="Color">
            <On Platform="Android" Value="{Binding First}"></On>
            <On Platform="iOS" Value="{Binding Second}"></On>
        </OnPlatform>
     </BoxView.BackgroundColor>
</BoxView>
```

<p>According to the documentation, you can try to define the cast in a converter, which is not the best approach, since you will be hiding this part of the converting behind the scenes. An alternative (and better) approach is to have the <code>BackgroundColor</code>'s binding to one property and define the logic there like so:</p>

<pre class="lang-xml prettyprint-override"><code><BoxView BackgroundColor="{Binding BgColor}" />
</code>```

and in the code-behind:

public Color BgColor => Device.RuntimePlatform == Device.Android ? Color.FromHex("#575757") : Color.FromHex("#ffffff");
```

NB: The last code assumes that you are developing only for 2 platforms - iOS & Android. If you are/plan to develop to other platforms, you need to extend the RuntimePlatform check.

Body:
Here is XAML:

<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             xmlns:d="http://xamarin.com/schemas/2014/forms/design"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
             mc:Ignorable="d"
             x:Class="App1.MainPage">

    <BoxView>
        <BoxView.BackgroundColor>
            <OnPlatform x:TypeArguments="Color">
                <On Platform="Android" Value="{Binding First}"></On>
                <On Platform="iOS" Value="{Binding Second}"></On>
            </OnPlatform>
        </BoxView.BackgroundColor>
    </BoxView>
</ContentPage>

Here is code-behind:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Xamarin.Forms;

namespace App1
{
    // Learn more about making custom code visible in the Xamarin.Forms previewer
    // by visiting https://aka.ms/xamarinforms-previewer
    [DesignTimeVisible(false)]
    public partial class MainPage : ContentPage
    {
        public MainPage()
        {
            InitializeComponent();
            this.BindingContext = this;
        }
        public Color First {
            get {
                return Color.FromHex("#575757");
            }
        }
        public Color Second
        {
            get
            {
                return Color.FromHex("#ffffff");
            }
        }
    }
}

After I ran the program, it reports an error:
Specified cast is not valid.

What's the problem with it?

Body:
I had to dug a bit into the docs to find it. OnPlatform can't take bindable values for the Color property.

From OnPlatform markup extension docs:

The XAML parser expects that values of the correct type will be provided to properties consuming the OnPlatform markup extension. If type conversion is necessary, the OnPlatform markup extension will attempt to perform it using the default converters provided by Xamarin.Forms. However, there are some type conversions that can't be performed by the default converters and in these cases the Converter property should be set to an IValueConverter implementation.

When you open the tag <BoxView.BackgroundColor>, the xaml analyzer will expect a value of type Color, like you have defined it in the next row. After that, you are passing a value that extends BindingBase class and is returning a value of this type. There is a cast conflict with the bindable value and the Color object that the parser expects out of the box.

What is happening behind the scenes is (look at the comments):

<BoxView>
    <BoxView.BackgroundColor> <!-- You are saying that we want to modify a property of type Color -->
        <OnPlatform x:TypeArguments="Color"> <!-- Here the analyzer expects type Color, nothing else will work | checked build time -->
            <On Platform="Android" Value="{Binding First}"></On> <!-- The parser expects type Color, but is receiving type BindingBase | checked run time -->
            <On Platform="iOS" Value="{Binding Second}"></On> <!-- The parser expects type Color, but is receiving type BindingBase | checked run time -->
        </OnPlatform>
     </BoxView.BackgroundColor>
</BoxView>

According to the documentation, you can try to define the cast in a converter, which is not the best approach, since you will be hiding this part of the converting behind the scenes. An alternative (and better) approach is to have the BackgroundColor's binding to one property and define the logic there like so:

<BoxView BackgroundColor="{Binding BgColor}" />

and in the code-behind:

public Color BgColor => Device.RuntimePlatform == Device.Android ? Color.FromHex("#575757") : Color.FromHex("#ffffff");

NB: The last code assumes that you are developing only for 2 platforms - iOS & Android. If you are/plan to develop to other platforms, you need to extend the RuntimePlatform check.


问:
Saxonica - .NET API - XQuery - XPDY0002: The context item for axis step root/descendant::xxx is absent
I'm getting same error as this question, but with XQuery:
SaxonApiException: The context item for axis step ./CLIENT is absent

When running from the command line, all is good.  So I don't think there is a syntax problem with the XQuery itself.  I won't post the input file unless needed.

The XQuery is displayed with a Console.WriteLine before the error appears:

```<code>----- Start: XQUERY:
(:  FLWOR = For Let Where Order-by Return   :)
<MyFlightLegs>
{
for $flightLeg in //FlightLeg
where $flightLeg/DepartureAirport = 'OKC' or $flightLeg/ArrivalAirport = 'OKC'
order by $flightLeg/ArrivalDate[1] descending
return $flightLeg
}
</MyFlightLegs>

----- End  : XQUERY:
Error evaluating (<MyFlightLegs {for $flightLeg in root/descendant::FlightLeg[DepartureAirport = "OKC" or ArrivalAirport = "OKC"] ... return $flightLeg}/>) on line 4 column 20
  XPDY0002: The context item for axis step root/descendant::FlightLeg is absent
</code>```

I think that like the other question, maybe my input XML file is not properly specified.

I took the samples/cs/ExamplesHE.cs run method of the XQuerytoStream class.

Code there for easy reference is:

```<code>public class XQueryToStream : Example
{

    public override string testName
    {
        get { return "XQueryToStream"; }
    }

    public override void run(Uri samplesDir)
    {
        Processor processor = new Processor();
        XQueryCompiler compiler = processor.NewXQueryCompiler();
        compiler.BaseUri = samplesDir.ToString();
        compiler.DeclareNamespace("saxon", "http://saxon.sf.net/");
        XQueryExecutable exp = compiler.Compile("<saxon:example>{static-base-uri()}</saxon:example>");
        XQueryEvaluator eval = exp.Load();
        Serializer qout = processor.NewSerializer();
        qout.SetOutputProperty(Serializer.METHOD, "xml");
        qout.SetOutputProperty(Serializer.INDENT, "yes");
        qout.SetOutputStream(new FileStream("testoutput.xml", FileMode.Create, FileAccess.Write));
        Console.WriteLine("Output written to testoutput.xml");
        eval.Run(qout);
    }

}
</code>```

I changed to pass the Xquery file name, the xml file name, and the output file name, and tried to make a static method out of it. (Had success doing the same with the XSLT processor.)

```<code>static void DemoXQuery(string xmlInputFilename, string xqueryInputFilename, string outFilename)
{

    // Create a Processor instance.
    Processor processor = new Processor();

    // Load the source document
    DocumentBuilder loader = processor.NewDocumentBuilder();
    loader.BaseUri = new Uri(xmlInputFilename);
    XdmNode indoc = loader.Build(loader.BaseUri);

    XQueryCompiler compiler = processor.NewXQueryCompiler();
    //BaseUri is inconsistent with Transform= Processor?
    //compiler.BaseUri = new Uri(xqueryInputFilename);
    //compiler.DeclareNamespace("saxon", "http://saxon.sf.net/");

    string xqueryFileContents = File.ReadAllText(xqueryInputFilename);
    Console.WriteLine("----- Start: XQUERY:");
    Console.WriteLine(xqueryFileContents);
    Console.WriteLine("----- End  : XQUERY:");
    XQueryExecutable exp = compiler.Compile(xqueryFileContents);
    XQueryEvaluator eval = exp.Load();

    Serializer qout = processor.NewSerializer();
    qout.SetOutputProperty(Serializer.METHOD, "xml");
    qout.SetOutputProperty(Serializer.INDENT, "yes");
    qout.SetOutputStream(new FileStream(outFilename,
                 FileMode.Create, FileAccess.Write));

    eval.Run(qout);

}
</code>```

Also two questions regarding "BaseURI".

1. Should it be a directory name, or can it be same as the Xquery file name?
2. I get this compile error: "Cannot implicity convert to "System.Uri" to "String".

```<code>compiler.BaseUri = new Uri(xqueryInputFilename);
</code>```

It's exactly the same thing I did for XSLT which worked. But it looks like BaseUri is a string for XQuery, but a real Uri object for XSLT?  Any reason for the difference?

答:
Bottom line solution based on Michael Kay's response; I added this line of code after doing the exp.Load(): </p>

```<code>eval.ContextItem = indoc;
</code>```

<p>The indoc object created earlier is what relates to the XML input file to be processed by the XQuery. </p>

Body:
I'm getting same error as this question, but with XQuery:
SaxonApiException: The context item for axis step ./CLIENT is absent

When running from the command line, all is good.  So I don't think there is a syntax problem with the XQuery itself.  I won't post the input file unless needed.

The XQuery is displayed with a Console.WriteLine before the error appears:

----- Start: XQUERY:
(:  FLWOR = For Let Where Order-by Return   :)
<MyFlightLegs>
{
for $flightLeg in //FlightLeg
where $flightLeg/DepartureAirport = 'OKC' or $flightLeg/ArrivalAirport = 'OKC'
order by $flightLeg/ArrivalDate[1] descending
return $flightLeg
}
</MyFlightLegs>

----- End  : XQUERY:
Error evaluating (<MyFlightLegs {for $flightLeg in root/descendant::FlightLeg[DepartureAirport = "OKC" or ArrivalAirport = "OKC"] ... return $flightLeg}/>) on line 4 column 20
  XPDY0002: The context item for axis step root/descendant::FlightLeg is absent

I think that like the other question, maybe my input XML file is not properly specified.

I took the samples/cs/ExamplesHE.cs run method of the XQuerytoStream class.

Code there for easy reference is:

public class XQueryToStream : Example
{

    public override string testName
    {
        get { return "XQueryToStream"; }
    }

    public override void run(Uri samplesDir)
    {
        Processor processor = new Processor();
        XQueryCompiler compiler = processor.NewXQueryCompiler();
        compiler.BaseUri = samplesDir.ToString();
        compiler.DeclareNamespace("saxon", "http://saxon.sf.net/");
        XQueryExecutable exp = compiler.Compile("<saxon:example>{static-base-uri()}</saxon:example>");
        XQueryEvaluator eval = exp.Load();
        Serializer qout = processor.NewSerializer();
        qout.SetOutputProperty(Serializer.METHOD, "xml");
        qout.SetOutputProperty(Serializer.INDENT, "yes");
        qout.SetOutputStream(new FileStream("testoutput.xml", FileMode.Create, FileAccess.Write));
        Console.WriteLine("Output written to testoutput.xml");
        eval.Run(qout);
    }

}

I changed to pass the Xquery file name, the xml file name, and the output file name, and tried to make a static method out of it. (Had success doing the same with the XSLT processor.)

static void DemoXQuery(string xmlInputFilename, string xqueryInputFilename, string outFilename)
{

    // Create a Processor instance.
    Processor processor = new Processor();

    // Load the source document
    DocumentBuilder loader = processor.NewDocumentBuilder();
    loader.BaseUri = new Uri(xmlInputFilename);
    XdmNode indoc = loader.Build(loader.BaseUri);

    XQueryCompiler compiler = processor.NewXQueryCompiler();
    //BaseUri is inconsistent with Transform= Processor?
    //compiler.BaseUri = new Uri(xqueryInputFilename);
    //compiler.DeclareNamespace("saxon", "http://saxon.sf.net/");

    string xqueryFileContents = File.ReadAllText(xqueryInputFilename);
    Console.WriteLine("----- Start: XQUERY:");
    Console.WriteLine(xqueryFileContents);
    Console.WriteLine("----- End  : XQUERY:");
    XQueryExecutable exp = compiler.Compile(xqueryFileContents);
    XQueryEvaluator eval = exp.Load();

    Serializer qout = processor.NewSerializer();
    qout.SetOutputProperty(Serializer.METHOD, "xml");
    qout.SetOutputProperty(Serializer.INDENT, "yes");
    qout.SetOutputStream(new FileStream(outFilename,
                 FileMode.Create, FileAccess.Write));

    eval.Run(qout);

}

Also two questions regarding "BaseURI".

1. Should it be a directory name, or can it be same as the Xquery file name?
2. I get this compile error: "Cannot implicity convert to "System.Uri" to "String".

compiler.BaseUri = new Uri(xqueryInputFilename);

It's exactly the same thing I did for XSLT which worked. But it looks like BaseUri is a string for XQuery, but a real Uri object for XSLT?  Any reason for the difference?

Body:
Bottom line solution based on Michael Kay's response; I added this line of code after doing the exp.Load():

eval.ContextItem = indoc;

The indoc object created earlier is what relates to the XML input file to be processed by the XQuery.


问:
MSI Patch Creation Problems
A new version of our product (a software package) has been released recently. To expand functionality, we developed a plugin afterwards. Now we would like to deploy these files (two new files and an updated version of an existing file) as hotfix (or update) with MSI patch (msp). I downloaded a blank PCP file from MSDN website and made some changes in it. The changes involve the following tables:

ImageFamilies

PatchMetadata

PatchSequence

Properties

TargetImages

UpgradedImages

All the other tables remain blank.

Then, I managed to create an msp file with this PCP file based on two versions of the admin image of the software package, both of which were built from Visual Studio setup project (VS 2010). The difference between these two msi packages are that I replaced a file and added two new files in, but nothing else. I didn't change the product code (GUID), the upgrade code (GUID), nor the version number.

Then I was trying to install this msp file on top of the released version.

The first screen appearing is asking to Repair or Remove the product. This is not what we want. We want the installer is like a fresh installation, including showing the licence agreement. How do I define the UI for MSI patch?

During the installation of the patch, I got an error message as below, then the installation failed:

Error 1001. Exception occurred while initializing the installation: System.IO.FileNotFoundException: Could not load file or assembly 'file:///C:\WINDOWS\system32\Files\BPS\TestApp' or one of its dependencies. This system cannot find the file specified.

BPS is the folder where we install our product in [ProgramFilesFolder]. I wondered why MSI was trying to search in "C:\Windows\system32" for files installed in [ProgramFilesFolder]. In addition, the changed files in the hotfix are located in somewhere else ([CommonAppDataFolder]) instead of in this "BPS" folder.

Can anyone help me with these problems? If any more information is needed to identify the issues, please let me know. Any thoughts, advices, suggestions would be very much appreciated.

Dan

答:
The first screen appearing is asking
  to Repair or Remove the product. This
  is not what we want.

In the upgrade package increase the Product Version. This way you will use a minor upgrade instead of a small update.

You can also try using the MSIEXEC command line to apply the patch:

http://msdn.microsoft.com/en-us/library/aa367574(VS.85).aspx

http://msdn.microsoft.com/en-us/library/aa367575(VS.85).aspx

During the installation of the patch,
  I got an error message as below, then
  the installation failed

Is there something in your installer using that file? Perhaps a custom action? Try looking in the log to see what action tries to access that file.

Title: MSI Patch Creation Problems


问:
Cannot open the connection for the driver: org.eclipse.birt.report.data.oda.jdbc. using database postgres
I am working on report using BIRT with postgresql. While I am able to run the report successfully using BIRT viewer, when I try to integrate with tomcat, it gives the below error-

```<code>Cannot open the connection for the driver:
org.eclipse.birt.report.data.oda.jdbc.
org.eclipse.birt.report.data.oda.jdbc.JDBCException: Cannot load JDBC Driver class: org.postgresql.Driver.
</code>```

while I have place the oda.jdbc.driver "postgresql-42.2.5" at location "\WEB-INF\lib" but still I'm facing this error.

I am running:

Birt version:-4.8.0

postgres version:- postgres9.5 (1.22.2)

答:
After viewing error it seems the the JDBC driver jar is on at class path into BIRT runtime so it is not able to load the Driver and throwing error.

Please ensure the Driver jars are placed into libs directory of BIRT runtime installed in your server and it is available into class path at runtime.

Body:
I am working on report using BIRT with postgresql. While I am able to run the report successfully using BIRT viewer, when I try to integrate with tomcat, it gives the below error-

Cannot open the connection for the driver:
org.eclipse.birt.report.data.oda.jdbc.
org.eclipse.birt.report.data.oda.jdbc.JDBCException: Cannot load JDBC Driver class: org.postgresql.Driver.

while I have place the oda.jdbc.driver "postgresql-42.2.5" at location "\WEB-INF\lib" but still I'm facing this error.

I am running:

Birt version:-4.8.0

postgres version:- postgres9.5 (1.22.2)


问:
Stacked numpy arrays
I am considerably new to Python.I am willing to stack a few 1-d arrays in python and create a 2-d array using that. The arrays which I want to stack are returned from another function. The minimum reproducible code that I have written for this purpose  has been shown below:

```<code>def fun1(i): # this function returns the array
  return array # This array is a function of i
h0= np.empty(5,dtype=object)
arrays=[h0]
for i in range(4):
 arr=fun1(i)
 arrays.append(arr)

h=np.vstack(arrays)
print (h)
</code>```

The desired output is of the form :

```<code>[[1 1 1 1 1]
 [2 2 2 2 2]
 [3 3 3 3 3]
 [4 4 4 4 4]]
</code>```

But I get :

```<code>[[None None None None None]
 [1 1 1 1 1]
 [2 2 2 2 2]
 [3 3 3 3 3]
 [4 4 4 4 4]]
</code>```

I understand that I get the above output because an empty array of dtype=object has all elements None . But I am not being able to solve the problem. Any help regarding this would be highly appreciated.

答:
try this

```<code>h = np.vstack([
    fun1(i)
    for i in range(4)
])

print(h)
</code>```

^^ this is assuming that fun1() is some proprietary function returning arrays of same length

but if you want a 2D array with equal rows entries and incrementing column-wise like

```<code>[[1 1 1 1 1]
 [2 2 2 2 2]
 [3 3 3 3 3]
 [4 4 4 4 4]]
</code>```

you can also try a faster method

```<code>x = np.arange(1,5).reshape([-1,1])
h = np.repeat(x, 5, axis= 1)
</code>```

Title: Stacked numpy arrays

Body:
I am considerably new to Python.I am willing to stack a few 1-d arrays in python and create a 2-d array using that. The arrays which I want to stack are returned from another function. The minimum reproducible code that I have written for this purpose  has been shown below:

def fun1(i): # this function returns the array
  return array # This array is a function of i
h0= np.empty(5,dtype=object)
arrays=[h0]
for i in range(4):
 arr=fun1(i)
 arrays.append(arr)

h=np.vstack(arrays)
print (h)

The desired output is of the form :

[[1 1 1 1 1]
 [2 2 2 2 2]
 [3 3 3 3 3]
 [4 4 4 4 4]]

But I get :

[[None None None None None]
 [1 1 1 1 1]
 [2 2 2 2 2]
 [3 3 3 3 3]
 [4 4 4 4 4]]

I understand that I get the above output because an empty array of dtype=object has all elements None . But I am not being able to solve the problem. Any help regarding this would be highly appreciated.

Body:
try this

h = np.vstack([
    fun1(i)
    for i in range(4)
])

print(h)

^^ this is assuming that fun1() is some proprietary function returning arrays of same length

but if you want a 2D array with equal rows entries and incrementing column-wise like

[[1 1 1 1 1]
 [2 2 2 2 2]
 [3 3 3 3 3]
 [4 4 4 4 4]]

you can also try a faster method

x = np.arange(1,5).reshape([-1,1])
h = np.repeat(x, 5, axis= 1)


问:
MERN project routing not working on Heroku
I have created a personal website. It is developed using ReactJs, Express, Node, and MongoDB. It is working fine on my localhost also, Heroku (using react-router-dom) too. But, when I direct hit the URL on Heroku then it is showing error. The homepage is working only.

Here is the URL, https://amper.herokuapp.com/

package.json

```<code>{
  "name": "amper",
  "version": "1.0.0",
  "description": "",
  "main": "server.js",
  "homepage": "https://amper.herokuapp.com",
  "scripts": {
    "dev-client": "PORT=3000 react-scripts start",
    "server": "node server.js",
    "dev-server": "nodemon ./server.js",
    "build": "react-scripts build",
    "test": "react-scripts test",
    "eject": "react-scripts eject",
    "start": "PORT=3000 react-scripts start && node server.js",
    "dev": "concurrently --kill-others \"npm run dev-client\" \"npm run dev-server\""
  },
  "author": "Amper",
  "license": "ISC",
  "dependencies": {
    "@ckeditor/ckeditor5-build-classic": "^19.0.1",
    "@ckeditor/ckeditor5-react": "^2.1.0",
    "@fortawesome/fontawesome-svg-core": "^1.2.28",
    "@fortawesome/free-brands-svg-icons": "^5.13.0",
    "@fortawesome/react-fontawesome": "^0.1.9",
    "@testing-library/jest-dom": "^5.9.0",
    "@testing-library/react": "^10.0.4",
    "@testing-library/user-event": "^10.4.0",
    "axios": "^0.19.2",
    "bcrypt": "^4.0.1",
    "body-parser": "^1.19.0",
    "bootstrap": "^4.5.0",
    "cors": "^2.8.5",
    "dotenv": "^8.2.0",
    "draft-js": "^0.11.5",
    "express": "^4.17.1",
    "jsonwebtoken": "^8.5.1",
    "moment": "^2.26.0",
    "mongoose": "^5.9.16",
    "path": "^0.12.7",
    "react": "^16.13.1",
    "react-bootstrap": "^1.0.1",
    "react-dom": "^16.13.1",
    "react-feather": "^2.0.8",
    "react-helmet": "^6.0.0",
    "react-moment": "^0.9.7",
    "react-router-dom": "^5.2.0",
    "react-scripts": "^3.4.1",
    "react-select": "^3.1.0",
    "serve-static": "^1.14.1"
  },
  "engines": {
    "node": "12.16.3"
  },
  "browserslist": {
    "production": [
      ">0.2%",
      "not dead",
      "not op_mini all"
    ],
    "development": [
      "last 1 chrome version",
      "last 1 firefox version",
      "last 1 safari version"
    ]
  },
  "devDependencies": {
    "concurrently": "^5.2.0",
    "node-sass": "^4.14.1",
    "nodemon": "^2.0.4"
  }
}
</code>```

server.js

```<code>const express = require('express');
const mongoose = require('mongoose');
const bodyparser = require('body-parser');
const cors = require('cors');
const path = require('path');
const serveStatic = require('serve-static');
require('dotenv').config();

const routes = require('./server/routes');

const app = express();
const port = process.env.PORT;

// mongo connection
mongoose.Promise = global.Promise;
mongoose.connect(process.env.MONGO_URI, { useNewUrlParser: true, useUnifiedTopology: true })
  .then(() => console.log('Database Connected'))
  .catch((err) => console.log(err));

app.use(serveStatic(path.join(__dirname, 'build')));

// bodyparser setup
app.use(bodyparser.urlencoded({ extended: true }));
app.use(bodyparser.json());

// cors setup
app.use(cors());

routes(app);

app.listen(port, () => console.log(`App is running on port ${port}`));
</code>```

Project folder structure

```<code>amper
|_ node_modules
|_ public
   |_ favicon.ico
   |_ index.html
   |_ manifest.json
   |_ robots.txt
|_ server
   |_ controllers
   |_ middleware
   |_ models
   |_ routes
|_ src
   |_ assets
   |_ components
   |_ App.js
   |_ index.js
   |_ serviceWorker.js
   |_ setupTests.js
|_ .env
|_ .gitignore
|_ package-lock.json
|_ package.json
|_ README.md
|_ server.js
</code>```

答:
serve-static package serve the build folder, however this is not quite enough if you use client-side routing.

Add the following code after all your routes

```<code>routes(app);
app.get('/*', function(req, res) {
    res.sendFile(path.join(__dirname, 'build', 'index.html'));
});
</code>```

Body:
I have created a personal website. It is developed using ReactJs, Express, Node, and MongoDB. It is working fine on my localhost also, Heroku (using react-router-dom) too. But, when I direct hit the URL on Heroku then it is showing error. The homepage is working only.

Here is the URL, https://amper.herokuapp.com/

package.json

{
  "name": "amper",
  "version": "1.0.0",
  "description": "",
  "main": "server.js",
  "homepage": "https://amper.herokuapp.com",
  "scripts": {
    "dev-client": "PORT=3000 react-scripts start",
    "server": "node server.js",
    "dev-server": "nodemon ./server.js",
    "build": "react-scripts build",
    "test": "react-scripts test",
    "eject": "react-scripts eject",
    "start": "PORT=3000 react-scripts start && node server.js",
    "dev": "concurrently --kill-others \"npm run dev-client\" \"npm run dev-server\""
  },
  "author": "Amper",
  "license": "ISC",
  "dependencies": {
    "@ckeditor/ckeditor5-build-classic": "^19.0.1",
    "@ckeditor/ckeditor5-react": "^2.1.0",
    "@fortawesome/fontawesome-svg-core": "^1.2.28",
    "@fortawesome/free-brands-svg-icons": "^5.13.0",
    "@fortawesome/react-fontawesome": "^0.1.9",
    "@testing-library/jest-dom": "^5.9.0",
    "@testing-library/react": "^10.0.4",
    "@testing-library/user-event": "^10.4.0",
    "axios": "^0.19.2",
    "bcrypt": "^4.0.1",
    "body-parser": "^1.19.0",
    "bootstrap": "^4.5.0",
    "cors": "^2.8.5",
    "dotenv": "^8.2.0",
    "draft-js": "^0.11.5",
    "express": "^4.17.1",
    "jsonwebtoken": "^8.5.1",
    "moment": "^2.26.0",
    "mongoose": "^5.9.16",
    "path": "^0.12.7",
    "react": "^16.13.1",
    "react-bootstrap": "^1.0.1",
    "react-dom": "^16.13.1",
    "react-feather": "^2.0.8",
    "react-helmet": "^6.0.0",
    "react-moment": "^0.9.7",
    "react-router-dom": "^5.2.0",
    "react-scripts": "^3.4.1",
    "react-select": "^3.1.0",
    "serve-static": "^1.14.1"
  },
  "engines": {
    "node": "12.16.3"
  },
  "browserslist": {
    "production": [
      ">0.2%",
      "not dead",
      "not op_mini all"
    ],
    "development": [
      "last 1 chrome version",
      "last 1 firefox version",
      "last 1 safari version"
    ]
  },
  "devDependencies": {
    "concurrently": "^5.2.0",
    "node-sass": "^4.14.1",
    "nodemon": "^2.0.4"
  }
}

server.js

const express = require('express');
const mongoose = require('mongoose');
const bodyparser = require('body-parser');
const cors = require('cors');
const path = require('path');
const serveStatic = require('serve-static');
require('dotenv').config();

const routes = require('./server/routes');

const app = express();
const port = process.env.PORT;

// mongo connection
mongoose.Promise = global.Promise;
mongoose.connect(process.env.MONGO_URI, { useNewUrlParser: true, useUnifiedTopology: true })
  .then(() => console.log('Database Connected'))
  .catch((err) => console.log(err));

app.use(serveStatic(path.join(__dirname, 'build')));

// bodyparser setup
app.use(bodyparser.urlencoded({ extended: true }));
app.use(bodyparser.json());

// cors setup
app.use(cors());

routes(app);

app.listen(port, () => console.log(`App is running on port ${port}`));

Project folder structure

amper
|_ node_modules
|_ public
   |_ favicon.ico
   |_ index.html
   |_ manifest.json
   |_ robots.txt
|_ server
   |_ controllers
   |_ middleware
   |_ models
   |_ routes
|_ src
   |_ assets
   |_ components
   |_ App.js
   |_ index.js
   |_ serviceWorker.js
   |_ setupTests.js
|_ .env
|_ .gitignore
|_ package-lock.json
|_ package.json
|_ README.md
|_ server.js

Body:
serve-static package serve the build folder, however this is not quite enough if you use client-side routing.

Add the following code after all your routes

routes(app);
app.get('/*', function(req, res) {
    res.sendFile(path.join(__dirname, 'build', 'index.html'));
});


问:
how to apply map function to the tf.Tensor
```<code>dataset = tf.data.Dataset.from_tensor_slices((images,boxes))
function_to_map = lambda x,y: func3(x,y)
fast_benchmark(dataset.map(function_to_map).batch(1).prefetch(tf.data.experimental.AUTOTUNE))
</code>```

Now I here is the func3

```<code>def fast_benchmark(dataset, num_epochs=2):
    start_time = time.perf_counter()
    print('dataset->',dataset)
    for _ in tf.data.Dataset.range(num_epochs):
        for _,__ in dataset:
            print(_,__)
            break
            pass
</code>```

the ooutput of print is

```<code>tf.Tensor([b'/media/jake/mark-4tb3/input/datasets/pascal/VOCtrainval_11-May-2012/VOCdevkit/VOC2012/JPEGImages/2008_000008.jpg'], shape=(1,), dtype=string) <tf.RaggedTensor [[[52, 86, 470, 419], [157, 43, 288, 166]]]>
</code>```

what I want to do in func3()

want to change image directory to the real image  and run the batch

答:
You need to extract string form the tensor and use the appropriate image reading function. Below are the steps to be implemented in the code to achieve this.

You have to decorate the map function with tf.py_function(get_path, [x], [tf.float32]). You can find more about tf.py_function here. In tf.py_function, first argument is the name of map function, second argument is the element to be passed to map function and final argument is the return type.

You can get your string part by using bytes.decode(file_path.numpy()) in map function.

Use appropriate function to load your image. We are using load_img.

In the below simple program, we are using tf.data.Dataset.list_files to read path of the image. Next in the map function we are reading the image using load_img and later doing the tf.image.central_crop function to crop central part of the image.

Code -

```<code>%tensorflow_version 2.x
import tensorflow as tf
from keras.preprocessing.image import load_img
from keras.preprocessing.image import img_to_array, array_to_img
from matplotlib import pyplot as plt
import numpy as np

def load_file_and_process(path):
    image = load_img(bytes.decode(path.numpy()), target_size=(224, 224))
    image = img_to_array(image)
    image = tf.image.central_crop(image, np.random.uniform(0.50, 1.00))
    return image

train_dataset = tf.data.Dataset.list_files('/content/bird.jpg')
train_dataset = train_dataset.map(lambda x: tf.py_function(load_file_and_process, [x], [tf.float32]))

for f in train_dataset:
  for l in f:
    image = np.array(array_to_img(l))
    plt.imshow(image)
</code>```

Output -

Hope this answers your question. Happy Learning.

Body:
dataset = tf.data.Dataset.from_tensor_slices((images,boxes))
function_to_map = lambda x,y: func3(x,y)
fast_benchmark(dataset.map(function_to_map).batch(1).prefetch(tf.data.experimental.AUTOTUNE))

Now I here is the func3

def fast_benchmark(dataset, num_epochs=2):
    start_time = time.perf_counter()
    print('dataset->',dataset)
    for _ in tf.data.Dataset.range(num_epochs):
        for _,__ in dataset:
            print(_,__)
            break
            pass

the ooutput of print is

tf.Tensor([b'/media/jake/mark-4tb3/input/datasets/pascal/VOCtrainval_11-May-2012/VOCdevkit/VOC2012/JPEGImages/2008_000008.jpg'], shape=(1,), dtype=string) <tf.RaggedTensor [[[52, 86, 470, 419], [157, 43, 288, 166]]]>

what I want to do in func3()

want to change image directory to the real image  and run the batch

Body:
You need to extract string form the tensor and use the appropriate image reading function. Below are the steps to be implemented in the code to achieve this.

You have to decorate the map function with tf.py_function(get_path, [x], [tf.float32]). You can find more about tf.py_function here. In tf.py_function, first argument is the name of map function, second argument is the element to be passed to map function and final argument is the return type.

You can get your string part by using bytes.decode(file_path.numpy()) in map function.

Use appropriate function to load your image. We are using load_img.

In the below simple program, we are using tf.data.Dataset.list_files to read path of the image. Next in the map function we are reading the image using load_img and later doing the tf.image.central_crop function to crop central part of the image.

Code -

%tensorflow_version 2.x
import tensorflow as tf
from keras.preprocessing.image import load_img
from keras.preprocessing.image import img_to_array, array_to_img
from matplotlib import pyplot as plt
import numpy as np

def load_file_and_process(path):
    image = load_img(bytes.decode(path.numpy()), target_size=(224, 224))
    image = img_to_array(image)
    image = tf.image.central_crop(image, np.random.uniform(0.50, 1.00))
    return image

train_dataset = tf.data.Dataset.list_files('/content/bird.jpg')
train_dataset = train_dataset.map(lambda x: tf.py_function(load_file_and_process, [x], [tf.float32]))

for f in train_dataset:
  for l in f:
    image = np.array(array_to_img(l))
    plt.imshow(image)

Output -

Hope this answers your question. Happy Learning.


问:
How to dynamical create a file with git info and include it in the the image and save it on build system
We have several developers working on a project.  The areas we are concerned about (and we regularly modify) are kernel, our custom code, and the yocto space itself.

We'd like to create a file at some point in the process (do_fetch, or do_install?) that contains info about what's being built.  Such as the git branch name and hash for each of the repos above.  We would then install that file (or files if need be) onto the image as well as archive it away on a centralized server.

I know that some of this info is available in the buildhistory, but I'm not sure if it is there when we'd like to install and package.

Getting the branch and hash should be easy to get via shell commands in the recipe functions.

Before I go off and hack something out, I thought I'd ask if there is a standard way to do something similar to this.

Thanks!

答:
OK, Here is what I did.

Added appends to the do_install functions I wanted to keep track of and put them in the top of the build dir:

```<code>do_install_append () {
 echo ${SRCPV} > ${TOPDIR}/kernel_manifest.txt
 git rev-parse --abbrev-ref HEAD >> ${TOPDIR}/kernel_manifest.txt
}
</code>```

Added a new bbclass in our meta- dir:

```<code>DEPENDS += "git-native"

do_rootfs_save_manifests[nostamp] = "1"
do_rootfs_save_manifests() {

    date  > ${TOPDIR}/buildinfo.txt
    hostname >> ${TOPDIR}/buildinfo.txt
    git config user.name >> ${TOPDIR}/buildinfo.txt
    cp ${TOPDIR}/buildinfo.txt ${IMAGE_ROOTFS}/usr/custom_space/

    if [ ! -f ${TOPDIR}/kernel_manifest.txt ]; then
       echo "kernel_manifest empty:  Rebuild or run cleanall on it's recipe" >    ${TOPDIR}/error_kernel_manifest.txt
       cp  ${TOPDIR}/error_kernel_manifest.txt ${IMAGE_ROOTFS}/usr/custom_space/
    else
       cp  ${TOPDIR}/kernel_manifest.txt ${IMAGE_ROOTFS}/usr/custom_space/
       if [ -f ${TOPDIR}/error_kernel_manifest.txt ]; then
           rm ${TOPDIR}/error_kernel_manifest.txt
       fi

    fi

    if [ ! -f ${TOPDIR}/buildhistory/metadata-revs ]; then
       echo " metadata_revs empty:  Make sure INHERIT += \"buildhistory\" and" > ${TOPDIR}/error_yocto_manifest.txt
       echo " BUILDHISTORY_COMMIT = "1" are in your local.conf " >> ${TOPDIR}/error_yocto_manifest.txt
       cp  ${TOPDIR}/error_yocto_manifest.txt ${IMAGE_ROOTFS}/usr/custom_space/

    else
       if [ -f ${TOPDIR}/error_yocto_manifest.txt ]; then
           rm ${TOPDIR}/error_yocto_manifest.txt
       fi
       cp  ${TOPDIR}/buildhistory/metadata-revs ${TOPDIR}/yocto_manifest.txt
       cp  ${TOPDIR}/buildhistory/metadata-revs ${IMAGE_ROOTFS}/usr/custom_space/yocto_manifest.txt
    fi

}

ROOTFS_POSTPROCESS_COMMAND += "do_rootfs_save_manifests;"
</code>```

Added the following lines to the image recipes that we wanted to use the process:

```<code>IMAGE_CLASSES += "manifest"
inherit ${IMAGE_CLASSES}
</code>```

Thanks for the help!

Body:
OK, Here is what I did.

Added appends to the do_install functions I wanted to keep track of and put them in the top of the build dir:

do_install_append () {
 echo ${SRCPV} > ${TOPDIR}/kernel_manifest.txt
 git rev-parse --abbrev-ref HEAD >> ${TOPDIR}/kernel_manifest.txt
}

Added a new bbclass in our meta- dir:

DEPENDS += "git-native"

do_rootfs_save_manifests[nostamp] = "1"
do_rootfs_save_manifests() {

    date  > ${TOPDIR}/buildinfo.txt
    hostname >> ${TOPDIR}/buildinfo.txt
    git config user.name >> ${TOPDIR}/buildinfo.txt
    cp ${TOPDIR}/buildinfo.txt ${IMAGE_ROOTFS}/usr/custom_space/

    if [ ! -f ${TOPDIR}/kernel_manifest.txt ]; then
       echo "kernel_manifest empty:  Rebuild or run cleanall on it's recipe" >    ${TOPDIR}/error_kernel_manifest.txt
       cp  ${TOPDIR}/error_kernel_manifest.txt ${IMAGE_ROOTFS}/usr/custom_space/
    else
       cp  ${TOPDIR}/kernel_manifest.txt ${IMAGE_ROOTFS}/usr/custom_space/
       if [ -f ${TOPDIR}/error_kernel_manifest.txt ]; then
           rm ${TOPDIR}/error_kernel_manifest.txt
       fi

    fi

    if [ ! -f ${TOPDIR}/buildhistory/metadata-revs ]; then
       echo " metadata_revs empty:  Make sure INHERIT += \"buildhistory\" and" > ${TOPDIR}/error_yocto_manifest.txt
       echo " BUILDHISTORY_COMMIT = "1" are in your local.conf " >> ${TOPDIR}/error_yocto_manifest.txt
       cp  ${TOPDIR}/error_yocto_manifest.txt ${IMAGE_ROOTFS}/usr/custom_space/

    else
       if [ -f ${TOPDIR}/error_yocto_manifest.txt ]; then
           rm ${TOPDIR}/error_yocto_manifest.txt
       fi
       cp  ${TOPDIR}/buildhistory/metadata-revs ${TOPDIR}/yocto_manifest.txt
       cp  ${TOPDIR}/buildhistory/metadata-revs ${IMAGE_ROOTFS}/usr/custom_space/yocto_manifest.txt
    fi

}

ROOTFS_POSTPROCESS_COMMAND += "do_rootfs_save_manifests;"

Added the following lines to the image recipes that we wanted to use the process:

IMAGE_CLASSES += "manifest"
inherit ${IMAGE_CLASSES}

Thanks for the help!


问:
Why can't the subs function of the sympy replace the value of the symbol sometimes？
I have the following code：

```<code>u_ini = 0.1
v_ini = 0.1
z_ini = 0.1  # 初始化三个拉格朗日乘子

q = 0

lis = list(range(2))
u = list(sp.symbols('u:{}'.format(len(lis))))
v = list(sp.symbols('v:{}'.format(len(lis))))
z = sp.symbols('z')
p = list(sp.symbols('p:{}'.format(len(lis))))

lag1 = 0
lag2 = 0
lag3 = 0

p_symbol_sum = np.sum(p)

for i in range(k):
    if i < k-1:
        lag1 += B*ts_ratio[i]*sp.log(1+g[i]*p[i]/(sgm_2+g[i]*np.sum(p[i+1:k])),2)-q*(af_eff*p[i]+Pc-eh_eff*(1-ts_ratio[i])*g[i]*p_symbol_sum)
        lag2 -= u[i] * (R_min - ts_ratio[i] * B * sp.log(1 + g[i] * p[i] / (sgm_2 + g[i] * np.sum(p[i + 1:k])),2))
    elif i == k-1:
        lag1 += B*ts_ratio[i]*sp.log(1+g[i]*p[i]/(sgm_2+g[i]*p[i]),2)-q*(af_eff*p[i]+Pc-eh_eff*(1-ts_ratio[i])*g[i]*p_symbol_sum)
        lag2 -= u[i] * (R_min - ts_ratio[i] * B * sp.log(1+g[i]*p[i]/(sgm_2+g[i]*p[i]),2))
    lag3 -= v[i] * (E_min - (1 - ts_ratio[i])*eh_eff*g[i]*p_symbol_sum) + z * (p[i] - p_max)
lag_fun = lag1 + lag2 + lag3
print("lag_fun:",lag_fun)

for i in range(k):
    lag_fun.subs([(u[i],u_ini), (v[i],v_ini), (z,z_ini), (p[i],p_ini)]).evalf()
print("lag_fun:",lag_fun)
</code>```

Why does the value of the expression not change after I count down the subs of the second line。
This is the output of the program. The first line is the output before using subs. The second is the output after using subs. Why hasn't it changed?

```<code>lag_fun: -u0*(-0.5*log(0.0410609879149758*p0/(0.0410609879149758*p1 + 0.001) + 1)/log(2) + 2) - u1*(-0.5*log(0.0123909311217172*p1/(0.0123909311217172*p1 + 0.001) + 1)/log(2) + 2) - v0*(-0.00205304939574879*p0 - 0.00205304939574879*p1 + 0.2) - v1*(-0.000619546556085859*p0 - 0.000619546556085859*p1 + 0.2) - z*(p0 - 20) - z*(p1 - 20) + 0.5*log(0.0410609879149758*p0/(0.0410609879149758*p1 + 0.001) + 1)/log(2) + 0.5*log(0.0123909311217172*p1/(0.0123909311217172*p1 + 0.001) + 1)/log(2)
lag_fun: -u0*(-0.5*log(0.0410609879149758*p0/(0.0410609879149758*p1 + 0.001) + 1)/log(2) + 2) - u1*(-0.5*log(0.0123909311217172*p1/(0.0123909311217172*p1 + 0.001) + 1)/log(2) + 2) - v0*(-0.00205304939574879*p0 - 0.00205304939574879*p1 + 0.2) - v1*(-0.000619546556085859*p0 - 0.000619546556085859*p1 + 0.2) - z*(p0 - 20) - z*(p1 - 20) + 0.5*log(0.0410609879149758*p0/(0.0410609879149758*p1 + 0.001) + 1)/log(2) + 0.5*log(0.0123909311217172*p1/(0.0123909311217172*p1 + 0.001) + 1)/log(2)
</code>```

答:
subs doesn't change anything in place, you have to capture the result for the same reason that this loop fails to change x:

```<code>>>> x = 0
>>> for i in range(10): x + 1
>>> x
0
</code>```

So it must be

```<code>lag_fun = lag_fun.subs(etc...)
</code>```

Body:
I have the following code：

u_ini = 0.1
v_ini = 0.1
z_ini = 0.1  # 初始化三个拉格朗日乘子

q = 0

lis = list(range(2))
u = list(sp.symbols('u:{}'.format(len(lis))))
v = list(sp.symbols('v:{}'.format(len(lis))))
z = sp.symbols('z')
p = list(sp.symbols('p:{}'.format(len(lis))))

lag1 = 0
lag2 = 0
lag3 = 0

p_symbol_sum = np.sum(p)

for i in range(k):
    if i < k-1:
        lag1 += B*ts_ratio[i]*sp.log(1+g[i]*p[i]/(sgm_2+g[i]*np.sum(p[i+1:k])),2)-q*(af_eff*p[i]+Pc-eh_eff*(1-ts_ratio[i])*g[i]*p_symbol_sum)
        lag2 -= u[i] * (R_min - ts_ratio[i] * B * sp.log(1 + g[i] * p[i] / (sgm_2 + g[i] * np.sum(p[i + 1:k])),2))
    elif i == k-1:
        lag1 += B*ts_ratio[i]*sp.log(1+g[i]*p[i]/(sgm_2+g[i]*p[i]),2)-q*(af_eff*p[i]+Pc-eh_eff*(1-ts_ratio[i])*g[i]*p_symbol_sum)
        lag2 -= u[i] * (R_min - ts_ratio[i] * B * sp.log(1+g[i]*p[i]/(sgm_2+g[i]*p[i]),2))
    lag3 -= v[i] * (E_min - (1 - ts_ratio[i])*eh_eff*g[i]*p_symbol_sum) + z * (p[i] - p_max)
lag_fun = lag1 + lag2 + lag3
print("lag_fun:",lag_fun)

for i in range(k):
    lag_fun.subs([(u[i],u_ini), (v[i],v_ini), (z,z_ini), (p[i],p_ini)]).evalf()
print("lag_fun:",lag_fun)

Why does the value of the expression not change after I count down the subs of the second line。
This is the output of the program. The first line is the output before using subs. The second is the output after using subs. Why hasn't it changed?

lag_fun: -u0*(-0.5*log(0.0410609879149758*p0/(0.0410609879149758*p1 + 0.001) + 1)/log(2) + 2) - u1*(-0.5*log(0.0123909311217172*p1/(0.0123909311217172*p1 + 0.001) + 1)/log(2) + 2) - v0*(-0.00205304939574879*p0 - 0.00205304939574879*p1 + 0.2) - v1*(-0.000619546556085859*p0 - 0.000619546556085859*p1 + 0.2) - z*(p0 - 20) - z*(p1 - 20) + 0.5*log(0.0410609879149758*p0/(0.0410609879149758*p1 + 0.001) + 1)/log(2) + 0.5*log(0.0123909311217172*p1/(0.0123909311217172*p1 + 0.001) + 1)/log(2)
lag_fun: -u0*(-0.5*log(0.0410609879149758*p0/(0.0410609879149758*p1 + 0.001) + 1)/log(2) + 2) - u1*(-0.5*log(0.0123909311217172*p1/(0.0123909311217172*p1 + 0.001) + 1)/log(2) + 2) - v0*(-0.00205304939574879*p0 - 0.00205304939574879*p1 + 0.2) - v1*(-0.000619546556085859*p0 - 0.000619546556085859*p1 + 0.2) - z*(p0 - 20) - z*(p1 - 20) + 0.5*log(0.0410609879149758*p0/(0.0410609879149758*p1 + 0.001) + 1)/log(2) + 0.5*log(0.0123909311217172*p1/(0.0123909311217172*p1 + 0.001) + 1)/log(2)

Body:
subs doesn't change anything in place, you have to capture the result for the same reason that this loop fails to change x:

>>> x = 0
>>> for i in range(10): x + 1
>>> x
0

So it must be

lag_fun = lag_fun.subs(etc...)


问:
Visual Studio 2010: Keyboard Shortcut to "Override Method" in C#?
In Visual Studio 2010, what is the keyboard shortcut to drop-down a list of C# virtual methods, and clicking them will generate an "override method" code?

In IntelliJ IDEA, that feature's shortcut is CTRL+Shift+O.

答:
Generally intellisense will automatically list after you've typed (or used intellisense to complete) override.

Typing a space after the "e" of override will get the list again.


问:
What is the struct (binary format) of float datatype in C?
How can I find information about float datatype in C? I mean the bit struct for this type (decimal, signal indicator, etc...)?
Let me explain what I'm trying to do:

I am implementing an network protocol and I need to send 6 octects with Latitude and Longitude (according to protocol documentation). First 3 octects must have LAT information and last 3 must have LON information.
I can't use bitwise operators in float datatype, so for debug, I'm copying memory of float variable to a new uint32_t variable (both 4-bytes wide) and then, trying to shift bit's to get the correct value, but it's not working.

This is the code that I'm using to test/debug conversion:

```<code>    int32_t b = 0;
    memcpy(&b,&a,4);
    int32_t c = (b >> 23);
    printf("Valor de C: 0x%X, Decimal: %d\n",c,c);
// Should print only '23', but it's printing
// Valor de C: 0x41B, Decimal: 1051
</code>```

After 'knowing' the correct bit-position of float, I'll copy those bit's to my protocol data, which is an array of unsigned char[6] (this I can't change the type, only values).

Any tip's about how to accomplish this?

答:
Usually for such purposes bit fields are used. You can try something like this:

```<code>#pragma pack(1)
typedef struct {
    union latitude{
        uint32_t value : 24;
        struct octets{
            uint8_t octetOne : 8;
            uint8_t octetTwo : 8;
            uint8_t octetThree : 8;
        }
    }
    union longitude{
        uint32_t value : 24;
        struct octets{
            uint8_t octetOne : 8;
            uint8_t octetTwo : 8;
            uint8_t octetThree : 8;
        }
    }
} frame;
</code>```

Then store incomming data in this struct and access desired values by:
frame.longitude.value etc.

Body:
How can I find information about float datatype in C? I mean the bit struct for this type (decimal, signal indicator, etc...)?
Let me explain what I'm trying to do:

I am implementing an network protocol and I need to send 6 octects with Latitude and Longitude (according to protocol documentation). First 3 octects must have LAT information and last 3 must have LON information.
I can't use bitwise operators in float datatype, so for debug, I'm copying memory of float variable to a new uint32_t variable (both 4-bytes wide) and then, trying to shift bit's to get the correct value, but it's not working.

This is the code that I'm using to test/debug conversion:

    int32_t b = 0;
    memcpy(&b,&a,4);
    int32_t c = (b >> 23);
    printf("Valor de C: 0x%X, Decimal: %d\n",c,c);
// Should print only '23', but it's printing
// Valor de C: 0x41B, Decimal: 1051

After 'knowing' the correct bit-position of float, I'll copy those bit's to my protocol data, which is an array of unsigned char[6] (this I can't change the type, only values).

Any tip's about how to accomplish this?

Body:
Usually for such purposes bit fields are used. You can try something like this:

#pragma pack(1)
typedef struct {
    union latitude{
        uint32_t value : 24;
        struct octets{
            uint8_t octetOne : 8;
            uint8_t octetTwo : 8;
            uint8_t octetThree : 8;
        }
    }
    union longitude{
        uint32_t value : 24;
        struct octets{
            uint8_t octetOne : 8;
            uint8_t octetTwo : 8;
            uint8_t octetThree : 8;
        }
    }
} frame;

Then store incomming data in this struct and access desired values by:
frame.longitude.value etc.