问:
Performing df.map() or df.merge() against a single <str> value to return a <float>
I am trying to create a list of 5 letter words in a pandas dataframe, which splits the word into different columns and assigns a value to each letter, then performs a summation of the values. The following code imports a .json dictionary and assigns values to a letter:

```<code>import json
import pandas as pd

def split(word):
    return [char for char in word]

j = open('words_dictionary.json')
dictionary = json.load(j)

dictionary_db = pd.DataFrame(columns=['Word'])
letter_db = pd.DataFrame(columns=['Letter'])

word_count = 0
num_word_count = 0
letter_count = 0

for i in dictionary:
    word_count += 1
    if len(i) == 5:
        dictionary1_db = pd.DataFrame({i}, columns=['Word'])
        dictionary_db = pd.concat([dictionary1_db, dictionary_db], ignore_index=True, axis=0)
        num_word_count += 1
        split_word = split(i)
        L1 = split_word[0]
        L2 = split_word[1]
        L3 = split_word[2]
        L4 = split_word[3]
        L5 = split_word[4]

        for s in split_word:
            letter_count += 1
            letter1_db = pd.DataFrame({s}, columns=['Letter'])
            letter_db = pd.concat([letter_db, letter1_db], ignore_index=True, axis=0)

grouped = letter_db.groupby('Letter').value_counts()
grouped_db = pd.DataFrame(grouped, columns=['Value'])
grouped_db = grouped_db.apply(lambda x: (x/num_word_count)*.2, axis=1)
grouped_dict = grouped_db.to_dict()
</code>```

Resulting in a grouped_db of:

Letter
Value

0
a
0.10544

1
b
0.02625

2
c
0.03448

..
..
..

as well as a similar dictionary:

```<code>grouped_dict = {'a': 0.10544, 'b': 0.02625, 'c': 0.03448, ...}
</code>```

My problems start to occur when I try to map the string value to the float value.

How would I go about either merging a float value to the specified letter key or mapping a dictionary float value to the specified letter key without causing an 'NaN' value error?

ATTEMPT 1:

```<code>df = pd.DataFrame([{'L1': 'a'}])
df['L1Val'] = df['L1'].map(grouped_dict)
</code>```

df:

L1
L1Val

0
a
nan

intended df output:

L1
L1Val

0
a
.10544

答:
You can merge the both dataframes as follows:

df.merge(grouped_db, left_on="L1", right_on="Letter")
```

The columns L1 and Letter will be redundant but you can filter one out afterwards.

Body:
I am trying to create a list of 5 letter words in a pandas dataframe, which splits the word into different columns and assigns a value to each letter, then performs a summation of the values. The following code imports a .json dictionary and assigns values to a letter:

import json
import pandas as pd

def split(word):
    return [char for char in word]

j = open('words_dictionary.json')
dictionary = json.load(j)

dictionary_db = pd.DataFrame(columns=['Word'])
letter_db = pd.DataFrame(columns=['Letter'])

word_count = 0
num_word_count = 0
letter_count = 0

for i in dictionary:
    word_count += 1
    if len(i) == 5:
        dictionary1_db = pd.DataFrame({i}, columns=['Word'])
        dictionary_db = pd.concat([dictionary1_db, dictionary_db], ignore_index=True, axis=0)
        num_word_count += 1
        split_word = split(i)
        L1 = split_word[0]
        L2 = split_word[1]
        L3 = split_word[2]
        L4 = split_word[3]
        L5 = split_word[4]

        for s in split_word:
            letter_count += 1
            letter1_db = pd.DataFrame({s}, columns=['Letter'])
            letter_db = pd.concat([letter_db, letter1_db], ignore_index=True, axis=0)

grouped = letter_db.groupby('Letter').value_counts()
grouped_db = pd.DataFrame(grouped, columns=['Value'])
grouped_db = grouped_db.apply(lambda x: (x/num_word_count)*.2, axis=1)
grouped_dict = grouped_db.to_dict()

Resulting in a grouped_db of:

Letter
Value

0
a
0.10544

1
b
0.02625

2
c
0.03448

..
..
..

as well as a similar dictionary:

grouped_dict = {'a': 0.10544, 'b': 0.02625, 'c': 0.03448, ...}

My problems start to occur when I try to map the string value to the float value.

How would I go about either merging a float value to the specified letter key or mapping a dictionary float value to the specified letter key without causing an 'NaN' value error?

ATTEMPT 1:

df = pd.DataFrame([{'L1': 'a'}])
df['L1Val'] = df['L1'].map(grouped_dict)

df:

L1
L1Val

0
a
nan

intended df output:

L1
L1Val

0
a
.10544

Body:
You can merge the both dataframes as follows:

df.merge(grouped_db, left_on="L1", right_on="Letter")

The columns L1 and Letter will be redundant but you can filter one out afterwards.


来源: stackexchange

问:
Query to return data from SQL Server table based on date criteria
I have the following piece of code in C# that I use to select some rows from a SQL Server table based on a date criteria.

```<code>DateTime From, DateTime To
SqlParameter[] oParam = new SqlParameter[3];
oParam[0] = new SqlParameter("@From", From.Date);
oParam[1] = new SqlParameter("@To", To.Date);
DataTable dt = clsDatabaseHistory.ExecuteReader("SELECT * FROM tblHistory WHERE Date_Requested BETWEEN @From and @To", oParam);
</code>```

If for example From=18/08/2011 and To=18/08/2011 and there is data in the table tblHistory that has the Date_Requested value as 18/08/2011 the query does not return it.

But if I change the value of To from 18/08/2011 to To=19/08/2011 the query returns me all the values from the table that have a Date_Requested value of 18/08/2011, but none from the 19/08/2011.

How can something like that be possible and what query should I use to return rows where the date field is between date1 and date2.

Something like :

```<code>select * rows where datevalue >= date1 and datevalue <= date2
</code>```

Thank you.

答:
You need to account for time (not just date).  One way I handle that is like this:

```<code>SELECT
...
WHERE CONVERT(varchar(8), date_begin, 112) <= convert(varchar(8), @to, 112)
</code>```

This converts dates to YYYYMMDD format (with no time), which is very easy to use in <, >, = comparrisons.

ContentLicense: CC BY-SA 3.0

Body:
I have the following piece of code in C# that I use to select some rows from a SQL Server table based on a date criteria.

DateTime From, DateTime To
SqlParameter[] oParam = new SqlParameter[3];
oParam[0] = new SqlParameter("@From", From.Date);
oParam[1] = new SqlParameter("@To", To.Date);
DataTable dt = clsDatabaseHistory.ExecuteReader("SELECT * FROM tblHistory WHERE Date_Requested BETWEEN @From and @To", oParam);

If for example From=18/08/2011 and To=18/08/2011 and there is data in the table tblHistory that has the Date_Requested value as 18/08/2011 the query does not return it.

But if I change the value of To from 18/08/2011 to To=19/08/2011 the query returns me all the values from the table that have a Date_Requested value of 18/08/2011, but none from the 19/08/2011.

How can something like that be possible and what query should I use to return rows where the date field is between date1 and date2.

Something like :

select * rows where datevalue >= date1 and datevalue <= date2

Thank you.

Body:
You need to account for time (not just date).  One way I handle that is like this:

SELECT
...
WHERE CONVERT(varchar(8), date_begin, 112) <= convert(varchar(8), @to, 112)

This converts dates to YYYYMMDD format (with no time), which is very easy to use in <, >, = comparrisons.


答:
This was a really hard one for me to track down.

What it came down to: This would only occur when I was running on a low spec device (Galaxy A12). I had a hook that looked like this:

```<code>  const [state, setState] = useState(1);
  useEffect(() => {
    const t = setInterval(
      () => setState(valueGoesHere),
      200,
    );
    return () => clearInterval(t);
  }, []);
</code>```

To poll a value.

This worked fine on higher spec'd phones but it caused the excessive promise issue. You should comb your code for anything like the above snippet, especially using setInterval as it will bank up promises and not allow prior ones time to finish before dispatch.

ContentLicense: CC BY-SA 4.0

Body:
In my react-native project, I am getting the following error message:

Warning: Please report: Excessive number of pending callbacks: 501. Some pending callbacks that might have leaked by never being called from native code:

{"203":{"module":"MyModule","method":"startProcessing"},"276":{"module":"RNFetchBlob","method":"emitExpiredEvent"},"1855":{},"1856":{},"1857":{},"1858":{},"1859":{},"1860":{},"1861":{},"1862":{},"1863":{},"1864":{},"1865":{},"1866":{},"1867":{},"1868":{},"1869":{},"1870":{},"1871":{},"1872":{},"1873":{},"1874":{},"1875":{},"1876":{},"1877":{},"1878":{},"1879":{},"1880":{},"1881":{},"1882":{},"1883":{},"1884":{},"1885":{},"1886":{},"1887":{},"1888":{},"1889":{},"1890":{},"1891":{},"1892":{},"1893":{},"1894":{},"1895":{},"1896":{},"1897":{},"1898":{},"1899":{},"1900":{},"1901":{},"1902":{},"...(truncated keys)...":451}

Can anyone tell me what module all of these callbacks are coming from or how to interpret this message?

Body:
This was a really hard one for me to track down.

What it came down to: This would only occur when I was running on a low spec device (Galaxy A12). I had a hook that looked like this:

  const [state, setState] = useState(1);
  useEffect(() => {
    const t = setInterval(
      () => setState(valueGoesHere),
      200,
    );
    return () => clearInterval(t);
  }, []);

To poll a value.

This worked fine on higher spec'd phones but it caused the excessive promise issue. You should comb your code for anything like the above snippet, especially using setInterval as it will bank up promises and not allow prior ones time to finish before dispatch.


问:
Execute function once earlier process is completed in react
live.js

```<code>const [report, setReport] = useState([]);
const [result, setResult] = useState([]);

useEffect(() => {
  pose.onResults(onResults);  => pose runs every second which runs onResults function every second
}, []);

const onResults = async () => {
  setResult(results.poseLandmarks); ==> It set above state name result
};

useEffect(() => {
   updateReport(); ==> as result state update this runs function updateReport
}, [result]);

const updateReport = async (result) => {
  let reportData = [...report];
  let updatedReport = [];
  let saveReport = [];
  if (report.length > 99) {
    saveReport = reportData.slice(0, 100);
    let body = {
     room_id: roomId,
     formatReport: {
      "frames": saveReport
     },
     session: sessionId
   };
   reportData.splice(0, 100);
   await awsUpload(body.formatReport, body.room_id); ==> This function uploads file to aws
}
reportData.push(updatedReport);
setReport(reportData); ===> It set in report state
</code>```

}

onResult is running at each second I want once updateReport function runs it must complete all its execution before running again but before completing execution it runs again as result state which is dependency is updating at each second

答:
You could introduce a flag to track wether updateReport is currently already running:

```<code>const [isUpdatingReport, setIsUpdatingReport] = useState(false);
</code>```

And then in onResult only call updateReport if it's not currently running:

```<code>const onResults = async () => {
  setResult(results.poseLandmarks);
  if (!isUpdatingReport) {
    setIsUpdatingReport(true);
    updateReport();
  }
};
</code>```

In addition, at the end of all the async stuff in updateReport, make sure to signal that the work is done with

```<code>const updateReport = async (result) => {
  // ...
  setIsUpdatingReport(false);
};
</code>```

This way there will only be one report being updated at the same time.

Some other thoughts on your code:

updateReport has one argument (result) in your snippet but gets called without arguments. Maybe something missing?

Do you really need result to be a state variable? It seems that its only purpose is to be processed by updateReport. If that is true you could simply pass it to the function. But maybe it gets rendered in the component, don't know.

Body:
live.js

const [report, setReport] = useState([]);
const [result, setResult] = useState([]);

useEffect(() => {
  pose.onResults(onResults);  => pose runs every second which runs onResults function every second
}, []);

const onResults = async () => {
  setResult(results.poseLandmarks); ==> It set above state name result
};

useEffect(() => {
   updateReport(); ==> as result state update this runs function updateReport
}, [result]);

const updateReport = async (result) => {
  let reportData = [...report];
  let updatedReport = [];
  let saveReport = [];
  if (report.length > 99) {
    saveReport = reportData.slice(0, 100);
    let body = {
     room_id: roomId,
     formatReport: {
      "frames": saveReport
     },
     session: sessionId
   };
   reportData.splice(0, 100);
   await awsUpload(body.formatReport, body.room_id); ==> This function uploads file to aws
}
reportData.push(updatedReport);
setReport(reportData); ===> It set in report state

}

onResult is running at each second I want once updateReport function runs it must complete all its execution before running again but before completing execution it runs again as result state which is dependency is updating at each second

Body:
You could introduce a flag to track wether updateReport is currently already running:

const [isUpdatingReport, setIsUpdatingReport] = useState(false);

And then in onResult only call updateReport if it's not currently running:

const onResults = async () => {
  setResult(results.poseLandmarks);
  if (!isUpdatingReport) {
    setIsUpdatingReport(true);
    updateReport();
  }
};

In addition, at the end of all the async stuff in updateReport, make sure to signal that the work is done with

const updateReport = async (result) => {
  // ...
  setIsUpdatingReport(false);
};

This way there will only be one report being updated at the same time.

Some other thoughts on your code:

updateReport has one argument (result) in your snippet but gets called without arguments. Maybe something missing?

Do you really need result to be a state variable? It seems that its only purpose is to be processed by updateReport. If that is true you could simply pass it to the function. But maybe it gets rendered in the component, don't know.


问:
Can a snakemake rule depend on data in the file instead of its change state
I have data in a CSV file that frequently changes. The CSV file is a source for a snakefile rule. My issue is that I want this rule to run only when a certain value appears in the data of the CSV file and not every time when the file changes. Is it possible to let rule execution depend on specific patterns in the file that has changed and not on the fact that it changed?</p>

答:
The specific check that Snakemake does to determine if a rule should be re-executed is based on timestamps (not file content), so first thing to do is to wrap relevant files in ancient.

Next, since the Snakefile is a Python file, it's possible to incorporate the required logic using pandas or some other library for handling csvs. Below is a rough idea:

import pandas as pd
csv_file = 'some_file.txt'
df = pd.read_csv(csv_file)
items_to_do = df.query('column_x>=10')['column_y'].values.tolist()

rule all:
    input: expand('file_out_{y}.txt', y=items_to_do)

rule some_rule:
    input: ancient('test.csv')
    output: 'file_out_{y}.txt'
    ... # code to generate the file
```
<p>So if you update <code>some_file.txt</code>, but the values that are updated are associated with <code>column_x</code> being less than 10, then no new jobs will be executed.</p>
<p>Update: I assumed that the rule in question generates multiple files using wildcards, but re-reading the question this doesn't seem to be the case. If it's just a single rule, then the snippet above can be modified to work along these lines:</p>
<pre class="lang-py prettyprint-override"><code>import pandas as pd
csv_file = 'some_file.txt'

def file_is_updated():
    df = pd.read_csv(csv_file)
    # implement logic to decide if the rule should be re-run
    # e.g. set to True if len() > 50
    needs_updating = True if len(df)>50 else False
    return needs_updating

# use python to execute conditionally
if file_is_updated():
    rule some_rule:
        input: csv_file
        ...
</code>```

Body:
The specific check that Snakemake does to determine if a rule should be re-executed is based on timestamps (not file content), so first thing to do is to wrap relevant files in ancient.

Next, since the Snakefile is a Python file, it's possible to incorporate the required logic using pandas or some other library for handling csvs. Below is a rough idea:

import pandas as pd
csv_file = 'some_file.txt'
df = pd.read_csv(csv_file)
items_to_do = df.query('column_x>=10')['column_y'].values.tolist()

rule all:
    input: expand('file_out_{y}.txt', y=items_to_do)

rule some_rule:
    input: ancient('test.csv')
    output: 'file_out_{y}.txt'
    ... # code to generate the file

So if you update some_file.txt, but the values that are updated are associated with column_x being less than 10, then no new jobs will be executed.

Update: I assumed that the rule in question generates multiple files using wildcards, but re-reading the question this doesn't seem to be the case. If it's just a single rule, then the snippet above can be modified to work along these lines:

import pandas as pd
csv_file = 'some_file.txt'

def file_is_updated():
    df = pd.read_csv(csv_file)
    # implement logic to decide if the rule should be re-run
    # e.g. set to True if len() > 50
    needs_updating = True if len(df)>50 else False
    return needs_updating

# use python to execute conditionally
if file_is_updated():
    rule some_rule:
        input: csv_file
        ...


问:
malformed or corrupted AST file: 'Unable to load module "/Library/Developer/Xcode/DerivedData/ModuleCache/34OBPFY26OANR/Darwin.pcm": file not found'
I am using OSX 10.9.3 in my Mac Mini and XCode 5.0.2.
When I execute my project as iPhone retina (3.5 inch) and iPhone retina (4.0 inch) it executes smoothly without any errors but if I want to execute on iPhone retina (4-inch 64-bit), when I select this simulator there is a fatal error:

malformed or corrupted AST file: 'Unable to load module "/Users/WeMitedMacMini1/Library/Developer/Xcode/DerivedData/ModuleCache/34OBPFY26OANR/Darwin.pcm": file not found'.

So I am not understanding for which file Darwin.pcm it generates an error. As far I know I did not use any file named Darwin.pcm. Please help me with this error.

答: In my case, the issue is solved when I delete the product file</p>


问:
How to associate a work item with a test result using the Azure DevOps API?
I have read through the docs, but I still cannot figure out how a custom Azure DevOps task can associate a test result with a work item programmatically. I built a custom task that executes tests (running and executing outside Azure DevOps). When the tests finish and the results come back, I get the list of associated work items as well. I would like to call the appropriate Azure DevOps API to associate the test result with one or more work items. Any pointers would be welcome.

答:
Check this extension that I have created https://github.com/JanuszNowak/janono.ado.testcase.associate.cli
it allows associating in automatic manner. Code sample:

```<code>namespace ExampleTestProject
{
    [TestClass]
    [janono.ado.testcase.associate.Organization("janono-pub")]
    public class UnitTest1
    {
        [TestMethod]
        [janono.ado.testcase.associate.TestCase(5)] //<---
        public void TestMethod1()
        {
            //yours test method content
            //...
            //
        }
    }
}
</code>```

Body:
Check this extension that I have created https://github.com/JanuszNowak/janono.ado.testcase.associate.cli
it allows associating in automatic manner. Code sample:

namespace ExampleTestProject
{
    [TestClass]
    [janono.ado.testcase.associate.Organization("janono-pub")]
    public class UnitTest1
    {
        [TestMethod]
        [janono.ado.testcase.associate.TestCase(5)] //<---
        public void TestMethod1()
        {
            //yours test method content
            //...
            //
        }
    }
}


问:
How to compute the mean with null treated as zero
In Snowflake how can I return the mean of a column, where null values are treated as zero. So, if we have 3 values: 1, 2, NULL, I would like to return 1, not 1.5 as returned by AVG function.</p>

答:
Using ZEROIFNULL function:

Returns 0 if its argument is null; otherwise, returns its argument.

```<code>SELECT AVG(ZEROIFNULL(col_name))
FROM tab;
</code>```

Body:
Using ZEROIFNULL function:

Returns 0 if its argument is null; otherwise, returns its argument.

SELECT AVG(ZEROIFNULL(col_name))
FROM tab;


问:
Show JSON data objects in React Native
I'm working on a little project which related to connecting API's on React Native. In that, I got a JSON data object like this.

```<code>{
  success: 1,
  data: {
    monthly_income: {
      0: {
        en: 'Below Ten Thousand',
        expect_en: 'Neglected',
      },
      10000: {
        en: 'Above Ten Thousand',
      },
      25000: {
        en: 'Above Twenty Thousand',
      },
      50000: {
        en: 'Above Fifty Thousand',
      },
      75000: {
        en: 'Above Seventy Five Thousand',
      },
      100000: {
        en: 'Above Hundred Thousand',
      },
    },
    height: {
      5: {
        en: '5 Feet',
      },
      5.1: {
        en: '5 Feet and 1 Inches',
      },
      5.2: {
        en: '5 Feet and 2 Inches',
      },
      5.3: {
        en: '5 Feet and 3 Inches',
      },
      5.4: {
        en: '5 Feet and 4 Inches',
      },
      5.5: {
        en: '5 Feet and 5 Inches',
      },
      5.6: {
        en: '5 Feet and 6 Inches',
      },
      5.7: {
        en: '5 Feet and 7 Inches',
      },
      5.8: {
        en: '5 Feet and 8 Inches',
      },
      5.9: {
        en: '5 Feet and 9 Inches',
      },
      '5.10': {
        en: '5 Feet and 10 Inches',
      },
      5.11: {
        en: '5 Feet and 11 Inches',
      },
      6: {
        en: '6 Feet',
      },
    },
  },
};
</code>```

I wanted to display above data in a React Native picker in separately, like a Monthly Income in one picker & Height in another picker. I tried using map method to do that, but I couldn't  access to the data inside this. My questions are,

Can we use map method to access these kinds of JSON objects?

If we can, what is the best way to do that?

If can't, please suggest the way to do that work

答:
You need to turn this into an array to be able to map it.

Try something like:

```<code>{Object.keys(JSON_NAME.data.monthly_income).map((key) => {
  return <Text>JSON_NAME.data.monthly_Income[key] </Text>
})}
</code>```

Title: Show JSON data objects in React Native

Body:
I'm working on a little project which related to connecting API's on React Native. In that, I got a JSON data object like this.

{
  success: 1,
  data: {
    monthly_income: {
      0: {
        en: 'Below Ten Thousand',
        expect_en: 'Neglected',
      },
      10000: {
        en: 'Above Ten Thousand',
      },
      25000: {
        en: 'Above Twenty Thousand',
      },
      50000: {
        en: 'Above Fifty Thousand',
      },
      75000: {
        en: 'Above Seventy Five Thousand',
      },
      100000: {
        en: 'Above Hundred Thousand',
      },
    },
    height: {
      5: {
        en: '5 Feet',
      },
      5.1: {
        en: '5 Feet and 1 Inches',
      },
      5.2: {
        en: '5 Feet and 2 Inches',
      },
      5.3: {
        en: '5 Feet and 3 Inches',
      },
      5.4: {
        en: '5 Feet and 4 Inches',
      },
      5.5: {
        en: '5 Feet and 5 Inches',
      },
      5.6: {
        en: '5 Feet and 6 Inches',
      },
      5.7: {
        en: '5 Feet and 7 Inches',
      },
      5.8: {
        en: '5 Feet and 8 Inches',
      },
      5.9: {
        en: '5 Feet and 9 Inches',
      },
      '5.10': {
        en: '5 Feet and 10 Inches',
      },
      5.11: {
        en: '5 Feet and 11 Inches',
      },
      6: {
        en: '6 Feet',
      },
    },
  },
};

I wanted to display above data in a React Native picker in separately, like a Monthly Income in one picker & Height in another picker. I tried using map method to do that, but I couldn't  access to the data inside this. My questions are,

Can we use map method to access these kinds of JSON objects?

If we can, what is the best way to do that?

If can't, please suggest the way to do that work

Body:
You need to turn this into an array to be able to map it.

Try something like:

{Object.keys(JSON_NAME.data.monthly_income).map((key) => {
  return <Text>JSON_NAME.data.monthly_Income[key] </Text>
})}


问:
Image Replacement Script (jQuery)
I'm building an employee bios page where the client wants selected thumbnails to display in color at full opacity and all others at lower opacity in black and white. Which wouldn't be hard - the trouble is, every thumbnail has to have a color state and a black and white state. So my next thought was to swap out the black and white image (which would be resting within the div with a color background image) on mouseover.

```<code>$('.thumbnail').mouseenter(function(){
    var current = $(this); // cache thing
    var thishtml = current.html(); // get contents of thing
    current.html('').mouseleave(function(){ //empty the thing
        current.html(thishtml); //put the variable back in the thing
        });
});
</code>```

My HTML would be as follows:

```<code><div class = "thumbnail" style = "background-image: url(color.jpg);">
<img src="blackandwhite.jpg" />
</div>
</code>```

Obviously, since I'm asking the question, my idea didn't work. The mouseover removes the innerHTML, and the variable is converted successfully, but it doesn't get inserted into the DIV again. What am I missing?

答:
Why not trying using the show and hide methods?  Be sure to specify a width for the containing divs, or the entire thing will disappear when hiding or showing.  I'm guessing the thumbnails are all the same size, so it will be easy to add CSS such as:

CSS:

```<code>.thumbnail
{
   width: 100px;
   height; 100px;
}
</code>```

Javascript

```<code>$(document).ready(function()
{
   $('img', '.thumbnail').hide();//Start off hidden
   $('.thumbnail').mouseenter(function()
   {
      $('img', this).show();
   });
   $('.thumbnail').mouseleave(function()
   {
      $('img', this).hide();
   });
});
</code>```

Title: Image Replacement Script (jQuery)

Body:
I'm building an employee bios page where the client wants selected thumbnails to display in color at full opacity and all others at lower opacity in black and white. Which wouldn't be hard - the trouble is, every thumbnail has to have a color state and a black and white state. So my next thought was to swap out the black and white image (which would be resting within the div with a color background image) on mouseover.

$('.thumbnail').mouseenter(function(){
    var current = $(this); // cache thing
    var thishtml = current.html(); // get contents of thing
    current.html('').mouseleave(function(){ //empty the thing
        current.html(thishtml); //put the variable back in the thing
        });
});

My HTML would be as follows:

Obviously, since I'm asking the question, my idea didn't work. The mouseover removes the innerHTML, and the variable is converted successfully, but it doesn't get inserted into the DIV again. What am I missing?

Body:
Why not trying using the show and hide methods?  Be sure to specify a width for the containing divs, or the entire thing will disappear when hiding or showing.  I'm guessing the thumbnails are all the same size, so it will be easy to add CSS such as:

CSS:

.thumbnail
{
   width: 100px;
   height; 100px;
}

Javascript

$(document).ready(function()
{
   $('img', '.thumbnail').hide();//Start off hidden
   $('.thumbnail').mouseenter(function()
   {
      $('img', this).show();
   });
   $('.thumbnail').mouseleave(function()
   {
      $('img', this).hide();
   });
});


问:
How to return data from Firestore query to a FlatList
I'm new to React-Native and I am trying to return the array of data from the firstore query to the device screen where I can setDevices.
I had this working using .get() and .then(), but I wasn't getting the updated events, so I've moved to onSnapshot and seem to have data at the query end, but can't get this set at the screen.

```<code>import React, { useEffect, useRef, useState } from "react";
import { Alert,FlatList,RefreshControl,StatusBar,Text,View } from "react-native";
import { TouchableOpacity } from "react-native-gesture-handler";
import styles from "./styles";
import { getDevices } from "../../services/devices";
import { useNavigation } from "@react-navigation/native";
import { Feather } from "@expo/vector-icons";
import CircularProgress from "react-native-circular-progress-indicator";
import { removeDevice } from "../../redux/actions";
import { useDispatch } from "react-redux";
import firebase from "firebase/app";
import "firebase/firestore";

const wait = (timeout) => {
  return new Promise((resolve) => setTimeout(resolve, timeout));
};

export default function DevicesScreen() {
  const [devices, setDevices] = useState([]);
  const [loading, setLoading] = useState(false);
  const componentMounted = useRef(true);
  const navigation = useNavigation();

  useEffect(() => {
    getDevices().then(setDevices)
  },[]);
  console.log()

TypeError: undefined is not an object (evaluating '(0, _devices.getDevices)().then')

This error is located at:
in DevicesScreen (created by SceneView)
</code>```

This error appears. If I remove .then(setDevices) I can see the array of data on the console.log

```<code>import firebase from "firebase/app";
import "firebase/firestore";

export const getDevices = () => {
  firebase
    .firestore()
    .collection("device")
    .where("user_id", "==", "Rweeff9MO8XIDheZLx0HVbfaezy2")
    .get()
    .then((querySnapshot) => {
      querySnapshot.docs.map(doc => {
        let data =doc.data();
        console.log(data);
        return { id, ...doc };
      }
      )}
    )
  }
</code>```

Thanks

答:
There are several problems in your code.

You don't return the Promises chain.

id is not defined. You need to do doc.id.

So the following should do the trick:

```<code>export const getDevices = () => {
    return admin   // <========= See the return here
        .firestore()
        .collection("projects")
        .get()
        .then((querySnapshot) => {
           return querySnapshot.docs.map(doc => ({  id: doc.id, ...doc.data() }));
           // ^^^  See the return here
        });
      }
</code>```

Body:
I'm new to React-Native and I am trying to return the array of data from the firstore query to the device screen where I can setDevices.
I had this working using .get() and .then(), but I wasn't getting the updated events, so I've moved to onSnapshot and seem to have data at the query end, but can't get this set at the screen.

import React, { useEffect, useRef, useState } from "react";
import { Alert,FlatList,RefreshControl,StatusBar,Text,View } from "react-native";
import { TouchableOpacity } from "react-native-gesture-handler";
import styles from "./styles";
import { getDevices } from "../../services/devices";
import { useNavigation } from "@react-navigation/native";
import { Feather } from "@expo/vector-icons";
import CircularProgress from "react-native-circular-progress-indicator";
import { removeDevice } from "../../redux/actions";
import { useDispatch } from "react-redux";
import firebase from "firebase/app";
import "firebase/firestore";

const wait = (timeout) => {
  return new Promise((resolve) => setTimeout(resolve, timeout));
};

export default function DevicesScreen() {
  const [devices, setDevices] = useState([]);
  const [loading, setLoading] = useState(false);
  const componentMounted = useRef(true);
  const navigation = useNavigation();

  useEffect(() => {
    getDevices().then(setDevices)
  },[]);
  console.log()

TypeError: undefined is not an object (evaluating '(0, _devices.getDevices)().then')

This error is located at:
in DevicesScreen (created by SceneView)

This error appears. If I remove .then(setDevices) I can see the array of data on the console.log

import firebase from "firebase/app";
import "firebase/firestore";

export const getDevices = () => {
  firebase
    .firestore()
    .collection("device")
    .where("user_id", "==", "Rweeff9MO8XIDheZLx0HVbfaezy2")
    .get()
    .then((querySnapshot) => {
      querySnapshot.docs.map(doc => {
        let data =doc.data();
        console.log(data);
        return { id, ...doc };
      }
      )}
    )
  }

Thanks

Body:
There are several problems in your code.

You don't return the Promises chain.

id is not defined. You need to do doc.id.

So the following should do the trick:

export const getDevices = () => {
    return admin   // <========= See the return here
        .firestore()
        .collection("projects")
        .get()
        .then((querySnapshot) => {
           return querySnapshot.docs.map(doc => ({  id: doc.id, ...doc.data() }));
           // ^^^  See the return here
        });
      }


问:
Is there a way to associate Selenium test with an Azure DevOps test case?
What I'm aiming for is closing the loop on test coverage.

My goal would be:

Define test cases with PM and list them out under a Test Plan in Azure DevOps.

Associate Selenium tests in Visual Studio with specific test case(s).

When the release pipeline runs the UI test, I would expect to see on the dashboard the % of test cases that passed/failed or were not even associated.

Is that even possible?

答:
Check this extension that I have created https://github.com/JanuszNowak/janono.ado.testcase.associate.cli . It allows associating in automatic manner. So if yours selenium test are using xunit, nunit or mstest you can associate them automatically.

Code sample:

```<code>namespace ExampleTestProject
{
    [TestClass]
    [janono.ado.testcase.associate.Organization("janono-pub")]
    public class UnitTest1
    {
        [TestMethod]
        [janono.ado.testcase.associate.TestCase(5)] //<---
        public void TestMethod1()
        {
            //yours test method content
            //...
            //
        }
    }
}
</code>```

Body:
Check this extension that I have created https://github.com/JanuszNowak/janono.ado.testcase.associate.cli . It allows associating in automatic manner. So if yours selenium test are using xunit, nunit or mstest you can associate them automatically.

Code sample:

namespace ExampleTestProject
{
    [TestClass]
    [janono.ado.testcase.associate.Organization("janono-pub")]
    public class UnitTest1
    {
        [TestMethod]
        [janono.ado.testcase.associate.TestCase(5)] //<---
        public void TestMethod1()
        {
            //yours test method content
            //...
            //
        }
    }
}


问:
FailedPreconditionError: Table not initialized
I am trying to create an NLP neural-network using the following code:

imports:

```<code>import zipfile
import pandas as pd
import numpy as np
import tensorflow as tf
from tensorflow.keras.layers import TextVectorization,Embedding,Input,GlobalAveragePooling1D,Dense
from sklearn.model_selection import train_test_split
</code>```

Download and unzip dataset:

```<code># Download data (same as from Kaggle)
!wget "https://storage.googleapis.com/ztm_tf_course/nlp_getting_started.zip"

# Unzip data
zip_ref = zipfile.ZipFile("nlp_getting_started.zip", "r")
zip_ref.extractall()
zip_ref.close()
</code>```

Split data into train and test datasets:

```<code>    train_df = pd.read_csv("train.csv")

    train_sentences, val_sentences, train_labels, val_labels = train_test_split(train_df['text'], train_df['target'],train_size=.8)
    average_output_sequence_length = 15

</code>```

Create the neural-network:

```<code>input = Input(shape=(1,),dtype='string')
x = TextVectorization(max_tokens=10000,
                      ngrams=5,
                      standardize='lower_and_strip_punctuation',
                      output_mode='int',
                      output_sequence_length = average_output_sequence_length)(input)
x = Embedding(input_dim=22,embeddings_initializer='uniform',output_dim=128, name= 'embeding_layer')(x)
x = GlobalAveragePooling1D()(x)
output = Dense(1,activation='sigmoid')(x)

model = tf.keras.Model(input,output)

model.compile(loss='binary_crossentropy',optimizer='adam',metrics=['accuracy'] )

model.fit(x=train_sentences,y=train_labels,epochs=6,validation_data=(val_sentences,val_labels))
</code>```

Unfortunately, when i run the code, i face with the following error:

```<code>Epoch 1/6
---------------------------------------------------------------------------
FailedPreconditionError                   Traceback (most recent call last)
<ipython-input-52-991547d73612> in <module>()
     13 model.compile(loss='binary_crossentropy',optimizer='adam',metrics=['accuracy'] )
     14
---> 15 model.fit(x=train_sentences,y=train_labels,epochs=6,validation_data=(val_sentences,val_labels))

1 frames
/usr/local/lib/python3.7/dist-packages/tensorflow/python/eager/execute.py in quick_execute(op_name, num_outputs, inputs, attrs, ctx, name)
     57     ctx.ensure_initialized()
     58     tensors = pywrap_tfe.TFE_Py_Execute(ctx._handle, device_name, op_name,
---> 59                                         inputs, attrs, num_outputs)
     60   except core._NotOkStatusException as e:
     61     if name is not None:

FailedPreconditionError:  Table not initialized.
     [[node model_6/text_vectorization_7/string_lookup_7/None_Lookup/LookupTableFindV2
 (defined at /usr/local/lib/python3.7/dist-packages/keras/layers/preprocessing/index_lookup.py:669)
]] [Op:__inference_train_function_5066]

Errors may have originated from an input operation.
</code>```

UPDATE:
I got it to work when i change the way that i use the functional code:

Create TextVectorization function:

```<code>text_vectorization_layer =  TextVectorization(max_tokens=10000,
                                              ngrams=5,
                                              standardize='lower_and_strip_punctuation',
                                              output_mode='int',
                                              output_sequence_length = average_output_sequence_length
                                              )
</code>```

And then finally create the neural-network:

```<code>input = Input(shape=(1,),dtype='string')
x = text_vectorization_layer(input)
x = Embedding(input_dim=22,embeddings_initializer='uniform',output_dim=128, name= 'embeding_layer')(x)
x = GlobalAveragePooling1D()(x)
output = Dense(1,activation='sigmoid')(x)

model = tf.keras.Model(input,output)

model.compile(loss='binary_crossentropy',optimizer='adam',metrics=['accuracy'] )

model.fit(x=train_sentences,y=train_labels,epochs=6,validation_data=(val_sentences,val_labels))
</code>```

QUESTION:

But, i still do not understand why these change fix the issue ?

in other word, why the:

```<code>x = TextVectorization(input)
</code>```

and the

```<code>x = TextVectorization(max_tokens=10000,
                      ngrams=5,
                      standardize='lower_and_strip_punctuation',
                      output_mode='int',
                      output_sequence_length = average_output_sequence_length)(input)
</code>```

are not equal ?

答:
The TextVectorization layer is a preprocessing layer that needs to be instantiated before being called. Also as the docs explain:

The vocabulary for the layer must be either supplied on construction
or learned via adapt().

Another important information can be found here:

Crucially, these layers are non-trainable. Their state is not set during training; it must be set before training, either by initializing them from a precomputed constant, or by "adapting" them on data

Furthermore, it is important to note, that the TextVectorization layer uses an underlying StringLookup layer that also needs to be initialized beforehand. Otherwise, you will get the FailedPreconditionError: Table not initialized as you posted.

Body:
I am trying to create an NLP neural-network using the following code:

imports:

import zipfile
import pandas as pd
import numpy as np
import tensorflow as tf
from tensorflow.keras.layers import TextVectorization,Embedding,Input,GlobalAveragePooling1D,Dense
from sklearn.model_selection import train_test_split

Download and unzip dataset:

# Download data (same as from Kaggle)
!wget "https://storage.googleapis.com/ztm_tf_course/nlp_getting_started.zip"

# Unzip data
zip_ref = zipfile.ZipFile("nlp_getting_started.zip", "r")
zip_ref.extractall()
zip_ref.close()

Split data into train and test datasets:

    train_df = pd.read_csv("train.csv")

    train_sentences, val_sentences, train_labels, val_labels = train_test_split(train_df['text'], train_df['target'],train_size=.8)
    average_output_sequence_length = 15

Create the neural-network:

input = Input(shape=(1,),dtype='string')
x = TextVectorization(max_tokens=10000,
                      ngrams=5,
                      standardize='lower_and_strip_punctuation',
                      output_mode='int',
                      output_sequence_length = average_output_sequence_length)(input)
x = Embedding(input_dim=22,embeddings_initializer='uniform',output_dim=128, name= 'embeding_layer')(x)
x = GlobalAveragePooling1D()(x)
output = Dense(1,activation='sigmoid')(x)

model = tf.keras.Model(input,output)

model.compile(loss='binary_crossentropy',optimizer='adam',metrics=['accuracy'] )

model.fit(x=train_sentences,y=train_labels,epochs=6,validation_data=(val_sentences,val_labels))

Unfortunately, when i run the code, i face with the following error:

Epoch 1/6
---------------------------------------------------------------------------
FailedPreconditionError                   Traceback (most recent call last)
<ipython-input-52-991547d73612> in <module>()
     13 model.compile(loss='binary_crossentropy',optimizer='adam',metrics=['accuracy'] )
     14
---> 15 model.fit(x=train_sentences,y=train_labels,epochs=6,validation_data=(val_sentences,val_labels))

1 frames
/usr/local/lib/python3.7/dist-packages/tensorflow/python/eager/execute.py in quick_execute(op_name, num_outputs, inputs, attrs, ctx, name)
     57     ctx.ensure_initialized()
     58     tensors = pywrap_tfe.TFE_Py_Execute(ctx._handle, device_name, op_name,
---> 59                                         inputs, attrs, num_outputs)
     60   except core._NotOkStatusException as e:
     61     if name is not None:

FailedPreconditionError:  Table not initialized.
     [[node model_6/text_vectorization_7/string_lookup_7/None_Lookup/LookupTableFindV2
 (defined at /usr/local/lib/python3.7/dist-packages/keras/layers/preprocessing/index_lookup.py:669)
]] [Op:__inference_train_function_5066]

Errors may have originated from an input operation.

UPDATE:
I got it to work when i change the way that i use the functional code:

Create TextVectorization function:

text_vectorization_layer =  TextVectorization(max_tokens=10000,
                                              ngrams=5,
                                              standardize='lower_and_strip_punctuation',
                                              output_mode='int',
                                              output_sequence_length = average_output_sequence_length
                                              )

And then finally create the neural-network:

input = Input(shape=(1,),dtype='string')
x = text_vectorization_layer(input)
x = Embedding(input_dim=22,embeddings_initializer='uniform',output_dim=128, name= 'embeding_layer')(x)
x = GlobalAveragePooling1D()(x)
output = Dense(1,activation='sigmoid')(x)

model = tf.keras.Model(input,output)

model.compile(loss='binary_crossentropy',optimizer='adam',metrics=['accuracy'] )

model.fit(x=train_sentences,y=train_labels,epochs=6,validation_data=(val_sentences,val_labels))

QUESTION:

But, i still do not understand why these change fix the issue ?

in other word, why the:

x = TextVectorization(input)

and the

x = TextVectorization(max_tokens=10000,
                      ngrams=5,
                      standardize='lower_and_strip_punctuation',
                      output_mode='int',
                      output_sequence_length = average_output_sequence_length)(input)

are not equal ?


问:
sql case in column and where section without repeating the case
I have a sql statement like this but with a very long case expression in it and I need it in the where as well as in the column. Is there a way to use the case without repeating it in the column and where section.</p>
```<code>select * from c.name, (case when c.age = 1 then 0 when c.age = 2 then 1 ... etc else -1 end;)
from customer c
where (case when c.age = 1 then 0 when c.age = 2 then 1 ... etc else -1 end;) > 0
</code>```

答:
A simple way of consolidating would be to use a lateral join

```<code>select *
from customer c,
lateral (values(case when c.age = 1 then 0 when c.age = 2 then 1 ... etc else -1 end))v(AgeCheck)
where AgeCheck > 0;
</code>```

Body:
I have a sql statement like this but with a very long case expression in it and I need it in the where as well as in the column. Is there a way to use the case without repeating it in the column and where section.

select * from c.name, (case when c.age = 1 then 0 when c.age = 2 then 1 ... etc else -1 end;)
from customer c
where (case when c.age = 1 then 0 when c.age = 2 then 1 ... etc else -1 end;) > 0

Body:
A simple way of consolidating would be to use a lateral join

select *
from customer c,
lateral (values(case when c.age = 1 then 0 when c.age = 2 then 1 ... etc else -1 end))v(AgeCheck)
where AgeCheck > 0;


问:
Selenium 4 : frameToBeAvailableAndSwitchToIt doesn't seem to work
I am trying to work with a webpage in Selenium 4. The page has a few iframes and I am trying to wait for an iframe to load completely and then switch to it.

However, the code below doesn't seem to work:

```<code>driver = new ChromeDriver(options);

driver.get("https://www.stagecoachliquor.com/online-store-1/Whiskey-c20954043");

WebDriverWait wait = new WebDriverWait(driver,Duration.ofSeconds(30));

wait.until(ExpectedConditions.frameToBeAvailableAndSwitchToIt(By.cssSelector("#TPASection_iw75naz9 > iframe")));

System.out.println(driver.getPageSource());
</code>```

The system out just prints an empty HTML snippet below:

```<code><html><head></head><body></body></html>
</code>```

As a result, when I try to select any element after the switch, it fails. The iframe is loading alright in the chrome window which seems strange to me. I have tried implicit wait as well which did not work and had the same result.

After a few hours of debugging, I have not been able to identify the root cause. Any help is much appreciated.

Best,
R

答:
The root cause is your condition is always true, iframe is available after you get the HTML. You can simply add a Thread.sleep to verify it.

For now: I can't find any condition that is suited for your situation.

```<code>WebDriver driver = new ChromeDriver();

driver.get("https://www.stagecoachliquor.com/online-store-1/Whiskey-c20954043");

Thread.sleep(10000);

driver.switchTo().frame(driver.findElement(By.cssSelector("#TPASection_iw75naz9 > iframe")));

System.out.println(driver.getPageSource());

driver.quit();
</code>```

Body:
I am trying to work with a webpage in Selenium 4. The page has a few iframes and I am trying to wait for an iframe to load completely and then switch to it.

However, the code below doesn't seem to work:

driver = new ChromeDriver(options);

driver.get("https://www.stagecoachliquor.com/online-store-1/Whiskey-c20954043");

WebDriverWait wait = new WebDriverWait(driver,Duration.ofSeconds(30));

wait.until(ExpectedConditions.frameToBeAvailableAndSwitchToIt(By.cssSelector("#TPASection_iw75naz9 > iframe")));

System.out.println(driver.getPageSource());

The system out just prints an empty HTML snippet below:

As a result, when I try to select any element after the switch, it fails. The iframe is loading alright in the chrome window which seems strange to me. I have tried implicit wait as well which did not work and had the same result.

After a few hours of debugging, I have not been able to identify the root cause. Any help is much appreciated.

Best,
R

Body:
The root cause is your condition is always true, iframe is available after you get the HTML. You can simply add a Thread.sleep to verify it.

For now: I can't find any condition that is suited for your situation.

WebDriver driver = new ChromeDriver();

driver.get("https://www.stagecoachliquor.com/online-store-1/Whiskey-c20954043");

Thread.sleep(10000);

driver.switchTo().frame(driver.findElement(By.cssSelector("#TPASection_iw75naz9 > iframe")));

System.out.println(driver.getPageSource());

driver.quit();


问:
How to authenticate mongo dB docker container through MongoDB compass?
Problem:

I have set up a docker container for MongoDB and mongo-express. Both are up and running successfully. This is how my docker-compose configurations.

```<code>questionsdb:
    container_name: questionsdb
    restart: always
    command: mongod --auth
    environment:
        - MONGO_INITDB_DATABASE=questions
        - MONGO_INITDB_ROOT_USERNAME=admin
        - MONGO_INITDB_ROOT_PASSWORD=org1234
    volumes:
        - mongo_data:/data/db
    ports:
        - "27019:27017"

  mongo-express:
    container_name: mongo-express
    restart: always
    ports:
        - "8081:8081"
    volumes:
        - mongoadmin_data:/data/dbadmin
    environment:
        #- ME_CONFIG_MONGODB_ADMINUSERNAME=admin
        #- ME_CONFIG_MONGODB_ADMINPASSWORD=org1234
        - ME_CONFIG_MONGODB_SERVER=questionsdb
        - ME_CONFIG_OPTIONS_EDITORTHEME=ambiance
        - ME_CONFIG_MONGODB_URL=mongodb://admin:org1234@questionsdb:27017
        - ME_CONFIG_BASICAUTH_USERNAME=admin@myorg.com
        - ME_CONFIG_BASICAUTH_PASSWORD=org@1234
        - ME_CONFIG_MONGODB_ENABLE_ADMIN=true
    links:
        - questionsdb
</code>```

But when I open the mongo-express nothing showing. Then I look on mongo-express logs. Then I saw this.

```<code>(node:7) [MONGODB DRIVER] Warning: Current Server Discovery and Monitoring engine is deprecated, and will be removed in a future version. To use the new Server Discover and Monitoring engine, pass option { useUnifiedTopology: true } to the MongoClient constructor.

(node:7) UnhandledPromiseRejectionWarning: MongoError: command listDatabases requires authentication

at Connection.<anonymous> (/node_modules/mongodb/lib/core/connection/pool.js:453:61)

at Connection.emit (events.js:314:20)

at processMessage (/node_modules/mongodb/lib/core/connection/connection.js:454:10)

at Socket.<anonymous> (/node_modules/mongodb/lib/core/connection/connection.js:623:15)

at Socket.emit (events.js:314:20)

at addChunk (_stream_readable.js:297:12)

at readableAddChunk (_stream_readable.js:272:9)

at Socket.Readable.push (_stream_readable.js:213:10)

at TCP.onStreamRead (internal/stream_base_commons.js:188:23)

(node:7) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 1)

(node:7) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
</code>```

Then I tried to access the MongoDB container through MongoDbComapsss like this.

but that also failed with giving me authentication failed error. If I remove MONGO_INITDB_ROOT_USERNAME and  MONGO_INITDB_ROOT_PASSWORD it working without any issues. I tried a lot to find a solution to this one. But I was unable to do so. Can someone help me to solve this issue? Thank you

答:
this issue can be resolved if you put
USERNAME & PASSWORD
encrypted in BASE64

Replace this

```<code>ME_CONFIG_MONGODB_ADMINUSERNAME=admin
ME_CONFIG_MONGODB_ADMINPASSWORD=org1234
</code>```

with

```<code>ME_CONFIG_MONGODB_ADMINUSERNAME=YWRtaW4=
ME_CONFIG_MONGODB_ADMINPASSWORD=b3JnMTIzNA==
</code>```

BASE64 Encode & Decoder

```<code>https://www.base64encode.org/
</code>```

Body:
Problem:

I have set up a docker container for MongoDB and mongo-express. Both are up and running successfully. This is how my docker-compose configurations.

questionsdb:
    container_name: questionsdb
    restart: always
    command: mongod --auth
    environment:
        - MONGO_INITDB_DATABASE=questions
        - MONGO_INITDB_ROOT_USERNAME=admin
        - MONGO_INITDB_ROOT_PASSWORD=org1234
    volumes:
        - mongo_data:/data/db
    ports:
        - "27019:27017"

  mongo-express:
    container_name: mongo-express
    restart: always
    ports:
        - "8081:8081"
    volumes:
        - mongoadmin_data:/data/dbadmin
    environment:
        #- ME_CONFIG_MONGODB_ADMINUSERNAME=admin
        #- ME_CONFIG_MONGODB_ADMINPASSWORD=org1234
        - ME_CONFIG_MONGODB_SERVER=questionsdb
        - ME_CONFIG_OPTIONS_EDITORTHEME=ambiance
        - ME_CONFIG_MONGODB_URL=mongodb://admin:org1234@questionsdb:27017
        - ME_CONFIG_BASICAUTH_USERNAME=admin@myorg.com
        - ME_CONFIG_BASICAUTH_PASSWORD=org@1234
        - ME_CONFIG_MONGODB_ENABLE_ADMIN=true
    links:
        - questionsdb

But when I open the mongo-express nothing showing. Then I look on mongo-express logs. Then I saw this.

(node:7) [MONGODB DRIVER] Warning: Current Server Discovery and Monitoring engine is deprecated, and will be removed in a future version. To use the new Server Discover and Monitoring engine, pass option { useUnifiedTopology: true } to the MongoClient constructor.

(node:7) UnhandledPromiseRejectionWarning: MongoError: command listDatabases requires authentication

at Connection.<anonymous> (/node_modules/mongodb/lib/core/connection/pool.js:453:61)

at Connection.emit (events.js:314:20)

at processMessage (/node_modules/mongodb/lib/core/connection/connection.js:454:10)

at Socket.<anonymous> (/node_modules/mongodb/lib/core/connection/connection.js:623:15)

at Socket.emit (events.js:314:20)

at addChunk (_stream_readable.js:297:12)

at readableAddChunk (_stream_readable.js:272:9)

at Socket.Readable.push (_stream_readable.js:213:10)

at TCP.onStreamRead (internal/stream_base_commons.js:188:23)

(node:7) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 1)

(node:7) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.

Then I tried to access the MongoDB container through MongoDbComapsss like this.

but that also failed with giving me authentication failed error. If I remove MONGO_INITDB_ROOT_USERNAME and  MONGO_INITDB_ROOT_PASSWORD it working without any issues. I tried a lot to find a solution to this one. But I was unable to do so. Can someone help me to solve this issue? Thank you

Body:
this issue can be resolved if you put
USERNAME & PASSWORD
encrypted in BASE64

Replace this

ME_CONFIG_MONGODB_ADMINUSERNAME=admin
ME_CONFIG_MONGODB_ADMINPASSWORD=org1234

with

ME_CONFIG_MONGODB_ADMINUSERNAME=YWRtaW4=
ME_CONFIG_MONGODB_ADMINPASSWORD=b3JnMTIzNA==

BASE64 Encode & Decoder

https://www.base64encode.org/


问:
Swift: iOS Deployment Target Command Line Flag
How do I check the iOS deployment target in a Swift conditional compilation statement?

I've tried the following:

```<code>#if __IPHONE_OS_VERSION_MIN_REQUIRED < __IPHONE_8_0
    // some code here
#else
    // other code here
#endif
</code>```

But, the first expression causes the compile error:

```<code>Expected '&&' or '||' expression
</code>```

答:
I have come across this issue recently when building a library whose source code supports multiple iOS and macOS versions with different functionality.

My solution is using custom build flags in Xcode which derive their value from the actual deployment target:

```<code>TARGET_IOS_MAJOR = TARGET_IOS_MAJOR_$(IPHONEOS_DEPLOYMENT_TARGET:base)
TARGET_MACOS_MAJOR = TARGET_MACOS_MAJOR_$(MACOSX_DEPLOYMENT_TARGET:base)
</code>```

Referring to those user defined settings in Others Swift Flags like:

```<code>OTHER_SWIFT_FLAGS = -D$(TARGET_MACOS_MAJOR) -D$(TARGET_IOS_MAJOR)
</code>```

allows me to check for the actual major OS version in my Swift sources as follows:

#if os(macOS)
    #if TARGET_MACOS_MAJOR_12
        #warning("TARGET_MACOS_MAJOR_12")

    #elseif TARGET_MACOS_MAJOR_11
        // use custom implementation
        #warning("TARGET_MACOS_MAJOR_11")
    #endif

#elseif os(iOS)
    #if TARGET_IOS_MAJOR_15
        #warning("TARGET_IOS_MAJOR_15")

    #elseif TARGET_IOS_MAJOR_14
        #warning("TARGET_IOS_MAJOR_14")

    #else
        #warning("older iOS")
    #endif
#endif

```

Currently I don't know if a similar approach would be possible in a SPM package. This is something I will try to do in a later phase.

Body:
How do I check the iOS deployment target in a Swift conditional compilation statement?

I've tried the following:

#if __IPHONE_OS_VERSION_MIN_REQUIRED < __IPHONE_8_0
    // some code here
#else
    // other code here
#endif

But, the first expression causes the compile error:

Expected '&&' or '||' expression

Body:
I have come across this issue recently when building a library whose source code supports multiple iOS and macOS versions with different functionality.

My solution is using custom build flags in Xcode which derive their value from the actual deployment target:

TARGET_IOS_MAJOR = TARGET_IOS_MAJOR_$(IPHONEOS_DEPLOYMENT_TARGET:base)
TARGET_MACOS_MAJOR = TARGET_MACOS_MAJOR_$(MACOSX_DEPLOYMENT_TARGET:base)

Referring to those user defined settings in Others Swift Flags like:

OTHER_SWIFT_FLAGS = -D$(TARGET_MACOS_MAJOR) -D$(TARGET_IOS_MAJOR)

allows me to check for the actual major OS version in my Swift sources as follows:

#if os(macOS)
    #if TARGET_MACOS_MAJOR_12
        #warning("TARGET_MACOS_MAJOR_12")

    #elseif TARGET_MACOS_MAJOR_11
        // use custom implementation
        #warning("TARGET_MACOS_MAJOR_11")
    #endif

#elseif os(iOS)
    #if TARGET_IOS_MAJOR_15
        #warning("TARGET_IOS_MAJOR_15")

    #elseif TARGET_IOS_MAJOR_14
        #warning("TARGET_IOS_MAJOR_14")

    #else
        #warning("older iOS")
    #endif
#endif

Currently I don't know if a similar approach would be possible in a SPM package. This is something I will try to do in a later phase.


问:
Using variables and functions in other fileis Node js
I have two separate files and I want to use functions and variables in my first file in another file.
What I mean is, here is the content of my first file:

```<code>const db = mongoose.connection;
</code>```

and in my second file I need to for example log it:

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

I used export and import but it did not work:

```<code>export const db = mongoose.connection;

import db from (./db.js)
console.log(db)
</code>```

I got this error:
SyntaxError: Cannot use import statement outside a module

答:
Did you create the HTML file, too? If so try loading the second file in as a module type to fix the error.

Put this in your HTML file:

```<code><script type="module" src="secondScript.js"></script>
</code>```

Body:
I have two separate files and I want to use functions and variables in my first file in another file.
What I mean is, here is the content of my first file:

const db = mongoose.connection;

and in my second file I need to for example log it:

console.log(db)

I used export and import but it did not work:

export const db = mongoose.connection;

import db from (./db.js)
console.log(db)

I got this error:
SyntaxError: Cannot use import statement outside a module

Body:
Did you create the HTML file, too? If so try loading the second file in as a module type to fix the error.

Put this in your HTML file:

<script type="module" src="secondScript.js"></script>


问:
python json how to write data one under the other instead of side by side
```<code>        self.channel_ticket = await category.create_text_channel(f'övgü-{user.name}',  overwrites=overwrites)

        with open('data.json', 'a+') as f:
            f.seek(0)
            json.dump(str(user_id), f, indent = 4 )
</code>```

here, it writes user ID that created channel.

Output :

```<code>"332115091338297344""323516141777715202"
</code>```

it writes the ID of more than one user, but how can I make it type from one under the other instead of side by side

答:
.json is essentially equivalent to a dictionary in python.

JSON

{
    "name" : "Li",
    "age" : 20,
    "stupid" : true
}
```
<p><strong>PYTHON DICT</strong></p>
<pre class="lang-py prettyprint-override"><code>about_li = {
    "name" : "Li",
    "age" : 20,
    "stupid" : True
}
</code>```

So what you can do is (and this is keeping in mind the last question you asked) store the values as True or False with the key being their ID.

import json

id_json = open("id.json", "r+")

ids = json.loads(id_json)

try:
    if not ids[str(user_id)]:
        # Create your channel and send the dm
        ids[str(user_id)] = True
    else:
        # Say the channel is already open
except:
    ids[str(user_id)] = False

id_json.write(json.dumps(ids))
id_json.close()
```

Body:
        self.channel_ticket = await category.create_text_channel(f'övgü-{user.name}',  overwrites=overwrites)

        with open('data.json', 'a+') as f:
            f.seek(0)
            json.dump(str(user_id), f, indent = 4 )

here, it writes user ID that created channel.

Output :

"332115091338297344""323516141777715202"

it writes the ID of more than one user, but how can I make it type from one under the other instead of side by side

Body:
.json is essentially equivalent to a dictionary in python.

JSON

{
    "name" : "Li",
    "age" : 20,
    "stupid" : true
}

PYTHON DICT

about_li = {
    "name" : "Li",
    "age" : 20,
    "stupid" : True
}

So what you can do is (and this is keeping in mind the last question you asked) store the values as True or False with the key being their ID.

import json

id_json = open("id.json", "r+")

ids = json.loads(id_json)

try:
    if not ids[str(user_id)]:
        # Create your channel and send the dm
        ids[str(user_id)] = True
    else:
        # Say the channel is already open
except:
    ids[str(user_id)] = False

id_json.write(json.dumps(ids))
id_json.close()


问:
Multi language PHP application: best practice?
I'd like to get your feedback over the way I implemented multi-language support on my PHP MVC web app. That's how I did:

in the /app folder I created a /languages folder which contains one file per language (english.php, spanish.php, etc.)

each file contains a serie of variables with the same names in each files, containing the texts to render in the views

these variables are then echoed in the different views

a "language" cookie variable is updated when the user changes the language

in the controller of each view, I include a language file on the following format:

include $_SERVER['DOCUMENT_ROOT'] . "/app/languages/" . $_COOKIE["language"] . ".php";

Sounds pretty neat to me. Would you have any negative thoughts about this method?

答:
As you are just having data in the language files, I would recommend using GetText. It is a port of the standard GetText of C++ for internationalization, there are tons of tools to build up the language files and is very fast due to compiled files during runtime.

You essentially build up your data-files (e.g. fr.po, en.po) with a kind-of INI-file format and compile those files to specialized .mo-files (fr.mo, en.mo, ...) and simply echo the internationalized strings with the static function _(), e.g. echo _("Hello World"); would produce the german output Hallo Welt or (if no translation is available in the .mo-files) the default string Hello World.

As for choosing the right language: that depends on your requirements. As already pointed out, you should use the Accept-language-Header of the browser and might want to add support for an overwrite through session-information.


答:
You can use stringr::str_wrap within scale_x_discrete to wrap your labels, and fct_inorder to convert your column to ordered factor by the order in which they appear.

```<code>datadim.lng %>%
    mutate(vizit = fct_inorder(vizit)) %>% # convert to factor in order of appearance
    ggplot(aes(x = vizit, y = gem, fill = Therapy.group)) +
    geom_boxplot(position = position_dodge(width = 0.85), width = 0.8)+
    theme_classic() +
    stat_summary(
        fun = median,
        geom = 'line',
        aes(group = Therapy.group, color = Therapy.group),
        position = position_dodge(width = 0.85)
    ) +
    scale_x_discrete(labels = function(x) str_wrap(gsub("\\.+", " ", x), width = 5))
</code>```

the labels argument can be provided with either the labels to use or a function that will be applied to all labels. In the above code a function is created that firsts convert the dots to spaces within your column and then uses str_wrap for wrapping the words into multiple lines. (str_wrap won't work if there are no breaks between words)

Title: lack of space between signatures on the plot and wrong column order on the plot in R

Body:
I need create plot using ggplot2

Here my code with reproducible example

library(tidyverse)
    gemoglabin=structure(list(Therapy.group = c(1L, 2L, 1L, 2L, 1L, 2L, 2L,
2L, 1L, 1L, 2L, 1L, 2L, 2L, 1L, 1L, 1L, 2L, 2L, 1L, 2L, 1L, 2L,
1L, 2L, 2L, 2L, 1L, 1L, 2L, 1L, 2L, 2L, 1L, 1L, 2L, 1L, 1L),
    X.Hemoglobin..g.l...WWScreening = c(139L, 168L, 152L, 122L,
    142L, 150L, 120L, 157L, 136L, 128L, 157L, 154L, 142L, 124L,
    138L, 138L, 151L, 148L, 148L, 142L, 149L, 157L, 137L, 135L,
    121L, 148L, 121L, 159L, 133L, 132L, 155L, 133L, 136L, 121L,
    140L, 142L, 137L, 147L), X.Hemoglobin..g.L...Visit.1.Day.2 = c(166L,
    141L, 144L, 121L, 141L, 145L, 121L, 158L, 135L, 121L, 158L,
    152L, 144L, 128L, 129L, 146L, 142L, 141L, 139L, 139L, 140L,
    159L, 143L, 132L, 134L, 149L, 123L, 163L, 145L, 141L, 145L,
    142L, 146L, 121L, 143L, 139L, 145L, 149L), X.Hemoglobin..g.L...Visit.2.Day.9 = c(140L,
    155L, 142L, 122L, 138L, 143L, 126L, 151L, 129L, 124L, 155L,
    140L, 140L, 122L, 132L, 136L, 135L, 140L, 141L, 142L, 136L,
    145L, 138L, 126L, 128L, 144L, 120L, 160L, 143L, 133L, 141L,
    142L, 147L, 121L, 138L, 139L, 142L, 152L), X.Hemoglobin..g.L...Visit.3.Day.16 = c(150L,
    157L, 153L, 117L, 140L, 143L, 122L, 155L, 125L, 121L, 156L,
    144L, 137L, 122L, 136L, 136L, 140L, 140L, 143L, 143L, 140L,
    143L, 141L, 123L, 129L, 150L, 121L, 163L, 149L, 143L, 136L,
    136L, 143L, 123L, 147L, 137L, 139L, 152L), X.Hemoglobin..g.L...Visit.4.Day.23 = c(140L,
    150L, 144L, 122L, 139L, 140L, 124L, 149L, 121L, 125L, 148L,
    141L, 132L, 126L, 133L, 136L, 137L, 141L, 141L, 137L, 141L,
    145L, 140L, 120L, 124L, 143L, 122L, 163L, 139L, 132L, 141L,
    141L, 138L, 121L, 134L, 134L, 137L, 148L), X.Hemoglobin..g.L...Visit.5.Day.29 = c(132L,
    165L, 141L, 122L, 143L, 140L, 131L, 153L, 123L, 121L, 150L,
    150L, 139L, 132L, 132L, 139L, 136L, 134L, 145L, 137L, 144L,
    147L, 134L, 124L, 128L, 148L, 121L, 167L, 142L, 127L, 140L,
    141L, 144L, 126L, 132L, 134L, 136L, 148L)), class = "data.frame", row.names = c(NA,
-38L))

datadim.lng <- gemoglabin %>% pivot_longer(-Therapy.group,names_to="vizit", values_to = "gem")

datadim.lng$Therapy.group <- as.factor(datadim.lng$Therapy.group)

ggplot(datadim.lng, aes(x = vizit, y = gem, fill = Therapy.group)) +
  geom_boxplot(position = position_dodge(width = 0.85), width = 0.8)+
  theme_classic() +
  stat_summary(
    fun = median,
    geom = 'line',
    aes(group = Therapy.group, color = Therapy.group),
    position = position_dodge(width = 0.85)
  )

as the result i get such screen

as we can see here the signatures on the vizit axis are mixed up and i can’t really see which vizit number.

How to make the signatures not mixed and visible? I must have space between visits in plot

only not in such small print otherwise it is hard to see.

Another problem is wrong order of signatures. WWscreening as we can see the first column in dataset ,but in the plot it is last in order

Can you please help me fix  space between signatures and correct order of column in the plot.
Thank you

Body:
You can use stringr::str_wrap within scale_x_discrete to wrap your labels, and fct_inorder to convert your column to ordered factor by the order in which they appear.

datadim.lng %>%
    mutate(vizit = fct_inorder(vizit)) %>% # convert to factor in order of appearance
    ggplot(aes(x = vizit, y = gem, fill = Therapy.group)) +
    geom_boxplot(position = position_dodge(width = 0.85), width = 0.8)+
    theme_classic() +
    stat_summary(
        fun = median,
        geom = 'line',
        aes(group = Therapy.group, color = Therapy.group),
        position = position_dodge(width = 0.85)
    ) +
    scale_x_discrete(labels = function(x) str_wrap(gsub("\\.+", " ", x), width = 5))

the labels argument can be provided with either the labels to use or a function that will be applied to all labels. In the above code a function is created that firsts convert the dots to spaces within your column and then uses str_wrap for wrapping the words into multiple lines. (str_wrap won't work if there are no breaks between words)


问:
How to update with function in laravel query builder
I'm doing a query and want to update the data, but I want to do a math operation first. How to simplify it?

my code below:

```<code>$jumlah = 10;
$Rpodetail = Rpodetail::where('rpo_id',$request->postore)->where('produk_id',$produkid)->first();
$total = $Rpodetail->sisa - $jumlah;
Rpodetail::where('rpo_id',$request->postore)->where('produk_id',$produkid)->update([
'sisa' => $total,
]);

</code>```

答:
```<code>$jumlah = 10;
$Rpodetail = Rpodetail::where('rpo_id',$request->postore)->where('produk_id',$produkid)->first();
$total = $Rpodetail->sisa - $jumlah;
$Rpodetail->update([
    'sisa' => $total,
]);
</code>```

Or

```<code>$jumlah = 10;
$Rpodetail = Rpodetail::where('rpo_id',$request->postore)->where('produk_id',$produkid)->first();
$Rpodetail->update([
    'sisa' => $Rpodetail->sisa - $jumlah,
]);
</code>```

Or 1 line answer (According to @PBJ answer) with DB:raw() :

```<code>jumlah = 10;
Rpodetail::where('rpo_id',$request->postore)->where('produk_id',$produkid)->update(['
sisa' => DB::raw("sisa + '$jumlah'")]);
</code>```

Body:
I'm doing a query and want to update the data, but I want to do a math operation first. How to simplify it?

my code below:

$jumlah = 10;
$Rpodetail = Rpodetail::where('rpo_id',$request->postore)->where('produk_id',$produkid)->first();
$total = $Rpodetail->sisa - $jumlah;
Rpodetail::where('rpo_id',$request->postore)->where('produk_id',$produkid)->update([
'sisa' => $total,
]);

Body:
$jumlah = 10;
$Rpodetail = Rpodetail::where('rpo_id',$request->postore)->where('produk_id',$produkid)->first();
$total = $Rpodetail->sisa - $jumlah;
$Rpodetail->update([
    'sisa' => $total,
]);

Or

$jumlah = 10;
$Rpodetail = Rpodetail::where('rpo_id',$request->postore)->where('produk_id',$produkid)->first();
$Rpodetail->update([
    'sisa' => $Rpodetail->sisa - $jumlah,
]);

Or 1 line answer (According to @PBJ answer) with DB:raw() :

jumlah = 10;
Rpodetail::where('rpo_id',$request->postore)->where('produk_id',$produkid)->update(['
sisa' => DB::raw("sisa + '$jumlah'")]);


问:
Python Websockets: AttributeError: 'Connect' object has no attribute 'send'
So, I'm creating a websocket client in python, this is the code

```<code>import websockets

ws = websockets.connect('ws://localhost:6789')

ws.send('asdf')
</code>```

but whenever I tried to run it, it says

```<code>Traceback (most recent call last):
  File "client.py", line 5, in <module>
    ws.send('asdf')
AttributeError: 'Connect' object has no attribute 'send'
</code>```

答:
The object you have is the connector object which should be connected, similar to having a file descriptor that you need to open or use the "with" syntax.
try:</p>
```<code>import websockets

async with websockets.connect('ws://localhost:6789') as ws:
    await ws.send('asdf')
</code>```

Body:
So, I'm creating a websocket client in python, this is the code

import websockets

ws = websockets.connect('ws://localhost:6789')

ws.send('asdf')

but whenever I tried to run it, it says

Traceback (most recent call last):
  File "client.py", line 5, in <module>
    ws.send('asdf')
AttributeError: 'Connect' object has no attribute 'send'

Body:
The object you have is the connector object which should be connected, similar to having a file descriptor that you need to open or use the "with" syntax.
try:

import websockets

async with websockets.connect('ws://localhost:6789') as ws:
    await ws.send('asdf')


问:
R geom_smooth custom best fitted line formula

Geom_smooth formula

I am currently trying to fit a line to my data.

However, no fitted line is shown on the plot with none of the default methods of geom_smooth.

Here is the code that generated the plot:

```<code>p1 <- ggplot(data[ which(data$subject_id == "P121" & !is.na(data$col1)), ], aes(x = date, y= col1)) +
  geom_point(colour= met.brewer("Isfahan1", 1)) +
  geom_smooth(method = "stats::loess", se= FALSE) +
  theme(axis.title.x=element_blank(), axis.text.x=element_blank(),
                      axis.ticks.x=element_blank(), axis.title.y=element_blank(), axis.text.y=element_blank(),
                      axis.ticks.y =element_blank(), legend.title=element_blank()) +
  scale_color_manual(values=met.brewer("Isfahan1", 13))
</code>```

This is the plot that is created by the code above
I am aware that we can customize the formula for the model to be fitted, however, I'm new to R. Could you guide me on how to decide on the formula?

答:
Your problem is using the string 'stats ::' in the method parameter of the geom_smooth function.

See the code below

```<code>library(tidyverse)
library(MetBrewer)

i1 = c(21, 25, 27, 30:33, 35, 37, 38:41, 44, 46:48, 53, 54)
df = tibble(
  date = 1:55,
  col1 = ifelse(date %in% i1, 200, 100)
)

df %>%  ggplot(aes(date, col1)) +
  geom_point(colour= met.brewer("Isfahan1", 1)) +
  geom_smooth(formula = y~x, method = "loess", se= FALSE) +
  theme(
    axis.title.x=element_blank(),
    axis.text.x=element_blank(),
    axis.ticks.x=element_blank(),
    axis.title.y=element_blank(),
    axis.text.y=element_blank(),
    axis.ticks.y=element_blank(),
    legend.title=element_blank()) +
  scale_color_manual(values=met.brewer("Isfahan1", 13))
</code>```

You can also use another method, e.g. linear

```<code>df %>%  ggplot(aes(date, col1)) +
  geom_point(colour= met.brewer("Isfahan1", 1)) +
  geom_smooth(formula = y~x, method = "lm", se= FALSE) +
  theme(
    axis.title.x=element_blank(),
    axis.text.x=element_blank(),
    axis.ticks.x=element_blank(),
    axis.title.y=element_blank(),
    axis.text.y=element_blank(),
    axis.ticks.y=element_blank(),
    legend.title=element_blank()) +
  scale_color_manual(values=met.brewer("Isfahan1", 13))
</code>```

However, pay attention to the data you give to the ggplot function. If your date variable is not of numeric type, however, plot will be created without smooth path.

```<code>df = tibble(
  date = 1:55 %>% as.character(),
  col1 = ifelse(date %in% i1, 200, 100)
)

df %>%  ggplot(aes(date, col1)) +
  geom_point(colour= met.brewer("Isfahan1", 1)) +
  geom_smooth(formula = y~x, method = "loess", se= FALSE) +
  theme(
    axis.title.x=element_blank(),
    axis.text.x=element_blank(),
    axis.ticks.x=element_blank(),
    axis.title.y=element_blank(),
    axis.text.y=element_blank(),
    axis.ticks.y=element_blank(),
    legend.title=element_blank()) +
  scale_color_manual(values=met.brewer("Isfahan1", 13))
</code>```

As you can see in this example, I changed the value of the variable date to type character (date = 1:55 %>% as.character()) which made geom_smooth to not draw anything.

Body:
Geom_smooth formula

I am currently trying to fit a line to my data.

However, no fitted line is shown on the plot with none of the default methods of geom_smooth.

Here is the code that generated the plot:

p1 <- ggplot(data[ which(data$subject_id == "P121" & !is.na(data$col1)), ], aes(x = date, y= col1)) +
  geom_point(colour= met.brewer("Isfahan1", 1)) +
  geom_smooth(method = "stats::loess", se= FALSE) +
  theme(axis.title.x=element_blank(), axis.text.x=element_blank(),
                      axis.ticks.x=element_blank(), axis.title.y=element_blank(), axis.text.y=element_blank(),
                      axis.ticks.y =element_blank(), legend.title=element_blank()) +
  scale_color_manual(values=met.brewer("Isfahan1", 13))

This is the plot that is created by the code above
I am aware that we can customize the formula for the model to be fitted, however, I'm new to R. Could you guide me on how to decide on the formula?

Body:
Your problem is using the string 'stats ::' in the method parameter of the geom_smooth function.

See the code below

library(tidyverse)
library(MetBrewer)

i1 = c(21, 25, 27, 30:33, 35, 37, 38:41, 44, 46:48, 53, 54)
df = tibble(
  date = 1:55,
  col1 = ifelse(date %in% i1, 200, 100)
)

df %>%  ggplot(aes(date, col1)) +
  geom_point(colour= met.brewer("Isfahan1", 1)) +
  geom_smooth(formula = y~x, method = "loess", se= FALSE) +
  theme(
    axis.title.x=element_blank(),
    axis.text.x=element_blank(),
    axis.ticks.x=element_blank(),
    axis.title.y=element_blank(),
    axis.text.y=element_blank(),
    axis.ticks.y=element_blank(),
    legend.title=element_blank()) +
  scale_color_manual(values=met.brewer("Isfahan1", 13))

You can also use another method, e.g. linear

df %>%  ggplot(aes(date, col1)) +
  geom_point(colour= met.brewer("Isfahan1", 1)) +
  geom_smooth(formula = y~x, method = "lm", se= FALSE) +
  theme(
    axis.title.x=element_blank(),
    axis.text.x=element_blank(),
    axis.ticks.x=element_blank(),
    axis.title.y=element_blank(),
    axis.text.y=element_blank(),
    axis.ticks.y=element_blank(),
    legend.title=element_blank()) +
  scale_color_manual(values=met.brewer("Isfahan1", 13))

However, pay attention to the data you give to the ggplot function. If your date variable is not of numeric type, however, plot will be created without smooth path.

df = tibble(
  date = 1:55 %>% as.character(),
  col1 = ifelse(date %in% i1, 200, 100)
)

df %>%  ggplot(aes(date, col1)) +
  geom_point(colour= met.brewer("Isfahan1", 1)) +
  geom_smooth(formula = y~x, method = "loess", se= FALSE) +
  theme(
    axis.title.x=element_blank(),
    axis.text.x=element_blank(),
    axis.ticks.x=element_blank(),
    axis.title.y=element_blank(),
    axis.text.y=element_blank(),
    axis.ticks.y=element_blank(),
    legend.title=element_blank()) +
  scale_color_manual(values=met.brewer("Isfahan1", 13))

As you can see in this example, I changed the value of the variable date to type character (date = 1:55 %>% as.character()) which made geom_smooth to not draw anything.


问:
eslint imports in webpack: Unable to resolve path to module
With eslint-import-resolver-webpack I'm trying to let eslint know that I want to import files, by referencing a "shortcut" (eg. components/Counter).

In the example below, webpack (v2.2.0-rc.3) builds fine, but the test fails because it's "Unable to resolve path to module 'components/Counter'".
I get this error also for importing 'components/Counter/reducer', so it's not limited to index.

Both running npm run lint and my IDE (IntelliJ) give the same error.

Following the docs, I've set the following configs:

(Part of) file structure:

```<code>project-root/
  app/
    components/
      Counter/
        index.js
        reducer.js
    app.js
 internals/
   config/
      .eslintrc
      webpack.test.js
  package.json
</code>```

File: project-root/app/app.js

import Counter from 'components/Counter'
// etc...
```

<p>Excerpt of: project-root/package.json</p>

```...
"lint": "npm run lint:eslint -- . ",
"lint:eslint": "eslint -c internals/config/.eslintrc --fix --ignore-path .gitignore --ignore-pattern internals"
...
```

<p>File: project-root/config/.eslintrc</p>

<pre class="lang-json prettyprint-override"><code>{
  "parser": "babel-eslint",
  "extends": "airbnb",
  "env": {
    "browser": true,
    "node": true,
    "mocha": true,
    "es6": true
  },
  "plugins": [
    "redux-saga",
    "react",
    "jsx-a11y"
  ],
  "parserOptions": {
    "ecmaVersion": 6,
    "sourceType": "module",
    "ecmaFeatures": {
      "jsx": true
    }
  },
  "settings": {
    "import/resolver": {
      "webpack": {
        "config": "./internals/config/webpack.test.js"
      }
    }
  },
  "rules": {
    "arrow-parens": [
      "error",
      "always"
    ],
    "import/imports-first": 0,
    "import/newline-after-import": 0,
    "import/no-dynamic-require": 0,
    "import/no-extraneous-dependencies": 0,
    "import/no-named-as-default": 0,
    "import/prefer-default-export": 0,
    "jsx-a11y/aria-props": 2,
    "jsx-a11y/heading-has-content": 0,
    "jsx-a11y/href-no-hash": 2,
    "jsx-a11y/label-has-for": 2,
    "jsx-a11y/mouse-events-have-key-events": 2,
    "jsx-a11y/role-has-required-aria-props": 2,
    "jsx-a11y/role-supports-aria-props": 2,
    "max-len": [
      2,
      120,
      2,
      {
        "ignoreComments": true,
        "ignoreTrailingComments": false,
        "ignoreRegExpLiterals": true
      }
    ],
    "newline-per-chained-call": [
      2,
      {
        "ignoreChainWithDepth": 4
      }
    ],
    "no-console": [
      1,
      {
        "allow": [
          "warn",
          "error"
        ]
      }
    ],
    "no-use-before-define": [
      2,
      {
        "functions": false,
        "classes": true
      }
    ],
    "prefer-template": 2,
    "class-methods-use-this": 0,
    "react/forbid-prop-types": 0,
    "react/jsx-uses-vars": 2,
    "react/jsx-first-prop-new-line": [
      2,
      "multiline"
    ],
    "react/jsx-filename-extension": 0,
    "react/jsx-no-target-blank": 0,
    "react/prefer-stateless-function": 0,
    "react/require-extension": 0,
    "react/self-closing-comp": 0,
    "redux-saga/no-yield-in-race": 2,
    "redux-saga/yield-effects": 2,
    "semi": [
      2,
      "never"
    ]
  }
}
</code>```

And: project-root/internals/config/webpack.test.js:

const webpack = require('webpack')

module.exports = {
  devtool: 'inline-source-map',

  module: {
    loaders: [
      { test: /\.json$/, loader: 'json-loader' },

      { test: /\.css$/, loader: 'null-loader' },

      { test: /\.js$/,
        loader: 'babel',
        exclude: [/node_modules/],
      },

      { test: /\.jpe?g$|\.gif$|\.png$|\.svg$/i,
        loader: 'null-loader',
      },
    ],
  },

  plugins: [
    new webpack.DefinePlugin({
      'process.env': {
        NODE_ENV: JSON.stringify(process.env.NODE_ENV),
      },
    }),
  ],

  resolve: {
    modules: [
      'app',
      'node_modules',
    ],
  },
}
```

<p>Note: I've also tried pointing to a file that only exports the resolve object. Same thing:</p>

<pre class="lang-js prettyprint-override"><code>module.exports = {
  resolve: {
    modules: [
      'app',
      'node_modules',
    ],
  }
}
</code>```

答:
I believe you have missed some config in .eslintrc,js:

    'import/resolver': {
...,
      webpack: {
        config: {
          resolve: {
            alias: {
              // map your aliases here eg:
              components: '/src/components',
            },
          },
        },
      },
    },
```

Body:
With eslint-import-resolver-webpack I'm trying to let eslint know that I want to import files, by referencing a "shortcut" (eg. components/Counter).

In the example below, webpack (v2.2.0-rc.3) builds fine, but the test fails because it's "Unable to resolve path to module 'components/Counter'".
I get this error also for importing 'components/Counter/reducer', so it's not limited to index.

Both running npm run lint and my IDE (IntelliJ) give the same error.

Following the docs, I've set the following configs:

(Part of) file structure:

project-root/
  app/
    components/
      Counter/
        index.js
        reducer.js
    app.js
 internals/
   config/
      .eslintrc
      webpack.test.js
  package.json

File: project-root/app/app.js

import Counter from 'components/Counter'
// etc...

Excerpt of: project-root/package.json

...
"lint": "npm run lint:eslint -- . ",
"lint:eslint": "eslint -c internals/config/.eslintrc --fix --ignore-path .gitignore --ignore-pattern internals"
...

File: project-root/config/.eslintrc

{
  "parser": "babel-eslint",
  "extends": "airbnb",
  "env": {
    "browser": true,
    "node": true,
    "mocha": true,
    "es6": true
  },
  "plugins": [
    "redux-saga",
    "react",
    "jsx-a11y"
  ],
  "parserOptions": {
    "ecmaVersion": 6,
    "sourceType": "module",
    "ecmaFeatures": {
      "jsx": true
    }
  },
  "settings": {
    "import/resolver": {
      "webpack": {
        "config": "./internals/config/webpack.test.js"
      }
    }
  },
  "rules": {
    "arrow-parens": [
      "error",
      "always"
    ],
    "import/imports-first": 0,
    "import/newline-after-import": 0,
    "import/no-dynamic-require": 0,
    "import/no-extraneous-dependencies": 0,
    "import/no-named-as-default": 0,
    "import/prefer-default-export": 0,
    "jsx-a11y/aria-props": 2,
    "jsx-a11y/heading-has-content": 0,
    "jsx-a11y/href-no-hash": 2,
    "jsx-a11y/label-has-for": 2,
    "jsx-a11y/mouse-events-have-key-events": 2,
    "jsx-a11y/role-has-required-aria-props": 2,
    "jsx-a11y/role-supports-aria-props": 2,
    "max-len": [
      2,
      120,
      2,
      {
        "ignoreComments": true,
        "ignoreTrailingComments": false,
        "ignoreRegExpLiterals": true
      }
    ],
    "newline-per-chained-call": [
      2,
      {
        "ignoreChainWithDepth": 4
      }
    ],
    "no-console": [
      1,
      {
        "allow": [
          "warn",
          "error"
        ]
      }
    ],
    "no-use-before-define": [
      2,
      {
        "functions": false,
        "classes": true
      }
    ],
    "prefer-template": 2,
    "class-methods-use-this": 0,
    "react/forbid-prop-types": 0,
    "react/jsx-uses-vars": 2,
    "react/jsx-first-prop-new-line": [
      2,
      "multiline"
    ],
    "react/jsx-filename-extension": 0,
    "react/jsx-no-target-blank": 0,
    "react/prefer-stateless-function": 0,
    "react/require-extension": 0,
    "react/self-closing-comp": 0,
    "redux-saga/no-yield-in-race": 2,
    "redux-saga/yield-effects": 2,
    "semi": [
      2,
      "never"
    ]
  }
}

And: project-root/internals/config/webpack.test.js:

const webpack = require('webpack')

module.exports = {
  devtool: 'inline-source-map',

  module: {
    loaders: [
      { test: /\.json$/, loader: 'json-loader' },

      { test: /\.css$/, loader: 'null-loader' },

      { test: /\.js$/,
        loader: 'babel',
        exclude: [/node_modules/],
      },

      { test: /\.jpe?g$|\.gif$|\.png$|\.svg$/i,
        loader: 'null-loader',
      },
    ],
  },

  plugins: [
    new webpack.DefinePlugin({
      'process.env': {
        NODE_ENV: JSON.stringify(process.env.NODE_ENV),
      },
    }),
  ],

  resolve: {
    modules: [
      'app',
      'node_modules',
    ],
  },
}

Note: I've also tried pointing to a file that only exports the resolve object. Same thing:

module.exports = {
  resolve: {
    modules: [
      'app',
      'node_modules',
    ],
  }
}


问:
Can't create handler inside thread which has not called Looper.prepare() [xamarin]
So i don't actually have a question because i've already solved it, but in case someone else runs into this issue it's always nice to have a neat solution.

And while there is a plentitude of "Can't create handler inside thread which has not called Looper.prepare()" - questions there is none tagged with xamarin. (so theirs is all java and i had 0 matches for "Can't create handler inside thread which has not called Looper.prepare() [xamarin]")

答:
Very similar actually happend to me. Previous evening I was developing and testing my app. Next morning, from other computer I got the exception you described. I was remembered from a official Xamarin.Forms documentation that sometimes a bin and obj folder removal solves lot of issues.

I did exactly the same, removed my bin and obj folder from my shared Xamarin.Forms library and also from Xamarin.Android library.

The strange exception disappeared.


问:
Python: Unpacking tuple into variables, arithmetic operation type error
I am trying to understand why there is type error in the following code:

```<code>from itertools import product
# -10 2 -1 for example as an input

nums = input()
a, b, c = [int(x) for x in nums.split()]

for c in product((-1, 1), (-1, 1), (-1, 1)):
    x, y, z = c
    if (x * a + y * b + z * c) == 13:
        print("Yes")
        break
else:
    print("No")
</code>```

on (x * a + y * b + z * c) I get "TypeError: unsupported operand type(s) for +: 'int' and 'tuple'".
In debug x, y and z are indicated as (int) variables.
a, b and c are (int) as well. c is a tuple of (int). If all variables are of class (int) then why is that error?
Sorry for this post, a mistake.

答:
You replace "c" in for loop to "t" as tuple, because there are two variables called c: first type of int and second type of tuple.</p>
```<code>from itertools import product
# -10 2 -1 for example as an input

nums = input()
a, b, c = [int(x) for x in nums.split()]

for t in product((-1, 1), (-1, 1), (-1, 1)):
    x, y, z = t
    if (x * a + y * b + z * c) == 13:
        print("Yes")
        break
else:
    print("No")
</code>```

Body:
I am trying to understand why there is type error in the following code:

from itertools import product
# -10 2 -1 for example as an input

nums = input()
a, b, c = [int(x) for x in nums.split()]

for c in product((-1, 1), (-1, 1), (-1, 1)):
    x, y, z = c
    if (x * a + y * b + z * c) == 13:
        print("Yes")
        break
else:
    print("No")

on (x * a + y * b + z * c) I get "TypeError: unsupported operand type(s) for +: 'int' and 'tuple'".
In debug x, y and z are indicated as (int) variables.
a, b and c are (int) as well. c is a tuple of (int). If all variables are of class (int) then why is that error?
Sorry for this post, a mistake.

Body:
You replace "c" in for loop to "t" as tuple, because there are two variables called c: first type of int and second type of tuple.

from itertools import product
# -10 2 -1 for example as an input

nums = input()
a, b, c = [int(x) for x in nums.split()]

for t in product((-1, 1), (-1, 1), (-1, 1)):
    x, y, z = t
    if (x * a + y * b + z * c) == 13:
        print("Yes")
        break
else:
    print("No")