问:
Variable lengths differ - fligner.test
I have the folloing a dataset like follows:

```<code>attack defense sp_attack sp_defense speed is_legendary
 60      62      63      80          60         0
 80      100    123      122         120        0
 39      52      43      60          65         0
 58      64      58      80          80         0
 90      90      85      125         90         1
100      90      125     85          90         1
106      150     70      194         120        1
100      100    100      100         100        1
90       85      75      115         100        1
</code>```

From this dataset, I want to check if there is heteroscedasticity between two groups: Legendary vs. Non legendary pokemons. To do that, first I checked the normality of the data for the legendary and non legendary pokémon as follows:

```<code># Shapiro-test for legendary and non legendari pokemon, hp comparison.
shapiro.test(df_net$hp[df_net$is_legendary==0])
shapiro.test(df_net$hp[df_net$is_legendary==1])
</code>```

I´ve seen that in both cases the result is not distributed normally. Now, I´ve decided to carry out a Fligner test as follows:

```<code>fligner.test(hp[df_net$is_legendary==0] ~ hp[df_net$is_legendary==1], data = df_net)
</code>```

However, I obtain the following error:

```<code>Error in model.frame.default(formula = hp[df_net$is_legendary == 0] ~ : variable lengths differ (found for 'hp[df_net$is_legendary == 1]')
</code>```

I guess that this is due to the number of observations of pokemon legendary different from non legendary but then how can I check the heteroscedasticity between this two groups?

答:
The correct syntax for fligner.test is

```<code>fligner.test(x ~ group, data)
</code>```

In your case the correct syntax would be (e.g for variable sp_defense)

```<code>fligner.test(sp_defense ~ is_legendary, data=df_net)
</code>```

Title: Variable lengths differ - fligner.test

Body:
I have the folloing a dataset like follows:

attack defense sp_attack sp_defense speed is_legendary
 60      62      63      80          60         0
 80      100    123      122         120        0
 39      52      43      60          65         0
 58      64      58      80          80         0
 90      90      85      125         90         1
100      90      125     85          90         1
106      150     70      194         120        1
100      100    100      100         100        1
90       85      75      115         100        1

From this dataset, I want to check if there is heteroscedasticity between two groups: Legendary vs. Non legendary pokemons. To do that, first I checked the normality of the data for the legendary and non legendary pokémon as follows:

# Shapiro-test for legendary and non legendari pokemon, hp comparison.
shapiro.test(df_net$hp[df_net$is_legendary==0])
shapiro.test(df_net$hp[df_net$is_legendary==1])

I´ve seen that in both cases the result is not distributed normally. Now, I´ve decided to carry out a Fligner test as follows:

fligner.test(hp[df_net$is_legendary==0] ~ hp[df_net$is_legendary==1], data = df_net)

However, I obtain the following error:

Error in model.frame.default(formula = hp[df_net$is_legendary == 0] ~ : variable lengths differ (found for 'hp[df_net$is_legendary == 1]')

I guess that this is due to the number of observations of pokemon legendary different from non legendary but then how can I check the heteroscedasticity between this two groups?

Body:
The correct syntax for fligner.test is

fligner.test(x ~ group, data)

In your case the correct syntax would be (e.g for variable sp_defense)

fligner.test(sp_defense ~ is_legendary, data=df_net)


来源: stackexchange

问:
Including a CDATA field in a Service Connector
An API I am communicating with is Soap based and requires XML with inner XML (CDATA) in the request.

For the service connector action test I have hard-coded the inner xml with this format:

```<code><![CDATA[
<Application xmlns:xsd="http://www.w3.org/2001/XMLSchema"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" ApplicationCrossReferenceId="123">
...
...
</Application>    ]]>
</code>```

where the dots indicate the data contained.
When running the test the request payload has been transformed to the html entity for < which is $lt; - as seen below :

Is there a way to avoid this?

答:
This is a bug in Informatica. the other characters are decoded back to their original correctly, as described in KB 512858, &gt and &lt however are not decoded.

A bug report has been raised 29.05.2020.

Edit: Further investigation revealed that using CDATA was not necessary in my case, instead I was able to use the following input for the body binding:

```<code><Application xmlns:xsd="http://www.w3.org/2001/XMLSchema"
      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" ApplicationCrossReferenceId="123">
    ...
    ...
</Application>
</code>```

ContentLicense: CC BY-SA 4.0

Body:
An API I am communicating with is Soap based and requires XML with inner XML (CDATA) in the request.

For the service connector action test I have hard-coded the inner xml with this format:

<![CDATA[
<Application xmlns:xsd="http://www.w3.org/2001/XMLSchema"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" ApplicationCrossReferenceId="123">
...
...
</Application>    ]]>

where the dots indicate the data contained.
When running the test the request payload has been transformed to the html entity for < which is $lt; - as seen below :

Is there a way to avoid this?

Body:
This is a bug in Informatica. the other characters are decoded back to their original correctly, as described in KB 512858, &gt and &lt however are not decoded.

A bug report has been raised 29.05.2020.

Edit: Further investigation revealed that using CDATA was not necessary in my case, instead I was able to use the following input for the body binding:

<Application xmlns:xsd="http://www.w3.org/2001/XMLSchema"
      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" ApplicationCrossReferenceId="123">
    ...
    ...
</Application>


问:
Need a Regular expresssion that should not allow only space in string, It can allow spaces along with characters
Need a Regular expresssion that should not allow  only space  in string, It can allow spaces along  with characters.

e.g: space+char+space  is  allowed  where  as  only  space  is not allowed

答:
If you're just looking for a positive match:

```<code>/\S/
</code>```

If you want to capture:

```<code>/(.*\S.*)/
</code>```

EDIT:

Actually, if you meant a literal space:

```<code>/[ ]/
</code>```

ContentLicense: CC BY-SA 3.0

Body:
If you're just looking for a positive match:

/\S/

If you want to capture:

/(.*\S.*)/

EDIT:

Actually, if you meant a literal space:

/[ ]/


问:
improve performance for postgres
I count the number of users in this way, it runs for 5 seconds to produce results, I am looking for a better solution</p>

```<code>SELECT COUNT(*)
FROM (SELECT user_id
      FROM slot_result_primary
      WHERE session_timestamp BETWEEN 1590598800000 AND 1590685199999
      GROUP BY user_id) AS foo
</code>```

答:
First of all you can simplify the query:

```<code>SELECT COUNT(DISTINCT user_id)
FROM slot_result_primary
WHERE session_timestamp BETWEEN 1590598800000 AND 1590685199999
</code>```

Most importantly - make sure you have an index on sesion_timestamp

Title: improve performance for postgres

Body:
I count the number of users in this way, it runs for 5 seconds to produce results, I am looking for a better solution

SELECT COUNT(*)
FROM (SELECT user_id
      FROM slot_result_primary
      WHERE session_timestamp BETWEEN 1590598800000 AND 1590685199999
      GROUP BY user_id) AS foo

Body:
First of all you can simplify the query:

SELECT COUNT(DISTINCT user_id)
FROM slot_result_primary
WHERE session_timestamp BETWEEN 1590598800000 AND 1590685199999

Most importantly - make sure you have an index on sesion_timestamp


问:
How to specify dtype for pd.read_csv when there are no column headers?
I am currently writing code to analyse a large subset of data. I have used the pandas to read the text files and I am printing it using data.head(). I need to specify the dtype for 9 columns (the ninth one being null) because the process would be too memory intensive otherwise but I have no clue how to specify the dtype for columns lacking column headers. Would it be the same as for specifying dtype for column headers? For reference my columns data type would probably be the follows:

Column 1: Mixed as it contains alphanumeric characters

Column 2: Date in the format YY/MM/DD

Column 3: Time in Hours/Minutes/Seconds/Milliseconds

Column 4: Str

Column 5: Time

Column 6: Str

Column 7: Time

Column 8: Time

Column 9: Null

Here is an excerpt of the text file

Here is also an excerpt of my code

```<code>    import sys
    import os
    import glob
    import pandas as pd
    import numpy as np

    path = '/Users/MysteriousHo-Oh1231/Downloads/Datapoints1/*.txt'
    dataframes = []
    for filename in glob.iglob(path):
      data = pd.read_csv(filename, header=None, delimiter='\t',  dtype={0: object, 1: int, 2: int, 3: object, 4: int, 5: object, 6: int, 7: int, 8: None})
      print(data.head())
</code>```

I tried the above code and it returned this error:

Please help me with this!

答:
Define 3 following conversion functions:

```<code>def strToDate(tt):
    return pd.to_datetime(tt, yearfirst=True)

def strToTime(tt):
    return pd.to_datetime(tt, format='%I:%M:%S.%f').time()

def strToTime2(tt):
    return pd.Timestamp(float(tt), unit='s').time()
</code>```

Then read your DataFrame, passing them as converters for the columns
requiring "specialized" conversion:

```<code>df = pd.read_csv('Input.csv', header=None, converters={ 1: strToDate,
    2: strToTime, 4: strToTime2, 6: strToTime2, 7: strToTime2 })
</code>```

When you print df.info(), then:

column 1 (date) is of datetime64[ns] type,

column 8 (NaNs) is of float64 type,

all other columns are of object type.

But don't be misguided. In Pandas the type of object means actually
"something other than a number or datetime".

When you retrieve individual values, e.g. df.iloc[0,2] you
will get: datetime.time(11, 24, 31, 758000), similar for any cell
from column 4, 6 or 7, so they are of just the required type.

Another solution based on Timedelta

Define converter functions as:

```<code>def strToDate(tt):
    return pd.to_datetime(tt, yearfirst=True)

def strToTimeDelta(tt):
    return pd.Timedelta(float(tt), unit='S')
</code>```

Read your dataframe:

```<code>df = pd.read_csv('Input.csv', header=None, converters={ 1: strToDate,
    2: pd.Timedelta, 4: strToTimeDelta, 6: strToTimeDelta, 7: strToTimeDelta })
</code>```

(to convert column 2 use native pandasonic function pd.Timedelta).

Then, if you need to convert some Timedelta column (e.g. column 7)
to the total number of seconds, including the fractional part, run:

```<code>df[7].dt.seconds + df[7].dt.microseconds / 1e6
</code>```

But the default result of reading columns 4, 6 and 7 is just
float i.e. the number of seconds.

They are conceptually times, but actually:

in the input file they are kept as text,

after read_csv they are floats keeping the number of seconds.

So why do you need any conversion of these columns?

Body:
I am currently writing code to analyse a large subset of data. I have used the pandas to read the text files and I am printing it using data.head(). I need to specify the dtype for 9 columns (the ninth one being null) because the process would be too memory intensive otherwise but I have no clue how to specify the dtype for columns lacking column headers. Would it be the same as for specifying dtype for column headers? For reference my columns data type would probably be the follows:

Column 1: Mixed as it contains alphanumeric characters

Column 2: Date in the format YY/MM/DD

Column 3: Time in Hours/Minutes/Seconds/Milliseconds

Column 4: Str

Column 5: Time

Column 6: Str

Column 7: Time

Column 8: Time

Column 9: Null

Here is an excerpt of the text file

Here is also an excerpt of my code

    import sys
    import os
    import glob
    import pandas as pd
    import numpy as np

    path = '/Users/MysteriousHo-Oh1231/Downloads/Datapoints1/*.txt'
    dataframes = []
    for filename in glob.iglob(path):
      data = pd.read_csv(filename, header=None, delimiter='\t',  dtype={0: object, 1: int, 2: int, 3: object, 4: int, 5: object, 6: int, 7: int, 8: None})
      print(data.head())

I tried the above code and it returned this error:

Please help me with this!

Body:
Define 3 following conversion functions:

def strToDate(tt):
    return pd.to_datetime(tt, yearfirst=True)

def strToTime(tt):
    return pd.to_datetime(tt, format='%I:%M:%S.%f').time()

def strToTime2(tt):
    return pd.Timestamp(float(tt), unit='s').time()

Then read your DataFrame, passing them as converters for the columns
requiring "specialized" conversion:

df = pd.read_csv('Input.csv', header=None, converters={ 1: strToDate,
    2: strToTime, 4: strToTime2, 6: strToTime2, 7: strToTime2 })

When you print df.info(), then:

column 1 (date) is of datetime64[ns] type,

column 8 (NaNs) is of float64 type,

all other columns are of object type.

But don't be misguided. In Pandas the type of object means actually
"something other than a number or datetime".

When you retrieve individual values, e.g. df.iloc[0,2] you
will get: datetime.time(11, 24, 31, 758000), similar for any cell
from column 4, 6 or 7, so they are of just the required type.

Another solution based on Timedelta

Define converter functions as:

def strToDate(tt):
    return pd.to_datetime(tt, yearfirst=True)

def strToTimeDelta(tt):
    return pd.Timedelta(float(tt), unit='S')

Read your dataframe:

df = pd.read_csv('Input.csv', header=None, converters={ 1: strToDate,
    2: pd.Timedelta, 4: strToTimeDelta, 6: strToTimeDelta, 7: strToTimeDelta })

(to convert column 2 use native pandasonic function pd.Timedelta).

Then, if you need to convert some Timedelta column (e.g. column 7)
to the total number of seconds, including the fractional part, run:

df[7].dt.seconds + df[7].dt.microseconds / 1e6

But the default result of reading columns 4, 6 and 7 is just
float i.e. the number of seconds.

They are conceptually times, but actually:

in the input file they are kept as text,

after read_csv they are floats keeping the number of seconds.

So why do you need any conversion of these columns?


问:
Delete Operation Slows down intermittently oracle 11g
We have a audit Table in production environment where we delete almost 15 millions data everyday(data which is older than some days)in PL/SQL batch. On a good day this query takes 1.5 hours to delete the same data. But intermittently some days this is not deleting the same amount of data even in 4 hours. There is no trigger on this table and Created column is indexed.

```<code>DELETE FROM SIEBEL.CX_AUDIT_SEARCH
WHERE CREATED < '20-MAy-2020' AND rownum <= 10000;
</code>```

Explain pla:

```<code>DELETE STATEMENT    ALL_ROWS    6   10000   180000
DELETE SIEBEL.CX_AUDIT_SEARCH
COUNT(STOPKEY)                                  ROWNUM<=10000
INDEX(RANGE SCAN) SIEBEL.CX_AUDIT_SEARCH_U1 ANALYZED    6   170692  3072456             "CREATED"<'20-MAy-2020'
</code>```

Could you please suggest any possible reason.

答:
This is a bit long for a comment.

For this process, you want to partition the table.  This stores the table in separate "files" for each partition.  And partitions can be dropped -- this process is much faster than deleting the rows.

You have described the rows to be deleted as rows older than a particular date.  That is the sweet spot for a partitioning solution.

You can learn more about it in the documentation.  I am surprised that you could have such a large database and not be aware of this functionality.

Body:
We have a audit Table in production environment where we delete almost 15 millions data everyday(data which is older than some days)in PL/SQL batch. On a good day this query takes 1.5 hours to delete the same data. But intermittently some days this is not deleting the same amount of data even in 4 hours. There is no trigger on this table and Created column is indexed.

DELETE FROM SIEBEL.CX_AUDIT_SEARCH
WHERE CREATED < '20-MAy-2020' AND rownum <= 10000;

Explain pla:

DELETE STATEMENT    ALL_ROWS    6   10000   180000
DELETE SIEBEL.CX_AUDIT_SEARCH
COUNT(STOPKEY)                                  ROWNUM<=10000
INDEX(RANGE SCAN) SIEBEL.CX_AUDIT_SEARCH_U1 ANALYZED    6   170692  3072456             "CREATED"<'20-MAy-2020'

Could you please suggest any possible reason.


问:
Reading contents of Scanned PDF (JPEG) using OCR (Optical Character Recognition)
I have been trying to covert Scanned Non-selectable PDF (JPEG) using OCR (Optical Character Recognition).

Scanned PDF Document to be Converted

But, I am getting an error as attached.

Please look into this and suggest me to get the expected result.

```<code># Import libraries
from PIL import Image
import pytesseract
import sys
from pdf2image import convert_from_path
import os

# Path of the pdf
PDF_file = "document.pdf"

'''
Part #1 : Converting PDF to images
'''

# Store all the pages of the PDF in a variable
pages = convert_from_path(PDF_file, 500)

# Counter to store images of each page of PDF to image
image_counter = 1

# Iterate through all the pages stored above
for page in pages:

    # Declaring filename for each page of PDF as JPG
    # For each page, filename will be:
    # PDF page 1 -> page_1.jpg
    # PDF page 2 -> page_2.jpg
    # PDF page 3 -> page_3.jpg
    # ....
    # PDF page n -> page_n.jpg
    filename = "page_"+str(image_counter)+".jpg"

    # Save the image of the page in system
    page.save(filename, 'JPEG')

    # Increment the counter to update filename
    image_counter = image_counter + 1

'''
Part #2 - Recognizing text from the images using OCR
'''

# Variable to get count of total number of pages
filelimit = image_counter-1

# Creating a text file to write the output
outfile = "out_text.txt"

# Open the file in append mode so that
# All contents of all images are added to the same file
f = open(outfile, "a")

# Iterate from 1 to total number of pages
for i in range(1, filelimit + 1):

    # Set filename to recognize text from
    # Again, these files will be:
    # page_1.jpg
    # page_2.jpg
    # ....
    # page_n.jpg
    filename = "page_"+str(i)+".jpg"

    # Recognize the text as string in image using pytesserct
    text = str(((pytesseract.image_to_string(Image.open(filename)))))

    # The recognized text is stored in variable text
    # Any string processing may be applied on text
    # Here, basic formatting has been done:
    # In many PDFs, at line ending, if a word can't
    # be written fully, a 'hyphen' is added.
    # The rest of the word is written in the next line
    # Eg: This is a sample text this word here GeeksF-
    # orGeeks is half on first line, remaining on next.
    # To remove this, we replace every '-\n' to ''.
    text = text.replace('-\n', '')

    # Finally, write the processed text to the file.
    f.write(text)

# Close the file after writing all the text.
f.close()
</code>```

Attached the document to be converted and the error that I am facing.

答:
The problem is in your pdf to image conversion. I have not tried pdf2image.
I use fitz. This program is able to extract even multiple images present in a single pdf page.

Install the package

```<code>pip install PyMuPDF
</code>```

then

```<code>import fitz

def converted(directory_to_store, path_of_pdf_file):
    file = fitz.open(path_of_pdf_file)
    page = len(file)
    j = 0
    for i in range(page):
        for image in file.getPageImageList(i):
            my_xref = image[0]
            pic = fitz.Pixmap(file, my_xref)
            final_image = fitz.Pixmap(fitz.csRGB, pic)
            file_name = str(j) + '.png'
            image_path = directory_to_store + file_name
            final_image.writePNG(img_path)
            j+=1
            pic = None
            final_pic = None

    print('Conversion Complete')
</code>```

Body:
I have been trying to covert Scanned Non-selectable PDF (JPEG) using OCR (Optical Character Recognition).

Scanned PDF Document to be Converted

But, I am getting an error as attached.

Please look into this and suggest me to get the expected result.

# Import libraries
from PIL import Image
import pytesseract
import sys
from pdf2image import convert_from_path
import os

# Path of the pdf
PDF_file = "document.pdf"

'''
Part #1 : Converting PDF to images
'''

# Store all the pages of the PDF in a variable
pages = convert_from_path(PDF_file, 500)

# Counter to store images of each page of PDF to image
image_counter = 1

# Iterate through all the pages stored above
for page in pages:

    # Declaring filename for each page of PDF as JPG
    # For each page, filename will be:
    # PDF page 1 -> page_1.jpg
    # PDF page 2 -> page_2.jpg
    # PDF page 3 -> page_3.jpg
    # ....
    # PDF page n -> page_n.jpg
    filename = "page_"+str(image_counter)+".jpg"

    # Save the image of the page in system
    page.save(filename, 'JPEG')

    # Increment the counter to update filename
    image_counter = image_counter + 1

'''
Part #2 - Recognizing text from the images using OCR
'''

# Variable to get count of total number of pages
filelimit = image_counter-1

# Creating a text file to write the output
outfile = "out_text.txt"

# Open the file in append mode so that
# All contents of all images are added to the same file
f = open(outfile, "a")

# Iterate from 1 to total number of pages
for i in range(1, filelimit + 1):

    # Set filename to recognize text from
    # Again, these files will be:
    # page_1.jpg
    # page_2.jpg
    # ....
    # page_n.jpg
    filename = "page_"+str(i)+".jpg"

    # Recognize the text as string in image using pytesserct
    text = str(((pytesseract.image_to_string(Image.open(filename)))))

    # The recognized text is stored in variable text
    # Any string processing may be applied on text
    # Here, basic formatting has been done:
    # In many PDFs, at line ending, if a word can't
    # be written fully, a 'hyphen' is added.
    # The rest of the word is written in the next line
    # Eg: This is a sample text this word here GeeksF-
    # orGeeks is half on first line, remaining on next.
    # To remove this, we replace every '-\n' to ''.
    text = text.replace('-\n', '')

    # Finally, write the processed text to the file.
    f.write(text)

# Close the file after writing all the text.
f.close()

Attached the document to be converted and the error that I am facing.

Body:
The problem is in your pdf to image conversion. I have not tried pdf2image.
I use fitz. This program is able to extract even multiple images present in a single pdf page.

Install the package

pip install PyMuPDF

then

import fitz

def converted(directory_to_store, path_of_pdf_file):
    file = fitz.open(path_of_pdf_file)
    page = len(file)
    j = 0
    for i in range(page):
        for image in file.getPageImageList(i):
            my_xref = image[0]
            pic = fitz.Pixmap(file, my_xref)
            final_image = fitz.Pixmap(fitz.csRGB, pic)
            file_name = str(j) + '.png'
            image_path = directory_to_store + file_name
            final_image.writePNG(img_path)
            j+=1
            pic = None
            final_pic = None

    print('Conversion Complete')


答: Maybe it's easier and faster to test the emptiness of the string after using trim() on it.</p>

Body:
Need a Regular expresssion that should not allow  only space  in string, It can allow spaces along  with characters.

e.g: space+char+space  is  allowed  where  as  only  space  is not allowed


问:
Do we need Optional ifNotPresent for use in the middle of chain?
There are so many questions and threads about Optional API but I didn't found any for my case.

For example, I need first check emptiness of an Optional variable, for logging purpose, and then
check the value, if presents, with some predicate. Whatever check fails, I need to throw an exception.

Below is my real workaround for that

SomeValue value = someOptional.orElseThrow(() -> {
    log.debug("nothing here");
    return new NothingSpecialHereException();
});

if (!value.isSpecial()) {
    log.debug("something here, but not special");
    throw new NothingSpecialHereException();
}
```

<p>When I was looking for an alternative solution for that, I tried something like that</p>

<pre class="lang-java prettyprint-override"><code>SomeValue value = someOptional
    .filter(SomeValue::isSpecial)
    .orElseThrow(() -> {
        log.debug("nothing special here"); // but this case for both "no value" and "value is not special"
        return new NothingSpecialHereException();
    });
</code>```

I know that there's no any built-in solution for this situation in Java, but seems like I missing something like:

SomeValue value = someOptional
   .ifNotPresent(() -> log.debug("nothing here")) // that method returns Optional for further invocatons
   .filter(val -> {
      if (!val.isSpecial()) {
          log.debug("something here, but not special");
          return false;
      }
      return true;
   })
   .orElseThrow(NothingSpecialHereException::new);
```

<p>This is not the first time when I miss something like <code>ifNotPresent</code> or <code>else*</code> methods for use in the middle of pipe, not in the end. IMO sometimes that approach might be more readable, for example</p>

<pre class="lang-java prettyprint-override"><code>optional
    .map(...)
    .filter(...)
    .ifEmpty(...) // do smth after filter, maybe even throw
    .map(...) // and continue processing
</code>```

Maybe anyone encountered same problem? Or maybe I missed some better solution? Maybe there's a library that provides solutions for that?

答:
Thanks to comments! I've checked out Vavr Option and Guava Optional APIs.

Guava Optional is even less rich in methods than Java Optional, so this is not a solution.

What I've found is the Vavr onEmpty method of Option class, that executes Runnable if the Option value is empty.

SomeValue value = Option.ofOptional(someOptional)
    .onEmpty(() -> log.debug("nothing here"))
    .filter(val -> {
      if (!val.isSpecial()) {
          log.debug("something here, but not special");
          return false;
      }
      return true;
   })
   .getOrElseThrow(NothingHereException::new);

```
<p>That example displays one of debug messages and throws exception only in one place. Looks a lot better.</p>
<p>However, Vavr is a big library with own collections, functional interfaces and monads like above. This is a big dependency for a project and it is hardly will be implemented in my project or any other long-time-existed project just for new fancy <code>Optional</code> replacement.</p>
<p>Plus, Vavr's <code>Option</code> does'nt have something like <code>onEmptyThrow</code>, so it's not so perfect =).</p>
<p>This thread is still open for suggestions, but now for Java 8 workaround I think this comment may be considered as answer.</p>
<h2>UPDATE</h2>
<p>Seems like I've found the best solution for problems like that.
Few days ago I found lombok's @ExtensionMethod annotation that makes possible solutions like below</p>
```class Extensions {
    public static <T, E extends Throwable> Optional<T> ifNotPresentThrow(Optional<T> opt, Supplier<E> exceptionSupplier) throws E {
        if (!opt.isPresent()) {
            throw exceptionSupplier.get();
        }
        return opt;
    }

}

@ExtensionMethod(Extensions.class)
class Test {
    public static void main(String[] args) {
        // assume there is someNullable variable

        // instead of writing
        Extensions.ifNotPresentThrow(Optional.ofNullable(someNullable), NothingHereException::new)
                .map(...);

        // I can write
        Optional.ofNullable(someNullable)
                .ifNotPresentThrow(NothingHereException::new)
                .map(...); // now possible to continue if optional present
    }
}
```

With that Kotlin-like extension methods it's possible to add any method to Optional's API. Lombok will just transform second variant into first during compilation.

However, this feature is experimental (seems like forever) and has possible bugs and decompiled bytecode looks pretty dirty (with various unnecessary local variables, etc.)

Body:
There are so many questions and threads about Optional API but I didn't found any for my case.

For example, I need first check emptiness of an Optional variable, for logging purpose, and then
check the value, if presents, with some predicate. Whatever check fails, I need to throw an exception.

Below is my real workaround for that

SomeValue value = someOptional.orElseThrow(() -> {
    log.debug("nothing here");
    return new NothingSpecialHereException();
});

if (!value.isSpecial()) {
    log.debug("something here, but not special");
    throw new NothingSpecialHereException();
}

When I was looking for an alternative solution for that, I tried something like that

SomeValue value = someOptional
    .filter(SomeValue::isSpecial)
    .orElseThrow(() -> {
        log.debug("nothing special here"); // but this case for both "no value" and "value is not special"
        return new NothingSpecialHereException();
    });

I know that there's no any built-in solution for this situation in Java, but seems like I missing something like:

SomeValue value = someOptional
   .ifNotPresent(() -> log.debug("nothing here")) // that method returns Optional for further invocatons
   .filter(val -> {
      if (!val.isSpecial()) {
          log.debug("something here, but not special");
          return false;
      }
      return true;
   })
   .orElseThrow(NothingSpecialHereException::new);

This is not the first time when I miss something like ifNotPresent or else* methods for use in the middle of pipe, not in the end. IMO sometimes that approach might be more readable, for example

optional
    .map(...)
    .filter(...)
    .ifEmpty(...) // do smth after filter, maybe even throw
    .map(...) // and continue processing

Maybe anyone encountered same problem? Or maybe I missed some better solution? Maybe there's a library that provides solutions for that?

Body:
Thanks to comments! I've checked out Vavr Option and Guava Optional APIs.

Guava Optional is even less rich in methods than Java Optional, so this is not a solution.

What I've found is the Vavr onEmpty method of Option class, that executes Runnable if the Option value is empty.

SomeValue value = Option.ofOptional(someOptional)
    .onEmpty(() -> log.debug("nothing here"))
    .filter(val -> {
      if (!val.isSpecial()) {
          log.debug("something here, but not special");
          return false;
      }
      return true;
   })
   .getOrElseThrow(NothingHereException::new);

That example displays one of debug messages and throws exception only in one place. Looks a lot better.

However, Vavr is a big library with own collections, functional interfaces and monads like above. This is a big dependency for a project and it is hardly will be implemented in my project or any other long-time-existed project just for new fancy Optional replacement.

Plus, Vavr's Option does'nt have something like onEmptyThrow, so it's not so perfect =).

This thread is still open for suggestions, but now for Java 8 workaround I think this comment may be considered as answer.

UPDATE

Seems like I've found the best solution for problems like that.
Few days ago I found lombok's @ExtensionMethod annotation that makes possible solutions like below

class Extensions {
    public static <T, E extends Throwable> Optional<T> ifNotPresentThrow(Optional<T> opt, Supplier<E> exceptionSupplier) throws E {
        if (!opt.isPresent()) {
            throw exceptionSupplier.get();
        }
        return opt;
    }

}

@ExtensionMethod(Extensions.class)
class Test {
    public static void main(String[] args) {
        // assume there is someNullable variable

        // instead of writing
        Extensions.ifNotPresentThrow(Optional.ofNullable(someNullable), NothingHereException::new)
                .map(...);

        // I can write
        Optional.ofNullable(someNullable)
                .ifNotPresentThrow(NothingHereException::new)
                .map(...); // now possible to continue if optional present
    }
}

With that Kotlin-like extension methods it's possible to add any method to Optional's API. Lombok will just transform second variant into first during compilation.

However, this feature is experimental (seems like forever) and has possible bugs and decompiled bytecode looks pretty dirty (with various unnecessary local variables, etc.)


问:
Creating multiple folders dynamically if not exist in Box using Python
Can anybody help me , how to create multiple folders with Year format(Folders like 2018,2019 etc if it does not exists) in box inside a folder(named as Archive) using Python.

I have a piece of code like below.However I am unable to create any folder dynamicaly.

it = shared_folder.get_items()
for i in it:
    if (i.name == 'Lithuansa'):

```<code>#print('{0} {1} is named "{2}"'.format(i.type.capitalize(), i.id, i.name))
</code>```

答:
You can use the Python SDK.

Starting at your root folder ('0') you can create subsequent subfolders using this API call.

```<code>subfolder = client.folder('0').create_subfolder('Folder 1')
</code>```

This subfolder will then have an ID which you can then use to create subfolders in that folder.

Additionally, you might want to run a check to see if a folder already exists before this is created. You can do this by listing the files and folders in the folder.

```<code>items = client.folder(folder_id='22222').get_items()
for item in items:
    print('{0} {1} is named "{2}"'.format(item.type.capitalize(), item.id, item.name))
</code>```

Body:
Can anybody help me , how to create multiple folders with Year format(Folders like 2018,2019 etc if it does not exists) in box inside a folder(named as Archive) using Python.

I have a piece of code like below.However I am unable to create any folder dynamicaly.

it = shared_folder.get_items()
for i in it:
    if (i.name == 'Lithuansa'):

#print('{0} {1} is named "{2}"'.format(i.type.capitalize(), i.id, i.name))

Body:
You can use the Python SDK.

Starting at your root folder ('0') you can create subsequent subfolders using this API call.

subfolder = client.folder('0').create_subfolder('Folder 1')

This subfolder will then have an ID which you can then use to create subfolders in that folder.

Additionally, you might want to run a check to see if a folder already exists before this is created. You can do this by listing the files and folders in the folder.

items = client.folder(folder_id='22222').get_items()
for item in items:
    print('{0} {1} is named "{2}"'.format(item.type.capitalize(), item.id, item.name))


答:
You simply have to enforce a non-space character appearing at least once:</p>

<p>\s*\S+\s* </p>

Title: Need a Regular expresssion that should not allow only space in string, It can allow spaces along with characters

Body:
You simply have to enforce a non-space character appearing at least once:

\s*\S+\s*


问:
Does anyone have an example of PrestaSharp how to add products?
Hello

I am using presta sharp to star a new project of webservice with prestashop, does anybody have a code on c# of how to add a product?

Thank you

答: just look at https://www.prestashop.com/forums/topic/559930-c-how-send-a-new-product/ you have an example how you can push product with webservice in C#</p>


问:
Corda : The responder flow annotation @InitiatedBy in Corda showing an incompatible types error
I am in the process of developing a CorDapp for a Three Party Atomic Transaction in Java.

I was trying to write 2 flows - CreateAssetTransferRequestInitiatorFlow (Initiator Flow) which extends an Abstract class called AbstractCreateAssetTransferRequestFlow(This class extends FlowLogic Class) and a corresponding responder flow called CreateAssetTransferRequestResponderFlow.

The abstract class is annotated with @InitiatingFlow and the responder flow when annotated with @InitiatedBy(AbstractCreateAssetTransferRequestFlow.class) shows an error.

The error says

'Found:java.lang.Class <
  com.template.cordapp.flows.AbstractCreateAssetTransferRequestFlow>',
  Required : 'java.lang.Class< ? extends net.corda.core.flows.FlowLogic
  < ?>>'

The abstract class extends the Flow Logic class.

Initiating Flow

Abstract Flow

Responder Flow

Can someone please help me out with this. Please find attached screenshots for your reference.

Thank you

答:
You need to remove the <SignedTransaction> part from CreateAssetTransferRequestInitiatorFlow<SignedTransction>.

This should help you get rid of the compilation error.


问:
Characters '!1' and '!2' in command prompt
I'm using a Mac using iTerm2, OhMyZsh, and the Powerlevel10k theme. I've installed the recommended fonts directly from the Powerlevel10k docs, updated the settings for fonts in Terminal, iTerm2, and VS Code according to the docs, and it mostly works, except that there is always some unexpected character at the end of the prompt (usually !1 or !2). I've found nothing in the docs, searches of forums, or internet searches that helps with this so far.

screenshot of prompt

Any hints that could help me resolve this, even just the right search term to help me find answers would be much appreciated.

答:
From the Powerlevel10k FAQ:

Q: What do different symbols in Git status mean?

When using Lean, Classic or Rainbow style, Git status may look like this:

  ```<code>feature:master ⇣42⇡42 ⇠42⇢42 *42 merge ~42 +42 !42 ?42
</code>```

Legend:

  ```<code>| Symbol    | Meaning                                                              | Source                                                 |
| --------- | -------------------------------------------------------------------- | ------------------------------------------------------ |
| `feature` | current branch; replaced with `#tag` or `@commit` if not on a branch | `git status --ignore-submodules=dirty`                 |
| `master`  | remote tracking branch; only shown if different from local branch    | `git rev-parse --abbrev-ref --symbolic-full-name @{u}` |
| `⇣42`     | this many commits behind the remote                                  | `git status --ignore-submodules=dirty`                 |
| `⇡42`     | this many commits ahead of the remote                                | `git status --ignore-submodules=dirty`                 |
| `⇠42`     | this many commits behind the push remote                             | `git rev-list --left-right --count HEAD...@{push}`     |
| `⇢42`     | this many commits ahead of the push remote                           | `git rev-list --left-right --count HEAD...@{push}`     |
| `*42`     | this many stashes                                                    | `git stash list`                                       |
| `merge`   | repository state                                                     | `git status --ignore-submodules=dirty`                 |
| `~42`     | this many merge conflicts                                            | `git status --ignore-submodules=dirty`                 |
| `+42`     | this many staged changes                                             | `git status --ignore-submodules=dirty`                 |
| `!42`     | this many unstaged changes                                           | `git status --ignore-submodules=dirty`                 |
| `?42`     | this many untracked files                                            | `git status --ignore-submodules=dirty`                 |
| `─`       | the number of staged, unstaged or untracked files is unknown         | `echo $POWERLEVEL9K_VCS_MAX_INDEX_SIZE_DIRTY` or `git config --get bash.showDirtyState` |
</code>```

See also: How do I change the format of Git status?

Body:
From the Powerlevel10k FAQ:

Q: What do different symbols in Git status mean?

When using Lean, Classic or Rainbow style, Git status may look like this:

feature:master ⇣42⇡42 ⇠42⇢42 *42 merge ~42 +42 !42 ?42

Legend:

| Symbol    | Meaning                                                              | Source                                                 |
| --------- | -------------------------------------------------------------------- | ------------------------------------------------------ |
| `feature` | current branch; replaced with `#tag` or `@commit` if not on a branch | `git status --ignore-submodules=dirty`                 |
| `master`  | remote tracking branch; only shown if different from local branch    | `git rev-parse --abbrev-ref --symbolic-full-name @{u}` |
| `⇣42`     | this many commits behind the remote                                  | `git status --ignore-submodules=dirty`                 |
| `⇡42`     | this many commits ahead of the remote                                | `git status --ignore-submodules=dirty`                 |
| `⇠42`     | this many commits behind the push remote                             | `git rev-list --left-right --count HEAD...@{push}`     |
| `⇢42`     | this many commits ahead of the push remote                           | `git rev-list --left-right --count HEAD...@{push}`     |
| `*42`     | this many stashes                                                    | `git stash list`                                       |
| `merge`   | repository state                                                     | `git status --ignore-submodules=dirty`                 |
| `~42`     | this many merge conflicts                                            | `git status --ignore-submodules=dirty`                 |
| `+42`     | this many staged changes                                             | `git status --ignore-submodules=dirty`                 |
| `!42`     | this many unstaged changes                                           | `git status --ignore-submodules=dirty`                 |
| `?42`     | this many untracked files                                            | `git status --ignore-submodules=dirty`                 |
| `─`       | the number of staged, unstaged or untracked files is unknown         | `echo $POWERLEVEL9K_VCS_MAX_INDEX_SIZE_DIRTY` or `git config --get bash.showDirtyState` |

See also: How do I change the format of Git status?


问:
Failure building cross-compiling 64-bit GCC
I'm trying to get a working gcc cross-compiler created that lives on my local machine [Darwin new-host-2.home 10.7.4 Darwin Kernel Version 10.7.4: Mon Apr 18 21:24:17 PDT 2011; root:xnu-1504.14.12~3/RELEASE_X86_64 x86_64] and targets a FreeBSD 8.2 x86_64 (AMD64 in FreeBSD terms) target.

I'm compiling gcc 4.3.1, binutils 2.19, GMP 4.2.3, MPFR 2.3.2.

I'm seeing a couple of things that could be going wrong, but they may be red herrings.  For what it's worth I am taking known working scripts to build a cross compiler and simply trying to get them to work for x86_64 architecture, so I know I'm not out in left field..

I'm using the gcc compiler target "x86_64-pc-freebsd7" which seems correct.  I use compiler flags of: compilerConfigureFlags="--enable-version-specific-runtime-libs --enable-shared --enable-threads=posix --disable-checking --disable-libunwind-exceptions --with-system-zlib --enable-__cxa_atexit" and I configure binutils using "--enable-64-bit-bfd"

In my final error; something that catches my attention is '-m32' which I'm not sure if it should be there.  The error is because ld can't make sense out of my "incompatible" file /Developer/Cocotron/1.0/FreeBSD/x86_64/gcc-4.3.1/x86_64-pc-freebsd7/lib/libc.a when searching for -lc.  When I run file on libc.a and libc.so from the FreeBSD box I get:

sh-3.2# file /Developer/Cocotron/1.0/FreeBSD/x86_64/gcc-4.3.1/x86_64-pc-freebsd7/lib/libc.a/Developer/Cocotron/1.0/FreeBSD/x86_64/gcc-4.3.1/x86_64-pc-freebsd7/lib/libc.a: current ar archive

sh-3.2# file /Developer/Cocotron/1.0/FreeBSD/x86_64/gcc-4.3.1/x86_64-pc-freebsd7/lib/libc.so
/Developer/Cocotron/1.0/FreeBSD/x86_64/gcc-4.3.1/x86_64-pc-freebsd7/lib/libc.so: ELF 64-bit LSB shared object, x86-64, version 1 (FreeBSD), dynamically linked, stripped

Final line my build dies on:

/Developer/Cocotron/1.0/build/FreeBSD/x86_64/gcc-4.3.1/./gcc/xgcc -B/Developer/Cocotron/1.0/build/FreeBSD/x86_64/gcc-4.3.1/./gcc/ -B/Developer/Cocotron/1.0/FreeBSD/x86_64/gcc-4.3.1/x86_64-pc-freebsd7/bin/ -B/Developer/Cocotron/1.0/FreeBSD/x86_64/gcc-4.3.1/x86_64-pc-freebsd7/lib/ -isystem /Developer/Cocotron/1.0/FreeBSD/x86_64/gcc-4.3.1/x86_64-pc-freebsd7/include -isystem /Developer/Cocotron/1.0/FreeBSD/x86_64/gcc-4.3.1/x86_64-pc-freebsd7/sys-include -O2  -O2 -g -m32   -DIN_GCC -DCROSS_DIRECTORY_STRUCTURE -DNATIVE_CROSS   -W -Wall -Wwrite-strings -Wstrict-prototypes -Wmissing-prototypes -Wold-style-definition  -isystem ./include   -fPIC -pthread -g -DHAVE_GTHR_DEFAULT -DIN_LIBGCC2 -D__GCC_FLOAT_NOT_NEEDED  -shared -nodefaultlibs -Wl,--soname=libgcc_s.so.1 -Wl,--version-script=libgcc.map -o ./libgcc_s.so.1.tmp -O2 -g -m32 -B./ _muldi3_s.o _negdi2_s.o _lshrdi3_s.o _ashldi3_s.o _ashrdi3_s.o _cmpdi2_s.o _ucmpdi2_s.o _clear_cache_s.o _enable_execute_stack_s.o _trampoline_s.o __main_s.o _absvsi2_s.o _absvdi2_s.o _addvsi3_s.o _addvdi3_s.o _subvsi3_s.o _subvdi3_s.o _mulvsi3_s.o _mulvdi3_s.o _negvsi2_s.o _negvdi2_s.o _ctors_s.o _ffssi2_s.o _ffsdi2_s.o _clz_s.o _clzsi2_s.o _clzdi2_s.o _ctzsi2_s.o _ctzdi2_s.o _popcount_tab_s.o _popcountsi2_s.o _popcountdi2_s.o _paritysi2_s.o _paritydi2_s.o _powisf2_s.o _powidf2_s.o _powixf2_s.o _powitf2_s.o _mulsc3_s.o _muldc3_s.o _mulxc3_s.o _multc3_s.o _divsc3_s.o _divdc3_s.o _divxc3_s.o _divtc3_s.o _bswapsi2_s.o _bswapdi2_s.o _fixunssfsi_s.o _fixunsdfsi_s.o _fixunsxfsi_s.o _fixsfdi_s.o _fixdfdi_s.o _fixxfdi_s.o _fixtfdi_s.o _fixunssfdi_s.o _fixunsdfdi_s.o _fixunsxfdi_s.o _fixunstfdi_s.o _floatdisf_s.o _floatdidf_s.o _floatdixf_s.o _floatditf_s.o _floatundisf_s.o _floatundidf_s.o _floatundixf_s.o _floatunditf_s.o _divdi3_s.o _moddi3_s.o _udivdi3_s.o _umoddi3_s.o _udiv_w_sdiv_s.o _udivmoddi4_s.o unwind-dw2_s.o unwind-dw2-fde_s.o unwind-sjlj_s.o gthr-gnat_s.o unwind-c_s.o emutls_s.o -lc && rm -f ./libgcc_s.so && if [ -f ./libgcc_s.so.1 ]; then mv -f ./libgcc_s.so.1 ./libgcc_s.so.1.backup; else true; fi && mv ./libgcc_s.so.1.tmp ./libgcc_s.so.1 && ln -s libgcc_s.so.1 ./libgcc_s.so
/Developer/Cocotron/1.0/FreeBSD/x86_64/gcc-4.3.1/x86_64-pc-freebsd7/bin/ld: skipping incompatible /Developer/Cocotron/1.0/FreeBSD/x86_64/gcc-4.3.1/x86_64-pc-freebsd7/lib//libc.so when searching for -lc
/Developer/Cocotron/1.0/FreeBSD/x86_64/gcc-4.3.1/x86_64-pc-freebsd7/bin/ld: skipping incompatible /Developer/Cocotron/1.0/FreeBSD/x86_64/gcc-4.3.1/x86_64-pc-freebsd7/lib/libc.a when searching for -lc
/Developer/Cocotron/1.0/FreeBSD/x86_64/gcc-4.3.1/x86_64-pc-freebsd7/bin/ld: cannot find -lc
collect2: ld returned 1 exit status
make[2]: *** [libgcc_s.so] Error 1
make[1]: *** [all-target-libgcc] Error 2
make: *** [all] Error 2

I'm surprised ld can't handle it, because when I run this version of 'ld' I get the followig output:

/Developer/Cocotron/1.0/FreeBSD/x86_64/gcc-4.3.1/x86_64-pc-freebsd7/bin/ld: supported targets: elf64-x86-64-freebsd elf32-i386-freebsd coff-i386 efi-app-ia32 efi-bsdrv-ia32 efi-rtdrv-ia32 efi-app-x86_64 efi-bsdrv-x86_64 efi-rtdrv-x86_64 elf32-i386 elf64-x86-64 elf64-little elf64-big elf32-little elf32-big srec symbolsrec tekhex binary ihex
/Developer/Cocotron/1.0/FreeBSD/x86_64/gcc-4.3.1/x86_64-pc-freebsd7/bin/ld: supported emulations: elf_x86_64_fbsd elf_i386_fbsd elf_x86_64 elf_i386
/Developer/Cocotron/1.0/FreeBSD/x86_64/gcc-4.3.1/x86_64-pc-freebsd7/bin/ld: emulation specific options:
elf_x86_64_fbsd:

Which indicates to me that I've built the binutils correctly.. yet that can't handle a library that's an ELF 64-bit x86-64 FreeBSD shared object??

To give the story from the start - compiling binutils is flawless it seems.

Compiling GMP and MPFR both give me some ranlib issues that worry me a bit, trying to build up a .a library but the .o files have no symbols.. this could be normal but I can't tell?

GMP:

```/usr/bin/ranlib: file: .libs/libprintf.a(obprintf.o) has no symbols
/usr/bin/ranlib: file: .libs/libprintf.a(obvprintf.o) has no symbols
/usr/bin/ranlib: file: .libs/libprintf.a(obprntffuns.o) has no symbols
/usr/bin/ranlib: file: .libs/libprintf.a(repl-vsnprintf.o) has no symbols
ranlib .libs/libprintf.a
ranlib: file: .libs/libprintf.a(obprintf.o) has no symbols
ranlib: file: .libs/libprintf.a(obvprintf.o) has no symbols
ranlib: file: .libs/libprintf.a(obprntffuns.o) has no symbols
ranlib: file: .libs/libprintf.a(repl-vsnprintf.o) has no symbols
</blockquote>```

And I get some more further along..

```ranlib /Developer/Cocotron/1.0/FreeBSD/x86_64/gcc-4.3.1/lib/libgmp.a
ranlib: file: /Developer/Cocotron/1.0/FreeBSD/x86_64/gcc-4.3.1/lib/libgmp.a(mp_clz_tab.o) has no symbols
ranlib: file: /Developer/Cocotron/1.0/FreeBSD/x86_64/gcc-4.3.1/lib/libgmp.a(obprintf.o) has no symbols
ranlib: file: /Developer/Cocotron/1.0/FreeBSD/x86_64/gcc-4.3.1/lib/libgmp.a(obvprintf.o) has no symbols
ranlib: file: /Developer/Cocotron/1.0/FreeBSD/x86_64/gcc-4.3.1/lib/libgmp.a(obprntffuns.o) has no symbols
ranlib: file: /Developer/Cocotron/1.0/FreeBSD/x86_64/gcc-4.3.1/lib/libgmp.a(repl-vsnprintf.o) has no symbols
```

MPFR:

Similar deal:

```<blockquote></p>

<p>/usr/bin/ranlib: file: .libs/libmpfr.a(volatile.o) has no symbols
/usr/bin/ranlib: file: .libs/libmpfr.a(mp_clz_tab.o) has no symbols
/usr/bin/ranlib: file: .libs/libmpfr.a(logging.o) has no symbols
/usr/bin/ranlib: file: .libs/libmpfr.a(set_d64.o) has no symbols
/usr/bin/ranlib: file: .libs/libmpfr.a(get_d64.o) has no symbols
ranlib .libs/libmpfr.a
ranlib: file: .libs/libmpfr.a(volatile.o) has no symbols
ranlib: file: .libs/libmpfr.a(mp_clz_tab.o) has no symbols
ranlib: file: .libs/libmpfr.a(logging.o) has no symbols
ranlib: file: .libs/libmpfr.a(set_d64.o) has no symbols
ranlib: file: .libs/libmpfr.a(get_d64.o) has no symbols
creating libmpfr.la
```

And a bit further along..

```<blockquote>
ranlib /Developer/Cocotron/1.0/FreeBSD/x86_64/gcc-4.3.1/lib/libmpfr.a
ranlib: file: /Developer/Cocotron/1.0/FreeBSD/x86_64/gcc-4.3.1/lib/libmpfr.a(volatile.o) has no symbols
ranlib: file: /Developer/Cocotron/1.0/FreeBSD/x86_64/gcc-4.3.1/lib/libmpfr.a(mp_clz_tab.o) has no symbols
ranlib: file: /Developer/Cocotron/1.0/FreeBSD/x86_64/gcc-4.3.1/lib/libmpfr.a(logging.o) has no symbols
ranlib: file: /Developer/Cocotron/1.0/FreeBSD/x86_64/gcc-4.3.1/lib/libmpfr.a(set_d64.o) has no symbols
ranlib: file: /Developer/Cocotron/1.0/FreeBSD/x86_64/gcc-4.3.1/lib/libmpfr.a(get_d64.o) has no symbols
```

Then we're on to GCC, presumably with good binutils, GMP, and MPFR.. but finally during build of gcc (specifically libgcc) I get the ld linking failure.

Some more supporting information:

I compile binutils using:

```<blockquote>CFLAGS="-m32 -Wformat=0 -Wno-error=deprecated-declarations" $sourceFolder/binutils-$binutilsVersion/configure --prefix="$resultFolder" --target=$compilerTarget $binutilsConfigureFlags```

However I encounter the same problem if I switch to -m64..

```<blockquote>CFLAGS="-m64 -Wformat=0 -Wno-error=deprecated-declarations" $sourceFolder/binutils-$binutilsVersion/configure --prefix="$resultFolder" --target=$compilerTarget $binutilsConfigureFlags```

I compile GMP and MPFR using:

```<blockquote>ABI=32 $sourceFolder/gmp-$gmpVersion/configure --prefix="$resultFolder"```

I compile GCC using:

```<blockquote>
        CFLAGS="-m32" $sourceFolder/gcc-$gccVersion/configure -v --prefix="$resultFolder" --target=$compilerTarget \
                --with-gnu-as --with-gnu-ld --with-headers=$resultFolder/$compilerTarget/include \
                --without-newlib --disable-multilib --disable-libssp --disable-nls --enable-languages="$enableLanguages" \
                --with-gmp=$buildFolder/gmp-$gmpVersion --enable-decimal-float --with-mpfr=$resultFolder --enable-checking=release \
                --enable-objc-gc \<br>
                $compilerConfigureFlags<br>
```

For all these, I'm using:

```<blockquote>
compilerTarget=x86_64-pc-freebsd7
compilerConfigureFlags="--enable-version-specific-runtime-libs --enable-shared --enable-threads=posix --disable-checking --disable-libunwind-exceptions --with-system-zlib --enable-__cxa_atexit"
binutilsConfigureFlags="--enable-64-bit-bfd"
```

On my target FreeBSD system, which by the way is standard FreeBSD 8.2 RELEASE amd64, ld indicates very similar capabilities to my cross-compiling one.  In fact, it appears that my cross-compiling environment's ld handles a superset of what the actual target's ld handles - making me think I should be able to handle any files without the incompatibility I'm seeing

```<blockquote>
ld: supported targets: elf64-x86-64 efi-app-ia32 elf32-i386-freebsd srec symbolsrec tekhex binary ihex
ld: supported emulations: elf_i386_fbsd elf_x86_64_fbsd
ld: emulation specific options:
elf_i386_fbsd:
```

答: A 64 bit library can only linked to 64 bit object code. You need -m64 to build 64 bit object code, -m32 does produce 32 bit object code.

Body:
I'm trying to get a working gcc cross-compiler created that lives on my local machine [Darwin new-host-2.home 10.7.4 Darwin Kernel Version 10.7.4: Mon Apr 18 21:24:17 PDT 2011; root:xnu-1504.14.12~3/RELEASE_X86_64 x86_64] and targets a FreeBSD 8.2 x86_64 (AMD64 in FreeBSD terms) target.

I'm compiling gcc 4.3.1, binutils 2.19, GMP 4.2.3, MPFR 2.3.2.

I'm seeing a couple of things that could be going wrong, but they may be red herrings.  For what it's worth I am taking known working scripts to build a cross compiler and simply trying to get them to work for x86_64 architecture, so I know I'm not out in left field..

I'm using the gcc compiler target "x86_64-pc-freebsd7" which seems correct.  I use compiler flags of: compilerConfigureFlags="--enable-version-specific-runtime-libs --enable-shared --enable-threads=posix --disable-checking --disable-libunwind-exceptions --with-system-zlib --enable-__cxa_atexit" and I configure binutils using "--enable-64-bit-bfd"

In my final error; something that catches my attention is '-m32' which I'm not sure if it should be there.  The error is because ld can't make sense out of my "incompatible" file /Developer/Cocotron/1.0/FreeBSD/x86_64/gcc-4.3.1/x86_64-pc-freebsd7/lib/libc.a when searching for -lc.  When I run file on libc.a and libc.so from the FreeBSD box I get:

sh-3.2# file /Developer/Cocotron/1.0/FreeBSD/x86_64/gcc-4.3.1/x86_64-pc-freebsd7/lib/libc.a/Developer/Cocotron/1.0/FreeBSD/x86_64/gcc-4.3.1/x86_64-pc-freebsd7/lib/libc.a: current ar archive

sh-3.2# file /Developer/Cocotron/1.0/FreeBSD/x86_64/gcc-4.3.1/x86_64-pc-freebsd7/lib/libc.so
/Developer/Cocotron/1.0/FreeBSD/x86_64/gcc-4.3.1/x86_64-pc-freebsd7/lib/libc.so: ELF 64-bit LSB shared object, x86-64, version 1 (FreeBSD), dynamically linked, stripped

Final line my build dies on:

/Developer/Cocotron/1.0/build/FreeBSD/x86_64/gcc-4.3.1/./gcc/xgcc -B/Developer/Cocotron/1.0/build/FreeBSD/x86_64/gcc-4.3.1/./gcc/ -B/Developer/Cocotron/1.0/FreeBSD/x86_64/gcc-4.3.1/x86_64-pc-freebsd7/bin/ -B/Developer/Cocotron/1.0/FreeBSD/x86_64/gcc-4.3.1/x86_64-pc-freebsd7/lib/ -isystem /Developer/Cocotron/1.0/FreeBSD/x86_64/gcc-4.3.1/x86_64-pc-freebsd7/include -isystem /Developer/Cocotron/1.0/FreeBSD/x86_64/gcc-4.3.1/x86_64-pc-freebsd7/sys-include -O2  -O2 -g -m32   -DIN_GCC -DCROSS_DIRECTORY_STRUCTURE -DNATIVE_CROSS   -W -Wall -Wwrite-strings -Wstrict-prototypes -Wmissing-prototypes -Wold-style-definition  -isystem ./include   -fPIC -pthread -g -DHAVE_GTHR_DEFAULT -DIN_LIBGCC2 -D__GCC_FLOAT_NOT_NEEDED  -shared -nodefaultlibs -Wl,--soname=libgcc_s.so.1 -Wl,--version-script=libgcc.map -o ./libgcc_s.so.1.tmp -O2 -g -m32 -B./ _muldi3_s.o _negdi2_s.o _lshrdi3_s.o _ashldi3_s.o _ashrdi3_s.o _cmpdi2_s.o _ucmpdi2_s.o _clear_cache_s.o _enable_execute_stack_s.o _trampoline_s.o __main_s.o _absvsi2_s.o _absvdi2_s.o _addvsi3_s.o _addvdi3_s.o _subvsi3_s.o _subvdi3_s.o _mulvsi3_s.o _mulvdi3_s.o _negvsi2_s.o _negvdi2_s.o _ctors_s.o _ffssi2_s.o _ffsdi2_s.o _clz_s.o _clzsi2_s.o _clzdi2_s.o _ctzsi2_s.o _ctzdi2_s.o _popcount_tab_s.o _popcountsi2_s.o _popcountdi2_s.o _paritysi2_s.o _paritydi2_s.o _powisf2_s.o _powidf2_s.o _powixf2_s.o _powitf2_s.o _mulsc3_s.o _muldc3_s.o _mulxc3_s.o _multc3_s.o _divsc3_s.o _divdc3_s.o _divxc3_s.o _divtc3_s.o _bswapsi2_s.o _bswapdi2_s.o _fixunssfsi_s.o _fixunsdfsi_s.o _fixunsxfsi_s.o _fixsfdi_s.o _fixdfdi_s.o _fixxfdi_s.o _fixtfdi_s.o _fixunssfdi_s.o _fixunsdfdi_s.o _fixunsxfdi_s.o _fixunstfdi_s.o _floatdisf_s.o _floatdidf_s.o _floatdixf_s.o _floatditf_s.o _floatundisf_s.o _floatundidf_s.o _floatundixf_s.o _floatunditf_s.o _divdi3_s.o _moddi3_s.o _udivdi3_s.o _umoddi3_s.o _udiv_w_sdiv_s.o _udivmoddi4_s.o unwind-dw2_s.o unwind-dw2-fde_s.o unwind-sjlj_s.o gthr-gnat_s.o unwind-c_s.o emutls_s.o -lc && rm -f ./libgcc_s.so && if [ -f ./libgcc_s.so.1 ]; then mv -f ./libgcc_s.so.1 ./libgcc_s.so.1.backup; else true; fi && mv ./libgcc_s.so.1.tmp ./libgcc_s.so.1 && ln -s libgcc_s.so.1 ./libgcc_s.so
/Developer/Cocotron/1.0/FreeBSD/x86_64/gcc-4.3.1/x86_64-pc-freebsd7/bin/ld: skipping incompatible /Developer/Cocotron/1.0/FreeBSD/x86_64/gcc-4.3.1/x86_64-pc-freebsd7/lib//libc.so when searching for -lc
/Developer/Cocotron/1.0/FreeBSD/x86_64/gcc-4.3.1/x86_64-pc-freebsd7/bin/ld: skipping incompatible /Developer/Cocotron/1.0/FreeBSD/x86_64/gcc-4.3.1/x86_64-pc-freebsd7/lib/libc.a when searching for -lc
/Developer/Cocotron/1.0/FreeBSD/x86_64/gcc-4.3.1/x86_64-pc-freebsd7/bin/ld: cannot find -lc
collect2: ld returned 1 exit status
make[2]: *** [libgcc_s.so] Error 1
make[1]: *** [all-target-libgcc] Error 2
make: *** [all] Error 2

I'm surprised ld can't handle it, because when I run this version of 'ld' I get the followig output:

/Developer/Cocotron/1.0/FreeBSD/x86_64/gcc-4.3.1/x86_64-pc-freebsd7/bin/ld: supported targets: elf64-x86-64-freebsd elf32-i386-freebsd coff-i386 efi-app-ia32 efi-bsdrv-ia32 efi-rtdrv-ia32 efi-app-x86_64 efi-bsdrv-x86_64 efi-rtdrv-x86_64 elf32-i386 elf64-x86-64 elf64-little elf64-big elf32-little elf32-big srec symbolsrec tekhex binary ihex
/Developer/Cocotron/1.0/FreeBSD/x86_64/gcc-4.3.1/x86_64-pc-freebsd7/bin/ld: supported emulations: elf_x86_64_fbsd elf_i386_fbsd elf_x86_64 elf_i386
/Developer/Cocotron/1.0/FreeBSD/x86_64/gcc-4.3.1/x86_64-pc-freebsd7/bin/ld: emulation specific options:
elf_x86_64_fbsd:

Which indicates to me that I've built the binutils correctly.. yet that can't handle a library that's an ELF 64-bit x86-64 FreeBSD shared object??

To give the story from the start - compiling binutils is flawless it seems.

Compiling GMP and MPFR both give me some ranlib issues that worry me a bit, trying to build up a .a library but the .o files have no symbols.. this could be normal but I can't tell?

GMP:

/usr/bin/ranlib: file: .libs/libprintf.a(obprintf.o) has no symbols
/usr/bin/ranlib: file: .libs/libprintf.a(obvprintf.o) has no symbols
/usr/bin/ranlib: file: .libs/libprintf.a(obprntffuns.o) has no symbols
/usr/bin/ranlib: file: .libs/libprintf.a(repl-vsnprintf.o) has no symbols
ranlib .libs/libprintf.a
ranlib: file: .libs/libprintf.a(obprintf.o) has no symbols
ranlib: file: .libs/libprintf.a(obvprintf.o) has no symbols
ranlib: file: .libs/libprintf.a(obprntffuns.o) has no symbols
ranlib: file: .libs/libprintf.a(repl-vsnprintf.o) has no symbols

And I get some more further along..

ranlib /Developer/Cocotron/1.0/FreeBSD/x86_64/gcc-4.3.1/lib/libgmp.a
ranlib: file: /Developer/Cocotron/1.0/FreeBSD/x86_64/gcc-4.3.1/lib/libgmp.a(mp_clz_tab.o) has no symbols
ranlib: file: /Developer/Cocotron/1.0/FreeBSD/x86_64/gcc-4.3.1/lib/libgmp.a(obprintf.o) has no symbols
ranlib: file: /Developer/Cocotron/1.0/FreeBSD/x86_64/gcc-4.3.1/lib/libgmp.a(obvprintf.o) has no symbols
ranlib: file: /Developer/Cocotron/1.0/FreeBSD/x86_64/gcc-4.3.1/lib/libgmp.a(obprntffuns.o) has no symbols
ranlib: file: /Developer/Cocotron/1.0/FreeBSD/x86_64/gcc-4.3.1/lib/libgmp.a(repl-vsnprintf.o) has no symbols

MPFR:

Similar deal:

/usr/bin/ranlib: file: .libs/libmpfr.a(volatile.o) has no symbols
/usr/bin/ranlib: file: .libs/libmpfr.a(mp_clz_tab.o) has no symbols
/usr/bin/ranlib: file: .libs/libmpfr.a(logging.o) has no symbols
/usr/bin/ranlib: file: .libs/libmpfr.a(set_d64.o) has no symbols
/usr/bin/ranlib: file: .libs/libmpfr.a(get_d64.o) has no symbols
ranlib .libs/libmpfr.a
ranlib: file: .libs/libmpfr.a(volatile.o) has no symbols
ranlib: file: .libs/libmpfr.a(mp_clz_tab.o) has no symbols
ranlib: file: .libs/libmpfr.a(logging.o) has no symbols
ranlib: file: .libs/libmpfr.a(set_d64.o) has no symbols
ranlib: file: .libs/libmpfr.a(get_d64.o) has no symbols
creating libmpfr.la

And a bit further along..

ranlib /Developer/Cocotron/1.0/FreeBSD/x86_64/gcc-4.3.1/lib/libmpfr.a
ranlib: file: /Developer/Cocotron/1.0/FreeBSD/x86_64/gcc-4.3.1/lib/libmpfr.a(volatile.o) has no symbols
ranlib: file: /Developer/Cocotron/1.0/FreeBSD/x86_64/gcc-4.3.1/lib/libmpfr.a(mp_clz_tab.o) has no symbols
ranlib: file: /Developer/Cocotron/1.0/FreeBSD/x86_64/gcc-4.3.1/lib/libmpfr.a(logging.o) has no symbols
ranlib: file: /Developer/Cocotron/1.0/FreeBSD/x86_64/gcc-4.3.1/lib/libmpfr.a(set_d64.o) has no symbols
ranlib: file: /Developer/Cocotron/1.0/FreeBSD/x86_64/gcc-4.3.1/lib/libmpfr.a(get_d64.o) has no symbols

Then we're on to GCC, presumably with good binutils, GMP, and MPFR.. but finally during build of gcc (specifically libgcc) I get the ld linking failure.

Some more supporting information:

I compile binutils using:

CFLAGS="-m32 -Wformat=0 -Wno-error=deprecated-declarations" $sourceFolder/binutils-$binutilsVersion/configure --prefix="$resultFolder" --target=$compilerTarget $binutilsConfigureFlags

However I encounter the same problem if I switch to -m64..

CFLAGS="-m64 -Wformat=0 -Wno-error=deprecated-declarations" $sourceFolder/binutils-$binutilsVersion/configure --prefix="$resultFolder" --target=$compilerTarget $binutilsConfigureFlags

I compile GMP and MPFR using:

ABI=32 $sourceFolder/gmp-$gmpVersion/configure --prefix="$resultFolder"

I compile GCC using:

        CFLAGS="-m32" $sourceFolder/gcc-$gccVersion/configure -v --prefix="$resultFolder" --target=$compilerTarget \
                --with-gnu-as --with-gnu-ld --with-headers=$resultFolder/$compilerTarget/include \
                --without-newlib --disable-multilib --disable-libssp --disable-nls --enable-languages="$enableLanguages" \
                --with-gmp=$buildFolder/gmp-$gmpVersion --enable-decimal-float --with-mpfr=$resultFolder --enable-checking=release \
                --enable-objc-gc \

                $compilerConfigureFlags

For all these, I'm using:

compilerTarget=x86_64-pc-freebsd7
compilerConfigureFlags="--enable-version-specific-runtime-libs --enable-shared --enable-threads=posix --disable-checking --disable-libunwind-exceptions --with-system-zlib --enable-__cxa_atexit"
binutilsConfigureFlags="--enable-64-bit-bfd"

On my target FreeBSD system, which by the way is standard FreeBSD 8.2 RELEASE amd64, ld indicates very similar capabilities to my cross-compiling one.  In fact, it appears that my cross-compiling environment's ld handles a superset of what the actual target's ld handles - making me think I should be able to handle any files without the incompatibility I'm seeing

ld: supported targets: elf64-x86-64 efi-app-ia32 elf32-i386-freebsd srec symbolsrec tekhex binary ihex
ld: supported emulations: elf_i386_fbsd elf_x86_64_fbsd
ld: emulation specific options:
elf_i386_fbsd:


问:
MyUnifiedNativeAd.OnUnifiedNativeAdLoaded (Android.Gms.Ads.Formats.UnifiedNativeAd ad) crash on some devices _ Xamarin.Android
My Xamarin.Android app crashes on some devices
Stacktrace says MyUnifiedNativeAd.OnUnifiedNativeAdLoaded (Android.Gms.Ads.Formats.UnifiedNativeAd ad)

Here is stacktrace

```<code>MyUnifiedNativeAd.OnUnifiedNativeAdLoaded (Android.Gms.Ads.Formats.UnifiedNativeAd ad)
UnifiedNativeAd+IOnUnifiedNativeAdLoadedListenerInvoker.n_OnUnifiedNativeAdLoaded_Lcom_google_android_gms_ads_formats_UnifiedNativeAd_ (System.IntPtr jnienv, System.IntPtr native__this, System.IntPtr native_ad)
(wrapper dynamic-method) Android.Runtime.DynamicMethodNameCounter.26(intptr,intptr,intptr)
</code>```

Here is my code where I do inflate and initializing of Listener

```<code>UnifiedNativeAdView adView = (UnifiedNativeAdView)LayoutInflater.Inflate(Resource.Layout.ad_unified, null);
            FrameLayout frameLayout = inflated.FindViewById<FrameLayout>(Resource.Id.frameLayout1);
            var a = new MyUnifiedNativeAd(adView, frameLayout);
            AdLoader adLoader = new AdLoader.Builder(Context, Resources.GetString(Resource.String.ad_unit_id))
                .ForUnifiedNativeAd(a)
                .WithAdListener(new MyAdListener())
                .Build();
            adLoader.LoadAd(new AdRequest.Builder().Build());
</code>```

This is listener Class which implements IOnUnifiedNativeAdLoadedListener interface

```<code>class MyUnifiedNativeAd : Java.Lang.Object, IOnUnifiedNativeAdLoadedListener
    {
        UnifiedNativeAdView AdView = null;
        FrameLayout frame = null;
        public MyUnifiedNativeAd( UnifiedNativeAdView adv, FrameLayout f)
        {
            AdView = adv;
            frame = f;
        }
        public void OnUnifiedNativeAdLoaded(UnifiedNativeAd ad)
        {
            if (ad is null)
                return;
            MediaView mv = AdView.FindViewById<MediaView>(Resource.Id.ad_media);
            TextView advertiser = AdView.FindViewById<TextView>(Resource.Id.ad_advertiser);
            TextView headline = AdView.FindViewById<TextView>(Resource.Id.ad_headline);
            ImageView img = AdView.FindViewById<ImageView>(Resource.Id.ad_app_icon);
            TextView body = AdView.FindViewById<TextView>(Resource.Id.ad_body);
            RatingBar rating = AdView.FindViewById<RatingBar>(Resource.Id.ad_stars);
            TextView price = AdView.FindViewById<TextView>(Resource.Id.ad_price);
            TextView store = AdView.FindViewById<TextView>(Resource.Id.ad_store);
            Button action = AdView.FindViewById<Button>(Resource.Id.ad_call_to_action);
            List<View> v = new List<View>() { mv, advertiser, headline, img, body, rating, price, store, action };
            action.Text = ad.CallToAction;
            store.Text = ad.Store;
            price.Text = ad.Price;
            rating.NumStars = ad.StarRating is null ? 0 : ad.StarRating.IntValue();
            body.Text = ad.Body;
            img.SetImageDrawable(ad.Icon.Drawable);
            headline.Text = ad.Headline;
            advertiser.Text = ad.Advertiser;
            AdView.MediaView = mv;
            AdView.SetNativeAd(ad);
            frame.RemoveAllViews();
            frame.AddView(AdView);
        }
    }
</code>```

答:
Solved!
Sometimes Google send us ad,which doesn't have icon.
If ad doesn't have icon, it means Icon property is null.
When I tried to set Icon to ImageView, it threw exception </p>

Body:
My Xamarin.Android app crashes on some devices
Stacktrace says MyUnifiedNativeAd.OnUnifiedNativeAdLoaded (Android.Gms.Ads.Formats.UnifiedNativeAd ad)

Here is stacktrace

MyUnifiedNativeAd.OnUnifiedNativeAdLoaded (Android.Gms.Ads.Formats.UnifiedNativeAd ad)
UnifiedNativeAd+IOnUnifiedNativeAdLoadedListenerInvoker.n_OnUnifiedNativeAdLoaded_Lcom_google_android_gms_ads_formats_UnifiedNativeAd_ (System.IntPtr jnienv, System.IntPtr native__this, System.IntPtr native_ad)
(wrapper dynamic-method) Android.Runtime.DynamicMethodNameCounter.26(intptr,intptr,intptr)

Here is my code where I do inflate and initializing of Listener

UnifiedNativeAdView adView = (UnifiedNativeAdView)LayoutInflater.Inflate(Resource.Layout.ad_unified, null);
            FrameLayout frameLayout = inflated.FindViewById<FrameLayout>(Resource.Id.frameLayout1);
            var a = new MyUnifiedNativeAd(adView, frameLayout);
            AdLoader adLoader = new AdLoader.Builder(Context, Resources.GetString(Resource.String.ad_unit_id))
                .ForUnifiedNativeAd(a)
                .WithAdListener(new MyAdListener())
                .Build();
            adLoader.LoadAd(new AdRequest.Builder().Build());

This is listener Class which implements IOnUnifiedNativeAdLoadedListener interface

class MyUnifiedNativeAd : Java.Lang.Object, IOnUnifiedNativeAdLoadedListener
    {
        UnifiedNativeAdView AdView = null;
        FrameLayout frame = null;
        public MyUnifiedNativeAd( UnifiedNativeAdView adv, FrameLayout f)
        {
            AdView = adv;
            frame = f;
        }
        public void OnUnifiedNativeAdLoaded(UnifiedNativeAd ad)
        {
            if (ad is null)
                return;
            MediaView mv = AdView.FindViewById<MediaView>(Resource.Id.ad_media);
            TextView advertiser = AdView.FindViewById<TextView>(Resource.Id.ad_advertiser);
            TextView headline = AdView.FindViewById<TextView>(Resource.Id.ad_headline);
            ImageView img = AdView.FindViewById<ImageView>(Resource.Id.ad_app_icon);
            TextView body = AdView.FindViewById<TextView>(Resource.Id.ad_body);
            RatingBar rating = AdView.FindViewById<RatingBar>(Resource.Id.ad_stars);
            TextView price = AdView.FindViewById<TextView>(Resource.Id.ad_price);
            TextView store = AdView.FindViewById<TextView>(Resource.Id.ad_store);
            Button action = AdView.FindViewById<Button>(Resource.Id.ad_call_to_action);
            List<View> v = new List<View>() { mv, advertiser, headline, img, body, rating, price, store, action };
            action.Text = ad.CallToAction;
            store.Text = ad.Store;
            price.Text = ad.Price;
            rating.NumStars = ad.StarRating is null ? 0 : ad.StarRating.IntValue();
            body.Text = ad.Body;
            img.SetImageDrawable(ad.Icon.Drawable);
            headline.Text = ad.Headline;
            advertiser.Text = ad.Advertiser;
            AdView.MediaView = mv;
            AdView.SetNativeAd(ad);
            frame.RemoveAllViews();
            frame.AddView(AdView);
        }
    }


问:
How to flip a position? strategy.close() and strategy.exit()
i have code:

```<code>strategy(title="StackOverflowExample", overlay=true, slippage=200, commission_type=strategy.commission.percent, commission_value=0.2)
long=crossover(sma(close, 10), sma(close, 20))
close_condition=crossunder(sma(close, 10), sma(close, 20))
stl=strategy.position_avg_price *0.97
strategy.entry("long", true, 1, when = long)
strategy.close("long" , when = close_condition)
strategy.exit("exit", "long", stop=stl, trail_price=strategy.position_avg_price*1.04 ,trail_offset=close*0.03/syminfo.mintick)
</code>```

How to flip a position in both cases? (strategy.close(),strategy.exit())

答:
It strange that qty=2 solved the cases. Exits never flips position. For flip you need opposite entry:</p>

```<code>strategy(title="StackOverflowExample", overlay=true, slippage=200, commission_type=strategy.commission.percent, commission_value=0.2)
long=crossover(sma(close, 10), sma(close, 20))
close_condition=crossunder(sma(close, 10), sma(close, 20))
stl=strategy.position_avg_price *0.97
strategy.entry("long", true, 1, when = long)
strategy.entry("short", false, 1, when = close_condition)
...
</code>```

Body:
i have code:

strategy(title="StackOverflowExample", overlay=true, slippage=200, commission_type=strategy.commission.percent, commission_value=0.2)
long=crossover(sma(close, 10), sma(close, 20))
close_condition=crossunder(sma(close, 10), sma(close, 20))
stl=strategy.position_avg_price *0.97
strategy.entry("long", true, 1, when = long)
strategy.close("long" , when = close_condition)
strategy.exit("exit", "long", stop=stl, trail_price=strategy.position_avg_price*1.04 ,trail_offset=close*0.03/syminfo.mintick)

How to flip a position in both cases? (strategy.close(),strategy.exit())

Body:
It strange that qty=2 solved the cases. Exits never flips position. For flip you need opposite entry:

strategy(title="StackOverflowExample", overlay=true, slippage=200, commission_type=strategy.commission.percent, commission_value=0.2)
long=crossover(sma(close, 10), sma(close, 20))
close_condition=crossunder(sma(close, 10), sma(close, 20))
stl=strategy.position_avg_price *0.97
strategy.entry("long", true, 1, when = long)
strategy.entry("short", false, 1, when = close_condition)
...


问:
Line 0: Parsing error: Cannot read property 'map' of undefined
Currently starting up the server on my client side, the error above is what I have been
getting. I am using TypeScript, ReactJS, ESLint. I can't seem to go forward since this error
has been haunting me. The GitHub page for ESLint hasn't been of much help either.

This error went up after I had created the useMutation component and exported it in index.ts.
Not sure how to get rid of this error.

```<code>Below is my package.json
</code>```
```<code>    {
    "name": "tinyhouse_client",
    "version": "0.1.0",
    "private": true,
      "dependencies": {
      "@testing-library/jest-dom": "^4.2.4",
      "@testing-library/react": "^9.3.2",
      "@testing-library/user-event": "^7.1.2",
      "@types/jest": "^24.0.0",
      "@types/node": "^12.0.0",
      "@types/react": "^16.9.35",
      "@types/react-dom": "^16.9.0",
      "@typescript-eslint/parser": "^3.0.2",
      "react": "^16.13.1",
      "react-dom": "^16.13.1",
      "react-scripts": "3.4.1",
      "typescript": "~2.23.0"
      },
      "resolutions": {
     "@typescript-eslint/eslint-plugin": "^2.23.0",
     "@typescript-eslint/parser": "^2.23.0",
     "@typescript-eslint/typescript-estree": "^2.23.0"
     },
     "scripts": {
     "start": "react-scripts start",
     " build": "react-scripts build",
     "test": "react-scripts test",
     "eject": "react-scripts eject"
     },
     "eslintConfig": {
     "extends": "react-app"
     },
     "browserslist": {
     "production": [
      ">0.2%",
      "not dead",
      "not op_mini all"
    ],
      "development": [
      "last 1 chrome version",
      "last 1 firefox version",
      "last 1 safari version"
     ]
     },
     **strong text** "proxy": "http://localhost:9000"
      }
</code>```
```<code>Below is my index.ts
</code>```
```<code>    export * from './server';
    export * from './useQuery';
    export * from './useMutation';
</code>```
```<code>And my useMutation.ts
</code>```
```<code>    import { useState } from 'react';
    import { server } from './server';

    interface State<TData> {
    data: TData | null;
    loading: boolean;
    error: boolean;
    }

    type MutationTuple<TData, TVariables> = [
    (variables?: TVariables | undefined) => Promise<void>,
    State<TData>
    ];

    export const useMutation = <TData = any, TVariables = any>(
    query: string
    ): MutationTuple<TData, TVariables> => {
    const [state, setState] = useState<State<TData>>({
    data: null,
    loading: false,
    error: false,
    })

    const fetch = async (variables?: TVariables) => {
    try {
      setState({ data: null, loading: true, error: false });

      const { data, errors } = await server.fetch<TData, TVariables>({ query, variables });
      if (errors && errors.length) {
        throw new Error(errors[0].message);
      }

      setState({ data, loading: false, error: false });
    } catch (err) {
      setState({ data: null, loading: false, error: true });
      throw console.error(err);
    }
   }

   return [fetch, state];
};
</code>```

答: Is this coming from eslint-typescript? If so, check that your version of typescript is not a dev/nightly build.</p>

Body:
Currently starting up the server on my client side, the error above is what I have been
getting. I am using TypeScript, ReactJS, ESLint. I can't seem to go forward since this error
has been haunting me. The GitHub page for ESLint hasn't been of much help either.

This error went up after I had created the useMutation component and exported it in index.ts.
Not sure how to get rid of this error.

Below is my package.json

    {
    "name": "tinyhouse_client",
    "version": "0.1.0",
    "private": true,
      "dependencies": {
      "@testing-library/jest-dom": "^4.2.4",
      "@testing-library/react": "^9.3.2",
      "@testing-library/user-event": "^7.1.2",
      "@types/jest": "^24.0.0",
      "@types/node": "^12.0.0",
      "@types/react": "^16.9.35",
      "@types/react-dom": "^16.9.0",
      "@typescript-eslint/parser": "^3.0.2",
      "react": "^16.13.1",
      "react-dom": "^16.13.1",
      "react-scripts": "3.4.1",
      "typescript": "~2.23.0"
      },
      "resolutions": {
     "@typescript-eslint/eslint-plugin": "^2.23.0",
     "@typescript-eslint/parser": "^2.23.0",
     "@typescript-eslint/typescript-estree": "^2.23.0"
     },
     "scripts": {
     "start": "react-scripts start",
     " build": "react-scripts build",
     "test": "react-scripts test",
     "eject": "react-scripts eject"
     },
     "eslintConfig": {
     "extends": "react-app"
     },
     "browserslist": {
     "production": [
      ">0.2%",
      "not dead",
      "not op_mini all"
    ],
      "development": [
      "last 1 chrome version",
      "last 1 firefox version",
      "last 1 safari version"
     ]
     },
     **strong text** "proxy": "http://localhost:9000"
      }

Below is my index.ts

    export * from './server';
    export * from './useQuery';
    export * from './useMutation';

And my useMutation.ts

    import { useState } from 'react';
    import { server } from './server';

    interface State<TData> {
    data: TData | null;
    loading: boolean;
    error: boolean;
    }

    type MutationTuple<TData, TVariables> = [
    (variables?: TVariables | undefined) => Promise<void>,
    State<TData>
    ];

    export const useMutation = <TData = any, TVariables = any>(
    query: string
    ): MutationTuple<TData, TVariables> => {
    const [state, setState] = useState<State<TData>>({
    data: null,
    loading: false,
    error: false,
    })

    const fetch = async (variables?: TVariables) => {
    try {
      setState({ data: null, loading: true, error: false });

      const { data, errors } = await server.fetch<TData, TVariables>({ query, variables });
      if (errors && errors.length) {
        throw new Error(errors[0].message);
      }

      setState({ data, loading: false, error: false });
    } catch (err) {
      setState({ data: null, loading: false, error: true });
      throw console.error(err);
    }
   }

   return [fetch, state];
};


问:
Python: words replacing in huge text
I have a huge text and a list of words ~10K.
What is the fastest way in Python to replace all this words in text with some other word?

EDIT:
Text size >1Gb, text is human written, and "extremely tokenized" (any runs of alphanumeric characters and any other single symbols was splitted into new tokens)

a number of words >10K, each word frequency in text is 1
the replacement word is same in all replacements.
Python 2.5-2.7

答:
Input format and search / replace pairings info is going to necessary to refine this answer if it comes close to start with, but this would be my initial stab at it (assuming some form of regularity in the input data, space delimited in my example code below).

```<code>replacements = {
  's1': 'r1',
  's2': 'r2'
  ...
}

with open('input.txt') as fhi, open('output.txt', 'w') as fho:
  for line in fhi:
    words = line.split(' ')

    fho.write(' '.join(map(lambda w: replacements.get(w, w), words))

    # Or as a list comprehension from the comments.
    fho.write(' '.join([replacements.get(w, w) for w in words]))
</code>```

The idea here is that we'll be relocating data into an output file from an input file.  For each word of each line, we check to see if it's in our replacements dictionary.  We retrieve the new value if it is, or return the word unchanged otherwise via the dict.get(key[, default]) method.  This may not be ideal, doesn't handle punctuation, would probably have trouble on an input file that wasn't broken into lines, etc, but may be a way to get started.

Title: Python: words replacing in huge text

Body:
Input format and search / replace pairings info is going to necessary to refine this answer if it comes close to start with, but this would be my initial stab at it (assuming some form of regularity in the input data, space delimited in my example code below).

replacements = {
  's1': 'r1',
  's2': 'r2'
  ...
}

with open('input.txt') as fhi, open('output.txt', 'w') as fho:
  for line in fhi:
    words = line.split(' ')

    fho.write(' '.join(map(lambda w: replacements.get(w, w), words))

    # Or as a list comprehension from the comments.
    fho.write(' '.join([replacements.get(w, w) for w in words]))

The idea here is that we'll be relocating data into an output file from an input file.  For each word of each line, we check to see if it's in our replacements dictionary.  We retrieve the new value if it is, or return the word unchanged otherwise via the dict.get(key[, default]) method.  This may not be ideal, doesn't handle punctuation, would probably have trouble on an input file that wasn't broken into lines, etc, but may be a way to get started.


问:
Ansible Tower API call using OAuth2 Token from Nodejs App
Can we call Ansible Tower Api by passing only Oauth2 token no username or password?

(Say I want to fetch my inventories from ansible tower by passing only Oauth2 token to my nodejs script. Is that possible?)

If yes, please share syntax of that script.

Script which i have used is giving me correct output but it is using credentials as username and password but i want to do the same task by passing only OAuth2 token(generating from my username and password)

```<code>var unirest = require('unirest');
process.env.NODE_TLS_REJECT_UNAUTHORIZED = '0';
var Request = unirest.get('http://<tower-host>/api/v2/inventories');

Request
   .auth({
    user: 'foo',
    pass: 'bar',
})
   .then(function (response) {
    var data = response.body;
    console.log(data);
  })
</code>```

答:
You can simply pass the authorization token in a header.
Here's an example function:</p>

```<code>const fetch = require('node-fetch');
function job_inventory(tower_url, token) {
    return fetch(tower_url+ "/api/v2/inventories", {
        method: "GET",
        headers: {
            "content-type": "application/json",
            "authorization": "Bearer " + token
        }
    });
}
</code>```

Body:
Can we call Ansible Tower Api by passing only Oauth2 token no username or password?

(Say I want to fetch my inventories from ansible tower by passing only Oauth2 token to my nodejs script. Is that possible?)

If yes, please share syntax of that script.

Script which i have used is giving me correct output but it is using credentials as username and password but i want to do the same task by passing only OAuth2 token(generating from my username and password)

var unirest = require('unirest');
process.env.NODE_TLS_REJECT_UNAUTHORIZED = '0';
var Request = unirest.get('http://<tower-host>/api/v2/inventories');

Request
   .auth({
    user: 'foo',
    pass: 'bar',
})
   .then(function (response) {
    var data = response.body;
    console.log(data);
  })

Body:
You can simply pass the authorization token in a header.
Here's an example function:

const fetch = require('node-fetch');
function job_inventory(tower_url, token) {
    return fetch(tower_url+ "/api/v2/inventories", {
        method: "GET",
        headers: {
            "content-type": "application/json",
            "authorization": "Bearer " + token
        }
    });
}


问:
Unable to copy item from mapped network drive using powershell as file contains wierd characters
I am trying to copy files from mapped network drive.Some of them gets copied but others are not copied as filename has got some wierd characters.

for example my mapped network drive Z: contains the following files:

skifteretsattest 1(1).pdf

MailBody.msg

k�rekort terje(3).pdf

I am able to copy first two files from mapped network drive but not the last one using the below command

```<code>Copy-Item  -LiteralPath Z:\$name  -Destination I:\Dat\SomePath\ss/ -Force
</code>```

The error which I get is:

Copy-Item : Could not find file 'Z:\k�rekort terje(3).pdf

I tried [WildcardPattern]::Escape($name) but that also did not work
Kindly help if anybody knows the solution

答:
Try something like this:</p>

```<code>$files = Get-ChildItem -Path "Z:\"
$files | % { Copy-Item -Destination "I:\Dat\SomePath\ss" }
</code>```

Body:
I am trying to copy files from mapped network drive.Some of them gets copied but others are not copied as filename has got some wierd characters.

for example my mapped network drive Z: contains the following files:

skifteretsattest 1(1).pdf

MailBody.msg

k�rekort terje(3).pdf

I am able to copy first two files from mapped network drive but not the last one using the below command

Copy-Item  -LiteralPath Z:\$name  -Destination I:\Dat\SomePath\ss/ -Force

The error which I get is:

Copy-Item : Could not find file 'Z:\k�rekort terje(3).pdf

I tried [WildcardPattern]::Escape($name) but that also did not work
Kindly help if anybody knows the solution

Body:
Try something like this:

$files = Get-ChildItem -Path "Z:\"
$files | % { Copy-Item -Destination "I:\Dat\SomePath\ss" }


问:
Can't plot a chart with matplotlib
I have this code, and it's supposed to plot me a chart with a number, but it won't work. And I don't get any error

```<code>import numpy
import matplotlib.pyplot

# %matplotlib inline
all_values = data_list[0].split(',')
image_array = numpy.asfarray(all_values[1:]).reshape((28, 28))
matplotlib.pyplot.imshow(image_array, cmap='Greys', interpolation='None')
plt.show(image_array, cmap='Greys', interpolation='None')
scaled_input = (numpy.asfarray(all_values[1:]) / 255.0 * 0.99) + 0.1
print (scaled_input)
</code>```

Thank you for your answers!

答:
Your code should not even run:

all_values = data_list[0].split(',') should give NameError: data_list undefined

plt.show should give NameError: plt undefined

plt.show(image_array, cmap='Greys', interpolation='None') should give TypeError: got an unexpected keyword argument 'cmap'

My guess is that your code did not run at all... In PyCharm, you should be able to right click on your script and click on run script or something

Title: Can't plot a chart with matplotlib

Body:
I have this code, and it's supposed to plot me a chart with a number, but it won't work. And I don't get any error

import numpy
import matplotlib.pyplot

# %matplotlib inline
all_values = data_list[0].split(',')
image_array = numpy.asfarray(all_values[1:]).reshape((28, 28))
matplotlib.pyplot.imshow(image_array, cmap='Greys', interpolation='None')
plt.show(image_array, cmap='Greys', interpolation='None')
scaled_input = (numpy.asfarray(all_values[1:]) / 255.0 * 0.99) + 0.1
print (scaled_input)

Thank you for your answers!


问:
How to use edit an environment object from a class function?
I am new to swift programming. I was trying to play around with the environment object to update views by changing the value of the environment object specifically via a class function.
I have two subviews in the contentview as I wish to see if both subviews get updated together when the string gets changed in UserData environment object.

However, there's an error saying 'Thread 1: Fatal error: No ObservableObject of type UserData found. A View.environmentObject(_:) for UserData may be missing ...'

In SceneDelagate.swift, I have injected the environment object:

```<code>let userData = UserData()

window.rootViewController = UIHostingController(rootView:contentView.environmentObject(userData))
</code>```

UserData.swift

```<code>final class UserData: ObservableObject {

    @Published var image: UIImage? = nil
    @Published var string  = ""

}
</code>```

StringGenerator.swift

```<code>class StringGenerator {

    @EnvironmentObject var userData: UserData

    func changeURL(){
        print("Changing string now from \(userData.string)")
        if self.userData.string == "HELLO"{
            self.userData.string = "BYE"

        }
        else{
            self.userData.string = "HELLO"
        }
        print("to \(userData.string)")
    }
}
</code>```

SubView1.swift

```<code>struct SubView1: View {
    @EnvironmentObject var userData: UserData

    var body: some View {
        Text("\(userData.string)")

    }
}
</code>```

SubView2.swift

```<code>struct SubView2: View {
    @EnvironmentObject var userData: UserData

    var body: some View {
        Text("\(userData.string)")

    }
}
</code>```

ContentView.swift

```<code>struct ContentView: View {
    @EnvironmentObject var userData: UserData

    let stringGenerator = StringGenerator()

    var body: some View {

        VStack{

            Button(action: {
                print("Changing Text Now !")
                self.stringGenerator.changeURL()
                print("\(self.userData.string)")
            }) {
                Text("Change Text ")
            }

            SubView1()
            SubView2()

        }

    }
}
</code>```

In general, I wish to know how does one change the environment object via a class function.

The code crashes when I run it. What's the problem in here?

答:
Here is a solution:

1) in ContentView

```<code>struct ContentView: View {
    @EnvironmentObject var userData: UserData

    let stringGenerator: StringGenerator   // declare-only
</code>```

2) in generator

```<code>class StringGenerator {

    var userData: UserData   // just member
    init(userData: UserData) {
      self.userData = userData
    }
</code>```

3) in SceneDelegate

```<code>let userData = UserData()

// inject generator via constructor with same user data
let contentView = ContentView(stringGenerator:
                              StringGenerator(userData: userData))

window.rootViewController = UIHostingController(rootView:
                              contentView.environmentObject(userData))
</code>```

Body:
I am new to swift programming. I was trying to play around with the environment object to update views by changing the value of the environment object specifically via a class function.
I have two subviews in the contentview as I wish to see if both subviews get updated together when the string gets changed in UserData environment object.

However, there's an error saying 'Thread 1: Fatal error: No ObservableObject of type UserData found. A View.environmentObject(_:) for UserData may be missing ...'

In SceneDelagate.swift, I have injected the environment object:

let userData = UserData()

window.rootViewController = UIHostingController(rootView:contentView.environmentObject(userData))

UserData.swift

final class UserData: ObservableObject {

    @Published var image: UIImage? = nil
    @Published var string  = ""

}

StringGenerator.swift

class StringGenerator {

    @EnvironmentObject var userData: UserData

    func changeURL(){
        print("Changing string now from \(userData.string)")
        if self.userData.string == "HELLO"{
            self.userData.string = "BYE"

        }
        else{
            self.userData.string = "HELLO"
        }
        print("to \(userData.string)")
    }
}

SubView1.swift

struct SubView1: View {
    @EnvironmentObject var userData: UserData

    var body: some View {
        Text("\(userData.string)")

    }
}

SubView2.swift

struct SubView2: View {
    @EnvironmentObject var userData: UserData

    var body: some View {
        Text("\(userData.string)")

    }
}

ContentView.swift

struct ContentView: View {
    @EnvironmentObject var userData: UserData

    let stringGenerator = StringGenerator()

    var body: some View {

        VStack{

            Button(action: {
                print("Changing Text Now !")
                self.stringGenerator.changeURL()
                print("\(self.userData.string)")
            }) {
                Text("Change Text ")
            }

            SubView1()
            SubView2()

        }

    }
}

In general, I wish to know how does one change the environment object via a class function.

The code crashes when I run it. What's the problem in here?

Body:
Here is a solution:

1) in ContentView

struct ContentView: View {
    @EnvironmentObject var userData: UserData

    let stringGenerator: StringGenerator   // declare-only

2) in generator

class StringGenerator {

    var userData: UserData   // just member
    init(userData: UserData) {
      self.userData = userData
    }

3) in SceneDelegate

let userData = UserData()

// inject generator via constructor with same user data
let contentView = ContentView(stringGenerator:
                              StringGenerator(userData: userData))

window.rootViewController = UIHostingController(rootView:
                              contentView.environmentObject(userData))


问:
java.lang.NoSuchMethodError: java.lang.NoSuchMethodError
Running Tomcat 7 through eclipse
The error reported is:

```<code>javax.servlet.ServletException: java.lang.NoSuchMethodError: org.eclipse.jdt.internal.compiler.CompilationResult.getProblems()[Lorg/eclipse/jdt/core/compiler/IProblem;
at org.apache.jasper.compiler.JDTCompiler$2.acceptResult(JDTCompiler.java:341)
</code>```

I have tried both jasper-jdt-6.0.13.jar and tomcat-6.0.16-jasper-jdt.jar and both report the same error. In a way I shouldn't be surprised because I ran:

```<code>jar tf tomcat-6.0.16-jasper-jdt.jar
</code>```

and it doesn't have the class org.eclipse.jdt.internal.compiler.CompilationResult in it. But this site http://www.java2s.com/Code/Jar/STUVWXYZ/Downloadtomcat6016jasperjdtjar.htm says it does!!

Can someone tell me what the correct jar file is and where to get it from?
It seems to be a recurring theme. http://www.findjar.com lists a number of jars that purport to have this class - but do not.

OK, Found it in jasper-compiler-jdt-5.5.23.jar

答: Found it in jasper-compiler-jdt-5.5.23.jar</p>

Body:
Running Tomcat 7 through eclipse
The error reported is:

javax.servlet.ServletException: java.lang.NoSuchMethodError: org.eclipse.jdt.internal.compiler.CompilationResult.getProblems()[Lorg/eclipse/jdt/core/compiler/IProblem;
at org.apache.jasper.compiler.JDTCompiler$2.acceptResult(JDTCompiler.java:341)

I have tried both jasper-jdt-6.0.13.jar and tomcat-6.0.16-jasper-jdt.jar and both report the same error. In a way I shouldn't be surprised because I ran:

jar tf tomcat-6.0.16-jasper-jdt.jar

and it doesn't have the class org.eclipse.jdt.internal.compiler.CompilationResult in it. But this site http://www.java2s.com/Code/Jar/STUVWXYZ/Downloadtomcat6016jasperjdtjar.htm says it does!!

Can someone tell me what the correct jar file is and where to get it from?
It seems to be a recurring theme. http://www.findjar.com lists a number of jars that purport to have this class - but do not.

OK, Found it in jasper-compiler-jdt-5.5.23.jar