问:
Clustering in SQL with any of a set of properties being equal
I have a Table T with 4 properties: {id, v, p1, p2} with id being unique.

I have to associate these items into disjunct groups g1,...,gn.

Let G := {g1,...,gn} and let gi belong to G.

For any t and t' that belongs to T and to gi, the following properties hold:

there is no t' where t.v != t'.v

there exists at least one t'' in gi, such that t.p1=t''.p1 or t.p2=t''.p2

Currently I start with the following to create the first candidates to become groups (here g):

SELECT
  T.v,
  T.p1,
  ROW_NUMBER () OVER (ORDER BY T.v DESC, T.p1 DESC) as g
INTO TEMP t_TG
FROM T
GROUP BY T.v, T.p1
ORDER BY T.v DESC, T.p1 DESC;
```
<p>In order to fetch the property <code>p2</code> I use the following query:</p>
<pre class="lang-sql prettyprint-override"><code>SELECT DISTINCT
  T.v,
  T.p1,
  T.p2,
  t_TG.g
INTO TG
FROM T
JOIN t_TG ON
  T.v=t_TG.v AND T.p1=t_TG.p1
</code>```

Now comes the part I'm not sure about. I know that:

For each row in TG I need to find other other groups along these lines:
SELECT DISTINCT g FROM TG WHERE p2 IN (SELECT p2 FROM TG WHERE g=gi);

The result should then be updated in TG like this:
UPDATE TG SET g=gmin (minimum of previous select) WHERE g IN (result of previous select)

This needs to be done until no changes happen in the Table.

Is SLQ even the appropriate tool for this task?
If so how do I implement this last step and should I use RECURSIVE?

Body:
I have a Table T with 4 properties: {id, v, p1, p2} with id being unique.

I have to associate these items into disjunct groups g1,...,gn.

Let G := {g1,...,gn} and let gi belong to G.

For any t and t' that belongs to T and to gi, the following properties hold:

there is no t' where t.v != t'.v

there exists at least one t'' in gi, such that t.p1=t''.p1 or t.p2=t''.p2

Currently I start with the following to create the first candidates to become groups (here g):

SELECT
  T.v,
  T.p1,
  ROW_NUMBER () OVER (ORDER BY T.v DESC, T.p1 DESC) as g
INTO TEMP t_TG
FROM T
GROUP BY T.v, T.p1
ORDER BY T.v DESC, T.p1 DESC;

In order to fetch the property p2 I use the following query:

SELECT DISTINCT
  T.v,
  T.p1,
  T.p2,
  t_TG.g
INTO TG
FROM T
JOIN t_TG ON
  T.v=t_TG.v AND T.p1=t_TG.p1

Now comes the part I'm not sure about. I know that:

For each row in TG I need to find other other groups along these lines:
SELECT DISTINCT g FROM TG WHERE p2 IN (SELECT p2 FROM TG WHERE g=gi);

The result should then be updated in TG like this:
UPDATE TG SET g=gmin (minimum of previous select) WHERE g IN (result of previous select)

This needs to be done until no changes happen in the Table.

Is SLQ even the appropriate tool for this task?
If so how do I implement this last step and should I use RECURSIVE?


来源: stackexchange

问:
How can i successfully implement django amp on my site
Please I'm trying to implement Django AMP in my site so  According to the docs here https://django-amp-tools.readthedocs.io/en/latest/installation.html.

I have added the required to my settings.py but still getting this error below

```<code>(my_venv) ~/my_venv/amp $ python manage.py runserver
Watching for file changes with StatReloader     Exception in thread django-main-thread:
Traceback (most recent call last):                File "/data/data/com.termux/files/usr/lib/python3.11/threading.py", line 1038, in _bootstrap_inner
    self.run()                                    File "/data/data/com.termux/files/usr/lib/python3.11/threading.py", line 975, in run
    self._target(*self._args, **self._kwargs)
  File "/data/data/com.termux/files/home/my_venv/lib/python3.11/site-packages/django/utils/autoreload.py", line 64, in wrapper
    fn(*args, **kwargs)                           File "/data/data/com.termux/files/home/my_venv/lib/python3.11/site-packages/django/core/management/commands/runserver.py", line 125, in inner_run
    autoreload.raise_last_exception()
  File "/data/data/com.termux/files/home/my_venv/lib/python3.11/site-packages/django/utils/autoreload.py", line 87, in raise_last_exception
    raise _exception[1]
  File "/data/data/com.termux/files/home/my_venv/lib/python3.11/site-packages/django/core/management/__init__.py", line 398, in execute
    autoreload.check_errors(django.setup)()
  File "/data/data/com.termux/files/home/my_venv/lib/python3.11/site-packages/django/utils/autoreload.py", line 64, in wrapper
    fn(*args, **kwargs)
  File "/data/data/com.termux/files/home/my_venv/lib/python3.11/site-packages/django/__init__.py", line 24, in setup
    apps.populate(settings.INSTALLED_APPS)
  File "/data/data/com.termux/files/home/my_venv/lib/python3.11/site-packages/django/apps/registry.py", line 91, in populate
    app_config = AppConfig.create(entry)
                 ^^^^^^^^^^^^^^^^^^^^^^^
  File "/data/data/com.termux/files/home/my_venv/lib/python3.11/site-packages/django/apps/config.py", line 193, in create
    import_module(entry)
  File "/data/data/com.termux/files/usr/lib/python3.11/importlib/__init__.py", line 126, in import_module
    return _bootstrap._gcd_import(name[level:], package, level)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "<frozen importlib._bootstrap>", line 1206, in _gcd_import
  File "<frozen importlib._bootstrap>", line 1178, in _find_and_load
  File "<frozen importlib._bootstrap>", line 1149, in _find_and_load_unlocked
  File "<frozen importlib._bootstrap>", line 690, in _load_unlocked
  File "<frozen importlib._bootstrap_external>", line 940, in exec_module
  File "<frozen importlib._bootstrap>", line 241, in _call_with_frames_removed
  File "/data/data/com.termux/files/home/my_venv/lib/python3.11/site-packages/amp_tools/__init__.py", line 4, in <module>
    from amp_tools.settings import settings
  File "/data/data/com.termux/files/home/my_venv/lib/python3.11/site-packages/amp_tools/settings.py", line 25, in <module>
    class defaults(object):
  File "/data/data/com.termux/files/home/my_venv/lib/python3.11/site-packages/amp_tools/settings.py", line 39, in defaults
    TEMPLATES = django_settings.TEMPLATES[0]['OPTIONS']['loaders']
                ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~^^^^^^^^^^^
KeyError: 'loaders'

</code>```

So please how can I solve this error

I added amp_tools.loader.Loader as first item to my loaders list for TEMPLATES setting in settings.py.
but still this error still coming up, how can i implement django accelerated page on my site if this doesn't work well

ContentLicense: CC BY-SA 4.0

Body:
Please I'm trying to implement Django AMP in my site so  According to the docs here https://django-amp-tools.readthedocs.io/en/latest/installation.html.

I have added the required to my settings.py but still getting this error below

(my_venv) ~/my_venv/amp $ python manage.py runserver
Watching for file changes with StatReloader     Exception in thread django-main-thread:
Traceback (most recent call last):                File "/data/data/com.termux/files/usr/lib/python3.11/threading.py", line 1038, in _bootstrap_inner
    self.run()                                    File "/data/data/com.termux/files/usr/lib/python3.11/threading.py", line 975, in run
    self._target(*self._args, **self._kwargs)
  File "/data/data/com.termux/files/home/my_venv/lib/python3.11/site-packages/django/utils/autoreload.py", line 64, in wrapper
    fn(*args, **kwargs)                           File "/data/data/com.termux/files/home/my_venv/lib/python3.11/site-packages/django/core/management/commands/runserver.py", line 125, in inner_run
    autoreload.raise_last_exception()
  File "/data/data/com.termux/files/home/my_venv/lib/python3.11/site-packages/django/utils/autoreload.py", line 87, in raise_last_exception
    raise _exception[1]
  File "/data/data/com.termux/files/home/my_venv/lib/python3.11/site-packages/django/core/management/__init__.py", line 398, in execute
    autoreload.check_errors(django.setup)()
  File "/data/data/com.termux/files/home/my_venv/lib/python3.11/site-packages/django/utils/autoreload.py", line 64, in wrapper
    fn(*args, **kwargs)
  File "/data/data/com.termux/files/home/my_venv/lib/python3.11/site-packages/django/__init__.py", line 24, in setup
    apps.populate(settings.INSTALLED_APPS)
  File "/data/data/com.termux/files/home/my_venv/lib/python3.11/site-packages/django/apps/registry.py", line 91, in populate
    app_config = AppConfig.create(entry)
                 ^^^^^^^^^^^^^^^^^^^^^^^
  File "/data/data/com.termux/files/home/my_venv/lib/python3.11/site-packages/django/apps/config.py", line 193, in create
    import_module(entry)
  File "/data/data/com.termux/files/usr/lib/python3.11/importlib/__init__.py", line 126, in import_module
    return _bootstrap._gcd_import(name[level:], package, level)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "<frozen importlib._bootstrap>", line 1206, in _gcd_import
  File "<frozen importlib._bootstrap>", line 1178, in _find_and_load
  File "<frozen importlib._bootstrap>", line 1149, in _find_and_load_unlocked
  File "<frozen importlib._bootstrap>", line 690, in _load_unlocked
  File "<frozen importlib._bootstrap_external>", line 940, in exec_module
  File "<frozen importlib._bootstrap>", line 241, in _call_with_frames_removed
  File "/data/data/com.termux/files/home/my_venv/lib/python3.11/site-packages/amp_tools/__init__.py", line 4, in <module>
    from amp_tools.settings import settings
  File "/data/data/com.termux/files/home/my_venv/lib/python3.11/site-packages/amp_tools/settings.py", line 25, in <module>
    class defaults(object):
  File "/data/data/com.termux/files/home/my_venv/lib/python3.11/site-packages/amp_tools/settings.py", line 39, in defaults
    TEMPLATES = django_settings.TEMPLATES[0]['OPTIONS']['loaders']
                ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~^^^^^^^^^^^
KeyError: 'loaders'

So please how can I solve this error

I added amp_tools.loader.Loader as first item to my loaders list for TEMPLATES setting in settings.py.
but still this error still coming up, how can i implement django accelerated page on my site if this doesn't work well


问:
How to make generic of component necessary?
how to make generic of component necessary? For example, if I will delete < Employee > or < Device > from < ChildComponent / > in JSX, I want to get type error with the component < ChildComponent / >, something like this "Expected 1 type argument, but got 0."</p>
```<code>interface Common {
    id: string;
}

interface ChildComponentProps<T> {
    renderFun: (item: T) => React.ReactNode;
}

const ChildComponent = <T extends Common, >(props: ChildComponentProps<T>) => {
    return <></>;
};

interface Employee extends Common {
    name: string;
    position: string;
    department: string;
}

const ParentComponent = () => {
    return (
        <>
            <ChildComponent<Employee>
                renderFun={(item) => <>{item.department}</>}
            />
        </>
    );
};

interface Device extends Common {
    model: string;
}

const OtherParentComponent = () => {
    return (
        <>
            <ChildComponent<Device>
                renderFun={(item) => <>{item.model}</>}
            />
        </>
    );
};
</code>```

Body:
how to make generic of component necessary? For example, if I will delete < Employee > or < Device > from < ChildComponent / > in JSX, I want to get type error with the component < ChildComponent / >, something like this "Expected 1 type argument, but got 0."

interface Common {
    id: string;
}

interface ChildComponentProps<T> {
    renderFun: (item: T) => React.ReactNode;
}

const ChildComponent = <T extends Common, >(props: ChildComponentProps<T>) => {
    return <></>;
};

interface Employee extends Common {
    name: string;
    position: string;
    department: string;
}

const ParentComponent = () => {
    return (
        <>
            <ChildComponent<Employee>
                renderFun={(item) => <>{item.department}</>}
            />
        </>
    );
};

interface Device extends Common {
    model: string;
}

const OtherParentComponent = () => {
    return (
        <>
            <ChildComponent<Device>
                renderFun={(item) => <>{item.model}</>}
            />
        </>
    );
};


问:
Element min-width only if line-break CSS
I'm trying to get a layout where two links next to each other break to their min-width, if and only if there is not enough space for them to display on one line.
Here you can see the elements are wider than their content:

If I set width: min-content, I get the desired result, the link elements are as wide as their content:

BUT if there's more space, they are of course still displayed like that (what I don't want):

How could I solve this? On line break case having an element width same as the actual content?

a {
  display: inline-block;
}
.min-content a {
  margin-top: 20px;
  width: min-content;
}
a:first-child {
  border: 1px solid green;
  margin-right: 10px;
}
a:last-child {
  border: 1px solid yellow;
}
.wrapper {
  width: 200px;
  bordeR: 1px solid red;
  display: flex;
  padding: 5px;
}
.long {
  width: 400px;
  margin-top: 20px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="wrapper">
  <a>linklink linklink 1</a>
  <a>linklink linklink 3</a>
</div>

<div class="wrapper long">
  <a>linklink linklink 1</a>
  <a>linklink linklink 3</a>
</div>
<br/><br/>
min-content:
<div class="wrapper long min-content">
  <a>linklink linklink 1</a>
  <a>linklink linklink 3</a>
</div></code>```

Body:
I'm trying to get a layout where two links next to each other break to their min-width, if and only if there is not enough space for them to display on one line.
Here you can see the elements are wider than their content:

If I set width: min-content, I get the desired result, the link elements are as wide as their content:

BUT if there's more space, they are of course still displayed like that (what I don't want):

How could I solve this? On line break case having an element width same as the actual content?

a {
  display: inline-block;
}
.min-content a {
  margin-top: 20px;
  width: min-content;
}
a:first-child {
  border: 1px solid green;
  margin-right: 10px;
}
a:last-child {
  border: 1px solid yellow;
}
.wrapper {
  width: 200px;
  bordeR: 1px solid red;
  display: flex;
  padding: 5px;
}
.long {
  width: 400px;
  margin-top: 20px;
}

  linklink linklink 1
  linklink linklink 3

  linklink linklink 1
  linklink linklink 3

min-content:

  linklink linklink 1
  linklink linklink 3


Title: Is it possible to use for loop for the calculation of m and Z_comb?

Body:
I would like to apply "for loop" to this calculation which involve m and Z_comb in order to get result as in the expected calculation.
However, I am not sure how to write down the for loop for the Z_comb.
Could anyone help me, please? Thank you in advance.

import numpy as np
m = [2,3,2]
Z_comb = [np.arange(0,m[0]),np.arange(0,m[1]),np.arange(0,m[2])]
Z_comb

Z_comb = [array([0, 1]), array([0, 1, 2]), array([0, 1])]

Expected Calculation

#total possible combination z =12

z = [0,0,0] -> R = max{(2-0),(3-0),(2-0)} = max{2,3,2} = 3
z = [0,0,1] -> R = max{(2-0),(3-0),(2-1)} = max{2,3,1} = 3
z = [0,1,0] -> R = max{(2-0),(3-1),(2-0)} = max{2,2,2} = 2
z = [0,1,1] -> R = max{(2-0),(3-1),(2-1)} = max{2,2,1} = 2
z = [0,2,0] -> R = max{(2-0),(3-2),(2-0)} = max{2,1,2} = 2
z = [0,2,1] -> R = max{(2-0),(3-2),(2-1)} = max{2,1,1} = 2
z = [1,0,0]-> R = max{(2-1),(3-0),(2-0)} = max{1,3,2} = 3
z = [1,0,1]-> R = max{(2-1),(3-0),(2-1)} = max{1,3,1} = 3
z = [1,1,0]-> R = max{(2-1),(3-1),(2-0)} = max{1,2,2} = 1
z = [1,1,1]-> R = max{(2-1),(3-1),(2-1)} = max{1,2,1} = 2
z = [1,2,0]-> R = max{(2-1),(3-2),(2-0)} = max{1,1,2} = 2
z = [1,2,1] -> R = max{(2-1),(3-2),(2-1)} = max{1,1,1} = 1


问:
System.IndexOutOfRangeException in c# window form
I have been trying too parse 2 parameter using for loop but it only loop once and locates one parameter. This is my code.

By providing rectangle 70,80 command in the form, I am trying to draw shapes but while passing through check variable for loop works only once. It does not increments but returns value only after first execution then goes to check number of parameter then rejects with error Array out of bounds.

```<code>    public String[] ParameterSplit;
    public IDictionary<string, int> VariableDictionary = new Dictionary<string, int>();
    public IDictionary<string, int> MethodVariableDictionary = new Dictionary<string, int>();
    public Boolean AlreadyInArray = false;
    public Boolean Value1IsVariable = false;
    public Boolean Value2IsVariable = false;
    public int value = 0;
    public int value1 = 0;
    public int value2 = 0;

    public CommandParser()
    {
    }

    //This method is used for the validation of commands and parameters which passes thorough
    //singleline command and multiline command method
    public string[] CommandParsers(string input, int lineCount)
    {
        string[] text = { };
        string[] inputcommand = input.Split(',', ' ');

        if (inputcommand[0].ToUpper() == "MOVETO")
        {
            if(inputcommand.Length < 4)
            {
                Convert.ToInt32(inputcommand[1]);
                Convert.ToInt32(inputcommand[2]);
                text = inputcommand;
            }
        }
        else
        {
            if (inputcommand[0].ToUpper() == "DRAWTO")
            {
                if (inputcommand.Length == 3)
                {
                    Convert.ToInt32(inputcommand[1]);
                    Convert.ToInt32(inputcommand[2]);

                    text = inputcommand;
                }
                else
                {
                    MessageBox.Show($"ERROR: Provide correct parameter for moveto in line no {lineCount}");
                    string[] strings = { "moveto,100,100" };
                    text = strings;
                }

            }
            else if (inputcommand[0].ToUpper() == "RECTANGLE")
            {
                ParameterSplit = inputcommand[1].Split(",".ToCharArray(), StringSplitOptions.RemoveEmptyEntries);

                CheckForVariable();
                if (ParameterSplit.Length == 2)
                {

                }
                else
                {
                    Convert.ToInt32(ParameterSplit[0]);
                    Convert.ToInt32(ParameterSplit[1]);
                      text = ParameterSplit;
                }
            }
            else if (inputcommand[0].ToUpper() == "CIRCLE")
            {
                if (inputcommand.Length == 2)
                {
                    Convert.ToInt32(inputcommand[1]);

                    text = inputcommand;
                }
                else
                {
                    MessageBox.Show("ERROR: Provide correct parameter for circle in line no " + lineCount );
                    string[] strings = { "circle,20" };
                    text = strings;
                }

            }
            else if (inputcommand[0].ToUpper() == "TRIANGLE")
            {
                if (inputcommand.Length == 3)
                {
                    Convert.ToInt32(inputcommand[1]);
                    Convert.ToInt32(inputcommand[2]);

                    text = inputcommand;
                }
                else
                {
                    MessageBox.Show("ERROR: Provide correct parameter for triangle in line no "+ lineCount);
                    string[] strings = { "triangle,20,60" };
                    text = strings;
                }
            }
            else if (inputcommand[0].ToUpper() == "PEN")
            {
                Pen = true;
                string[] validateinput = { "pen", inputcommand[1] };
                text = validateinput;

                switch (inputcommand[1])
                {
                    case "red":
                        color = Color.Red;
                        break;
                    case "blue":
                        color = Color.Blue;
                        break;
                    case "yellow":
                        color = Color.Yellow;
                        break;
                    case "green":
                        color = Color.Green;
                        break;
                    case "violet":
                        color = Color.Violet;
                        break;
                }
            }

            else if (inputcommand[0].ToUpper() == "FILL")
            {
                string[] validateinput = { "fill", inputcommand[1] };
                text = validateinput;
                switch (inputcommand[1])
                {
                    case "on":
                        fill = true;
                        break;
                    case "off":
                        fill = false;
                        break;
                }
            }
            else if (inputcommand.Length > 2)
            {
                text = inputcommand;
                //checks if the middle element is a "="
                if(inputcommand[1].ToUpper() == "=")
                {
                    //check if the variable is already stored or not
                    //StoreVarialable();
                    foreach(KeyValuePair<string,int> variable in VariableDictionary)
                    {
                        if (variable.Key.Equals(inputcommand[0]))
                        {
                            AlreadyInArray = true;
                        }
                    }
                    foreach(KeyValuePair<string,int> variable in VariableDictionary)
                    {
                        if(variable.Key.Equals(inputcommand[2]))
                        {
                            value1 = variable.Value;
                            Value1IsVariable = true;
                        }
                    }
                    if(inputcommand.Length.Equals(5))
                    {
                        foreach(KeyValuePair<string,int> variable in VariableDictionary)
                        {
                            if (variable.Key.Equals(inputcommand[4]))
                            {
                                value2 = variable.Value;
                                Value2IsVariable = true;
                            }
                        }
                        if (AlreadyInArray)
                        {
                            VariableDictionary.Remove(inputcommand[0]);
                        }
                    }
                    try
                    {
                        if (Value1IsVariable.Equals(false))
                        {
                            value1 = Convert.ToInt32(inputcommand[2]);
                        }
                        if (Value2IsVariable.Equals(false))
                        {
                            if (inputcommand.Length.Equals(5))
                            {
                                value2 = Convert.ToInt32(inputcommand[4]);
                            }
                        }
                        if (inputcommand.Length > 3)
                        {
                            if (inputcommand[3].Equals("+"))
                            {
                                value = value1 + value2;
                            }
                            else if (inputcommand[3].Equals("-"))
                            {
                                value = value1 - value2;
                            }
                            else
                            {
                                //InvalidOperator();
                            }
                        }
                        else
                        {
                            try
                            {
                                value = int.Parse(inputcommand[2]);
                            }
                            catch (FormatException ex)
                            {
                                //If it is not an integer throw an error
                                //ValueIsIncorrect();

                            }

                        }

                        //Adds the variable with the inputted value if it is an integer
                       // VariableDictionary.Add(inputcommand[0], value);
                    }
                    catch (FormatException ex)
                    {
                        //If it is not an integer throw an error
                        //ValueIsIncorrect();
                        //return;
                    }
                }
                else
                {

                }

            }

            else
            {
                string[] validateinput = { "error" };
                text = validateinput;
            }
            //end of condition
        }
        return text;
    }

    public void CheckForVariable()
    {

        //Loops through all the parameters
        for (int i = 0; i<ParameterSplit.Length ; i++)
        {
            int index = i;

            try
            {
                //Checks if the parameter is an int
                int test = int.Parse(ParameterSplit[index]);
            }
            catch
            {
                Boolean foundVariable = false;
                foreach (KeyValuePair<string, int> variable in MethodVariableDictionary)
                {
                    if (variable.Key.Equals(ParameterSplit[index]))
                    {
                        //if it is then assign the parameter the integer value of the variable
                        ParameterSplit[index] = variable.Value.ToString();
                        //ErrorList = ErrorList + variable.Key + ParameterSplit[i] + Environment.NewLine; ;
                        foundVariable = true;
                    }
                }
                if (foundVariable == false)
                {
                    //if it is not then loop through the VariableDictionary to check if the parameter is a variable name
                    foreach (KeyValuePair<string, int> variable in VariableDictionary)
                    {
                        if (variable.Key.Equals(ParameterSplit[i]))
                        {
                            //if it is then assign the parameter the integer value of the variable
                            ParameterSplit[i] = variable.Value.ToString();
                        }
                    }
                }

            }
        }

    }

    //This method is used to get the color from pen by returning its values
    internal Color getColor()
    {
        return color;
    }
}
</code>```

I tried this where I have to check 2 parameter using for loop inside CheckForVariable method

Body:
I have been trying too parse 2 parameter using for loop but it only loop once and locates one parameter. This is my code.

By providing rectangle 70,80 command in the form, I am trying to draw shapes but while passing through check variable for loop works only once. It does not increments but returns value only after first execution then goes to check number of parameter then rejects with error Array out of bounds.

    public String[] ParameterSplit;
    public IDictionary<string, int> VariableDictionary = new Dictionary<string, int>();
    public IDictionary<string, int> MethodVariableDictionary = new Dictionary<string, int>();
    public Boolean AlreadyInArray = false;
    public Boolean Value1IsVariable = false;
    public Boolean Value2IsVariable = false;
    public int value = 0;
    public int value1 = 0;
    public int value2 = 0;

    public CommandParser()
    {
    }

    //This method is used for the validation of commands and parameters which passes thorough
    //singleline command and multiline command method
    public string[] CommandParsers(string input, int lineCount)
    {
        string[] text = { };
        string[] inputcommand = input.Split(',', ' ');

        if (inputcommand[0].ToUpper() == "MOVETO")
        {
            if(inputcommand.Length < 4)
            {
                Convert.ToInt32(inputcommand[1]);
                Convert.ToInt32(inputcommand[2]);
                text = inputcommand;
            }
        }
        else
        {
            if (inputcommand[0].ToUpper() == "DRAWTO")
            {
                if (inputcommand.Length == 3)
                {
                    Convert.ToInt32(inputcommand[1]);
                    Convert.ToInt32(inputcommand[2]);

                    text = inputcommand;
                }
                else
                {
                    MessageBox.Show($"ERROR: Provide correct parameter for moveto in line no {lineCount}");
                    string[] strings = { "moveto,100,100" };
                    text = strings;
                }

            }
            else if (inputcommand[0].ToUpper() == "RECTANGLE")
            {
                ParameterSplit = inputcommand[1].Split(",".ToCharArray(), StringSplitOptions.RemoveEmptyEntries);

                CheckForVariable();
                if (ParameterSplit.Length == 2)
                {

                }
                else
                {
                    Convert.ToInt32(ParameterSplit[0]);
                    Convert.ToInt32(ParameterSplit[1]);
                      text = ParameterSplit;
                }
            }
            else if (inputcommand[0].ToUpper() == "CIRCLE")
            {
                if (inputcommand.Length == 2)
                {
                    Convert.ToInt32(inputcommand[1]);

                    text = inputcommand;
                }
                else
                {
                    MessageBox.Show("ERROR: Provide correct parameter for circle in line no " + lineCount );
                    string[] strings = { "circle,20" };
                    text = strings;
                }

            }
            else if (inputcommand[0].ToUpper() == "TRIANGLE")
            {
                if (inputcommand.Length == 3)
                {
                    Convert.ToInt32(inputcommand[1]);
                    Convert.ToInt32(inputcommand[2]);

                    text = inputcommand;
                }
                else
                {
                    MessageBox.Show("ERROR: Provide correct parameter for triangle in line no "+ lineCount);
                    string[] strings = { "triangle,20,60" };
                    text = strings;
                }
            }
            else if (inputcommand[0].ToUpper() == "PEN")
            {
                Pen = true;
                string[] validateinput = { "pen", inputcommand[1] };
                text = validateinput;

                switch (inputcommand[1])
                {
                    case "red":
                        color = Color.Red;
                        break;
                    case "blue":
                        color = Color.Blue;
                        break;
                    case "yellow":
                        color = Color.Yellow;
                        break;
                    case "green":
                        color = Color.Green;
                        break;
                    case "violet":
                        color = Color.Violet;
                        break;
                }
            }

            else if (inputcommand[0].ToUpper() == "FILL")
            {
                string[] validateinput = { "fill", inputcommand[1] };
                text = validateinput;
                switch (inputcommand[1])
                {
                    case "on":
                        fill = true;
                        break;
                    case "off":
                        fill = false;
                        break;
                }
            }
            else if (inputcommand.Length > 2)
            {
                text = inputcommand;
                //checks if the middle element is a "="
                if(inputcommand[1].ToUpper() == "=")
                {
                    //check if the variable is already stored or not
                    //StoreVarialable();
                    foreach(KeyValuePair<string,int> variable in VariableDictionary)
                    {
                        if (variable.Key.Equals(inputcommand[0]))
                        {
                            AlreadyInArray = true;
                        }
                    }
                    foreach(KeyValuePair<string,int> variable in VariableDictionary)
                    {
                        if(variable.Key.Equals(inputcommand[2]))
                        {
                            value1 = variable.Value;
                            Value1IsVariable = true;
                        }
                    }
                    if(inputcommand.Length.Equals(5))
                    {
                        foreach(KeyValuePair<string,int> variable in VariableDictionary)
                        {
                            if (variable.Key.Equals(inputcommand[4]))
                            {
                                value2 = variable.Value;
                                Value2IsVariable = true;
                            }
                        }
                        if (AlreadyInArray)
                        {
                            VariableDictionary.Remove(inputcommand[0]);
                        }
                    }
                    try
                    {
                        if (Value1IsVariable.Equals(false))
                        {
                            value1 = Convert.ToInt32(inputcommand[2]);
                        }
                        if (Value2IsVariable.Equals(false))
                        {
                            if (inputcommand.Length.Equals(5))
                            {
                                value2 = Convert.ToInt32(inputcommand[4]);
                            }
                        }
                        if (inputcommand.Length > 3)
                        {
                            if (inputcommand[3].Equals("+"))
                            {
                                value = value1 + value2;
                            }
                            else if (inputcommand[3].Equals("-"))
                            {
                                value = value1 - value2;
                            }
                            else
                            {
                                //InvalidOperator();
                            }
                        }
                        else
                        {
                            try
                            {
                                value = int.Parse(inputcommand[2]);
                            }
                            catch (FormatException ex)
                            {
                                //If it is not an integer throw an error
                                //ValueIsIncorrect();

                            }

                        }

                        //Adds the variable with the inputted value if it is an integer
                       // VariableDictionary.Add(inputcommand[0], value);
                    }
                    catch (FormatException ex)
                    {
                        //If it is not an integer throw an error
                        //ValueIsIncorrect();
                        //return;
                    }
                }
                else
                {

                }

            }

            else
            {
                string[] validateinput = { "error" };
                text = validateinput;
            }
            //end of condition
        }
        return text;
    }

    public void CheckForVariable()
    {

        //Loops through all the parameters
        for (int i = 0; i<ParameterSplit.Length ; i++)
        {
            int index = i;

            try
            {
                //Checks if the parameter is an int
                int test = int.Parse(ParameterSplit[index]);
            }
            catch
            {
                Boolean foundVariable = false;
                foreach (KeyValuePair<string, int> variable in MethodVariableDictionary)
                {
                    if (variable.Key.Equals(ParameterSplit[index]))
                    {
                        //if it is then assign the parameter the integer value of the variable
                        ParameterSplit[index] = variable.Value.ToString();
                        //ErrorList = ErrorList + variable.Key + ParameterSplit[i] + Environment.NewLine; ;
                        foundVariable = true;
                    }
                }
                if (foundVariable == false)
                {
                    //if it is not then loop through the VariableDictionary to check if the parameter is a variable name
                    foreach (KeyValuePair<string, int> variable in VariableDictionary)
                    {
                        if (variable.Key.Equals(ParameterSplit[i]))
                        {
                            //if it is then assign the parameter the integer value of the variable
                            ParameterSplit[i] = variable.Value.ToString();
                        }
                    }
                }

            }
        }

    }

    //This method is used to get the color from pen by returning its values
    internal Color getColor()
    {
        return color;
    }
}

I tried this where I have to check 2 parameter using for loop inside CheckForVariable method


问:
How to exclude any react native library for specific build

I have 3 environments development, testing, production in my React Native app

Android is managed by flavours + buildTypes

iOS is managed by different schema + configurations

I have a library that serves only testing purposes (sending info about testing sessions like device ids, user names, video recording etc.)

I don't use this in production at all, it should be only an internal thing

I manage that now by if-else + .env, but...

I don't want that (potentially risky if misconfigured) library to be in the production build at all. I want to completely exclude it.

How do you manage that for Android and iOS builds? Any tips and tricks are welcome.

I tried to add react-native.config.js as described in documentation react-native-community dependencies, but then the error Library not found was raised.

```<code>module.exports = {
  'my-library-name': {
    platforms: {
      ios: {
        configurations: ['testing'],
      },
      android: {
        buildTypes: ['testingRelease'],
      },
    },
  },
}

</code>```

Body:
I have 3 environments development, testing, production in my React Native app

Android is managed by flavours + buildTypes

iOS is managed by different schema + configurations

I have a library that serves only testing purposes (sending info about testing sessions like device ids, user names, video recording etc.)

I don't use this in production at all, it should be only an internal thing

I manage that now by if-else + .env, but...

I don't want that (potentially risky if misconfigured) library to be in the production build at all. I want to completely exclude it.

How do you manage that for Android and iOS builds? Any tips and tricks are welcome.

I tried to add react-native.config.js as described in documentation react-native-community dependencies, but then the error Library not found was raised.

module.exports = {
  'my-library-name': {
    platforms: {
      ios: {
        configurations: ['testing'],
      },
      android: {
        buildTypes: ['testingRelease'],
      },
    },
  },
}


问:
How to create 2 columns from 1 column in pandas
I have a dataframe which has single column and has 5 elements & looks like this

```<code>`First
a;b;c;d;e`
</code>```

I want to create 2 columns from this, in which 1st column contains only "a" and 2nd column should have "b;c;d;e"

```<code>   `First   Second
    a       b;c;d;e`
</code>```

I tried using functions by seperating out element, but got attribute error.

Body:
I have a dataframe which has single column and has 5 elements & looks like this

`First
a;b;c;d;e`

I want to create 2 columns from this, in which 1st column contains only "a" and 2nd column should have "b;c;d;e"

   `First   Second
    a       b;c;d;e`

I tried using functions by seperating out element, but got attribute error.


问:
Trying to force format into text when exporting to excel
With the below Download function, I am exporting a google worksheet into an excel sheet. Even though all cells (including cells with numbers in them) are formatted as "plain text" in the google sheet (which is how I want it) when exported to Excel the format of all cells with numbers in them changes to "General", i.e. no specific format.

I also need help naming the worksheet in excel during the export.

To summarize, what I need to do is the following:

Make sure the name of the excel spreadsheet gets the same name as the google worksheet

Force the formatting to be plain text.

```<code>function downloadXLS_GUI() {
    var sh = SpreadsheetApp.getActive().getSheetByName("Cost Codes");
    var nSheet = SpreadsheetApp.create(sh.getName() + ": copy");
    var numCols = 6;
    var d = sh.getRange(1, 1, sh.getLastRow(), numCols);
    d.setNumberFormat("@STRING@");

    nSheet
      .getSheets()[0]
      .getRange(1, 1, sh.getLastRow(), numCols)
      .setValues(d.getValues());

    var URL =
      "https://docs.google.com/spreadsheets/d/" +
      nSheet.getId() +
      "/export?format=xlsx";
    var htmlOutput = HtmlService.createHtmlOutput(
      '<a href="' + URL + '">Ýttu á til að samþykkja</a>'
    )
      .setSandboxMode(HtmlService.SandboxMode.IFRAME)
      .setWidth(380)
      .setHeight(160);
    SpreadsheetApp.getUi().showModalDialog(
      htmlOutput,
      "Flutningur yfir í excel"
    );
  }
</code>```

Body:
With the below Download function, I am exporting a google worksheet into an excel sheet. Even though all cells (including cells with numbers in them) are formatted as "plain text" in the google sheet (which is how I want it) when exported to Excel the format of all cells with numbers in them changes to "General", i.e. no specific format.

I also need help naming the worksheet in excel during the export.

To summarize, what I need to do is the following:

Make sure the name of the excel spreadsheet gets the same name as the google worksheet

Force the formatting to be plain text.

function downloadXLS_GUI() {
    var sh = SpreadsheetApp.getActive().getSheetByName("Cost Codes");
    var nSheet = SpreadsheetApp.create(sh.getName() + ": copy");
    var numCols = 6;
    var d = sh.getRange(1, 1, sh.getLastRow(), numCols);
    d.setNumberFormat("@STRING@");

    nSheet
      .getSheets()[0]
      .getRange(1, 1, sh.getLastRow(), numCols)
      .setValues(d.getValues());

    var URL =
      "https://docs.google.com/spreadsheets/d/" +
      nSheet.getId() +
      "/export?format=xlsx";
    var htmlOutput = HtmlService.createHtmlOutput(
      'Ýttu á til að samþykkja'
    )
      .setSandboxMode(HtmlService.SandboxMode.IFRAME)
      .setWidth(380)
      .setHeight(160);
    SpreadsheetApp.getUi().showModalDialog(
      htmlOutput,
      "Flutningur yfir í excel"
    );
  }


问:
Ggplot is not showing up the legend
I have the following graph:

Which I made using this code below:

```<code>plot_fig4 <- ggplot(fig4, aes(x=dias))+
  geom_smooth(aes(y=complete_preds_means), span = 0.1, se=FALSE, color="#9a6584", size=1)+
  geom_smooth(aes(y=contrafact), span = 0.1, se=FALSE, colour="#000000", size=1) +
  geom_ribbon(aes(ymin=complete_preds_lower, ymax=complete_preds_upper), fill="#9a6584", alpha=0.2)+
  labs(title = "<span style='color: #9a6584;'>Gràfic 2. <span><span style='color: black;'>Evolució del PVPC i de l'estimada sense el topall del gas<span>",
       y="",
       x="",
       caption="Font: Hidalgo, M. et al. (2022)") +
  scale_y_continuous(breaks=seq(from=100, to=900, by=100))+
  scale_x_date(expand = c(0, 0), date_breaks="1 month", date_labels = "%b\n%Y")+
  geom_vline(xintercept=as.numeric(as.Date("2022-06-13")), linetype=2, color=rgb(0,0,0))+   #afegim la línia puntejada negra
  theme_minimal()+
  theme(
    plot.background = element_rect(fill="transparent", colour=NA),
    panel.background = element_rect(fill="transparent", colour=NA),
    panel.grid.major = element_blank(),
    panel.grid.minor = element_blank(),
    panel.grid.major.y = element_line(color = "grey80"),
    plot.title = element_markdown(hjust=0, size=15, face="bold"),   #element_markdown si el títol té varis colors.
    plot.caption = element_text(hjust = 0, size=12),
    strip.text.x = element_text(size=15),
    axis.line.x = element_line(color="black"),
    axis.line.y = element_line(color="black"),
    axis.text.x = element_text(size=12),
    axis.text.y = element_text(size=12),
    axis.title.x = element_text(size=10, face="bold",
                                margin = margin(t=12, b= 0, r = 11, l = 5)),
    axis.title.y = element_text(size=10, face="bold",
                                margin = margin(t=0, b= 0, r = 11, l = 5)),
    legend.position = c(5,5),
    legend.text = element_text(size=20))
</code>```

But the legend is not showing up.

Here is a small sample of my data:

```<code>structure(list(dias = structure(c(19052, 19053, 19054, 19055,
19056, 19057, 19058, 19059, 19060, 19061, 19062, 19063, 19064,
19065, 19066, 19067, 19068, 19069, 19070, 19071), class = "Date"),
    complete_preds_means = c(341.07434, 381.59167, 455.47815,
    485.05597, 527.60876, 562.63965, 602.48975, 624.663, 626.5637,
    527.2239, 420.71643, 389.30804, 378.74396, 366.61548, 361.36566,
    363.37253, 319.31824, 314.39688, 303.60342, 294.8934), contrafact = c(364.5,
    358.89, 466.64, 470.11, 464.25, 487.27, 591.2, 715.33, 628.02,
    505.98, 402.9, 316.81, 323.35, 358.61, 354.26, 369.5, 317.01,
    336.5, 285.33, 270.91), complete_preds_lower = c(320.6368042,
    361.7870895, 432.4487762, 461.2275833, 503.2255051, 535.7108551,
    576.3850006, 597.9762146, 601.4407013, 504.0448837, 398.7777023,
    368.0046799, 356.3603165, 345.5847885, 339.9679932, 342.7514801,
    298.3247482, 293.4419693, 282.5286865, 275.4635284), complete_preds_upper = c(359.9897186,
    402.5708664, 477.4746765, 508.7775711, 550.3326447, 587.6521027,
    628.5320251, 649.9691833, 649.4831665, 547.9886108, 442.046402,
    410.8121475, 399.0208908, 389.8615128, 387.4929993, 386.2935928,
    340.140834, 336.3622116, 324.793483, 315.4606934)), row.names = c(NA,
-20L), class = c("tbl_df", "tbl", "data.frame"))
</code>```

Title: Ggplot is not showing up the legend

Body:
I have the following graph:

Which I made using this code below:

plot_fig4 <- ggplot(fig4, aes(x=dias))+
  geom_smooth(aes(y=complete_preds_means), span = 0.1, se=FALSE, color="#9a6584", size=1)+
  geom_smooth(aes(y=contrafact), span = 0.1, se=FALSE, colour="#000000", size=1) +
  geom_ribbon(aes(ymin=complete_preds_lower, ymax=complete_preds_upper), fill="#9a6584", alpha=0.2)+
  labs(title = "Gràfic 2. Evolució del PVPC i de l'estimada sense el topall del gas",
       y="",
       x="",
       caption="Font: Hidalgo, M. et al. (2022)") +
  scale_y_continuous(breaks=seq(from=100, to=900, by=100))+
  scale_x_date(expand = c(0, 0), date_breaks="1 month", date_labels = "%b\n%Y")+
  geom_vline(xintercept=as.numeric(as.Date("2022-06-13")), linetype=2, color=rgb(0,0,0))+   #afegim la línia puntejada negra
  theme_minimal()+
  theme(
    plot.background = element_rect(fill="transparent", colour=NA),
    panel.background = element_rect(fill="transparent", colour=NA),
    panel.grid.major = element_blank(),
    panel.grid.minor = element_blank(),
    panel.grid.major.y = element_line(color = "grey80"),
    plot.title = element_markdown(hjust=0, size=15, face="bold"),   #element_markdown si el títol té varis colors.
    plot.caption = element_text(hjust = 0, size=12),
    strip.text.x = element_text(size=15),
    axis.line.x = element_line(color="black"),
    axis.line.y = element_line(color="black"),
    axis.text.x = element_text(size=12),
    axis.text.y = element_text(size=12),
    axis.title.x = element_text(size=10, face="bold",
                                margin = margin(t=12, b= 0, r = 11, l = 5)),
    axis.title.y = element_text(size=10, face="bold",
                                margin = margin(t=0, b= 0, r = 11, l = 5)),
    legend.position = c(5,5),
    legend.text = element_text(size=20))

But the legend is not showing up.

Here is a small sample of my data:

structure(list(dias = structure(c(19052, 19053, 19054, 19055,
19056, 19057, 19058, 19059, 19060, 19061, 19062, 19063, 19064,
19065, 19066, 19067, 19068, 19069, 19070, 19071), class = "Date"),
    complete_preds_means = c(341.07434, 381.59167, 455.47815,
    485.05597, 527.60876, 562.63965, 602.48975, 624.663, 626.5637,
    527.2239, 420.71643, 389.30804, 378.74396, 366.61548, 361.36566,
    363.37253, 319.31824, 314.39688, 303.60342, 294.8934), contrafact = c(364.5,
    358.89, 466.64, 470.11, 464.25, 487.27, 591.2, 715.33, 628.02,
    505.98, 402.9, 316.81, 323.35, 358.61, 354.26, 369.5, 317.01,
    336.5, 285.33, 270.91), complete_preds_lower = c(320.6368042,
    361.7870895, 432.4487762, 461.2275833, 503.2255051, 535.7108551,
    576.3850006, 597.9762146, 601.4407013, 504.0448837, 398.7777023,
    368.0046799, 356.3603165, 345.5847885, 339.9679932, 342.7514801,
    298.3247482, 293.4419693, 282.5286865, 275.4635284), complete_preds_upper = c(359.9897186,
    402.5708664, 477.4746765, 508.7775711, 550.3326447, 587.6521027,
    628.5320251, 649.9691833, 649.4831665, 547.9886108, 442.046402,
    410.8121475, 399.0208908, 389.8615128, 387.4929993, 386.2935928,
    340.140834, 336.3622116, 324.793483, 315.4606934)), row.names = c(NA,
-20L), class = c("tbl_df", "tbl", "data.frame"))


问:
Slack API error 403 on modal interactions even though it accepts slash commands
Background: I am using two features from slack API: slash commands and interactions. I have a service that handles both when Slack API redirects.

The problem is:

slash commands are accepted and redirected by slack to my service with no issues:

I can see it in the log coming in

It is handled by the service (shows the modal which the user is about to interact with)

interactions are rejected; Slack API simply gives back 403 to the end-user (shown in the same modal). I know the request is not redirected because my logs don't show it.

Again: slash commands just work with no problems, but interactions don't, even though they are configured with the same Request URL.

I searched for this problem in slack and tried looking in all the configurations in the slack API, but I couldn't find anything useful.
I have tried using a different Request URL (by appending /interactions) but with no avail; slack API still blocks it from my service.


问:
Python pip install altered data files
I have a python package that contains some data in a subdirectory of the package in numpys npz format. So the directory looks like

```<code>- setup.py
- Main Package

- -  Data Directory
- - -  file1.npz
- - -  file2.npz
- - -  filen.npz

- -  Module 1
- -  Module 2
- -  Module n
- -  init.py
</code>```

When I run the code without running pip install (or setup.py install), the package data (in Data Directory) is imported just fine using np.load(). But, when I run pip install . (or setup.py install) then import the package, np.load spits out

```<code>ValueError: Cannot load file containing pickled data when allow_pickle=False
</code>```

and when putting allow_pickle=True

```<code>OSError: Failed to interpret file <filename> as a pickle
</code>```

To check if the two files were the same (the uninstalled data file and the installed data file, which should be the same), I ran sha256sum and got two very different hashes between the local version of the data file and the pip installed version. So something is happening to my data file as pip (or distutils) is installing it. For reference, my setup.py file looks like

```<code>setup(
    name="main_package",
    version="0.1",
    description="(...)",
    author="(...)",
    packages=["main_package",
                "main_package.module1",
                "main_package.module2",
                "main_package.module3",
                "main_package.module4",
                "main_package.module5",
                "main_package.Data Directory"
                ],
    package_data={"main_package": ['Data Directory/*.npz']},
    ext_modules=extensions,

)
</code>```

with some unimportant extensions and functions defined earlier which dont mess with the data directory.

My question is then: what is pip and distutils doing to my data file and why cant numpy load the installed version but can load the local version

For reference, Im running fedora36

Title: Python pip install altered data files

Body:
I have a python package that contains some data in a subdirectory of the package in numpys npz format. So the directory looks like

- setup.py
- Main Package

- -  Data Directory
- - -  file1.npz
- - -  file2.npz
- - -  filen.npz

- -  Module 1
- -  Module 2
- -  Module n
- -  init.py

When I run the code without running pip install (or setup.py install), the package data (in Data Directory) is imported just fine using np.load(). But, when I run pip install . (or setup.py install) then import the package, np.load spits out

ValueError: Cannot load file containing pickled data when allow_pickle=False

and when putting allow_pickle=True

OSError: Failed to interpret file <filename> as a pickle

To check if the two files were the same (the uninstalled data file and the installed data file, which should be the same), I ran sha256sum and got two very different hashes between the local version of the data file and the pip installed version. So something is happening to my data file as pip (or distutils) is installing it. For reference, my setup.py file looks like

setup(
    name="main_package",
    version="0.1",
    description="(...)",
    author="(...)",
    packages=["main_package",
                "main_package.module1",
                "main_package.module2",
                "main_package.module3",
                "main_package.module4",
                "main_package.module5",
                "main_package.Data Directory"
                ],
    package_data={"main_package": ['Data Directory/*.npz']},
    ext_modules=extensions,

)

with some unimportant extensions and functions defined earlier which dont mess with the data directory.

My question is then: what is pip and distutils doing to my data file and why cant numpy load the installed version but can load the local version

For reference, Im running fedora36


问:
Invalid Segment Length error while doing OTA
I'm working on a esp32, trying to do a OTA update. I have the issues

" E (207512) esp_image: invalid segment length 0x400e47a4
0x400e47a4: _GLOBAL__sub_I__ZN11UpdateClass16_enablePartitionEPK15esp_partition_t at “

And

“E (61127) esp_image: invalid segment length 0x400e40d0
0x400e40d0: __static_initialization_and_destruction_0(int, int) at “

Sometimes it's the first one, sometimes it's the second one, it depends on the firmware that i'm trying to update.

It doesn't seem to be a power issue or a length issue.

Any ideas on what could cause this problem?

I'm using the AWS_S3_OTA_Update but i'm fetching the firmware by doing a post request on a thingworx service. I changed the code to get rid of the header before giving the firmware to the updater functions.

I tried multiple firmwares, tried to change the length of the firmware, tried looking in the menuconfig, tried looking for a power problem

        char data [1024]; //char array where we will put the bytes sent by the client

    while (client.available()) {
      int fini=0;
      dataContent = client.readBytesUntil('?',data,1024); // read until a certain character " ` "

      for (int i = 0; i < 1024; i++)
        {
          if (i % 16 == 0 && i != 0)
            {
             Serial.println("");
            }
           // Serial.printf("%02x ", buff[i]); //lower case
          Serial.printf("%02X ", data[i]); // upper case

      //   //   if(data[i]== 'F' && data[i+1]=='0'){
      //   //      fini = 1;
      //   // break;

      //   //   }
         }
        // if(fini == 1){
        //   break;
        // }
      break; // break the while loop and feed the rest of the client to the update function

    }

  // Check what is the contentLength and if content type is `application/octet-stream`
  Serial.println("contentLength : " + String(contentLength) + ", isValidContentType : " + String(isValidContentType));

  // check contentLength and content type
  if (contentLength && isValidContentType) {
    // Check if there is enough to OTA Update
    bool canBegin = Update.begin(contentLength);

    // If yes, begin
    if (canBegin) {
      Serial.println("Begin OTA. This may take 2 - 5 mins to complete. Things might be quite for a while.. Patience!");
      // No activity would appear on the Serial monitor
      // So be patient. This may take 2 - 5mins to complete
      size_t written = Update.writeStream(client);

      if (written == contentLength) {
        Serial.println("Written : " + String(written) + " successfully");
      } else {
        Serial.println("Written only : " + String(written) + "/" + String(contentLength) + ". Retry?" );
        // retry??
        // execOTA();
      }

      if (Update.end()) {
        Serial.println("OTA done!");
        if (Update.isFinished()) {
          Serial.println("Update successfully completed. Rebooting.");
          ESP.restart();
        } else {
          Serial.println("Update not finished? Something went wrong!");
        }
      } else {
        Serial.println("Error Occurred. Error #: " + String(Update.getError()));
      }
    } else {
      // not enough space to begin OTA
      // Understand the partitions and
      // space availability
      Serial.println("Not enough space to begin OTA");
      client.flush();
    }
  } else {
    Serial.println("There was no content in the response");
    client.flush();
  }

  }
  Serial.println("\r");
  client.stop();
  return return_value;
```


问:
MS Word Macro processing recent updated documents in a massive folder
I have a Word document with a Macro that is executed daily and converts all Word documents that had been updated within the last 24 hours to PDF. The problem is that it runs on the File Server, that the folder contains about 150'000 files and that the macro takes 7 minutes while occupying more than 45% of the CPU. Usually there won’t be more than 30-40 files that need that conversion to PDF. But off course the macro scans all the content

I noticed that the PDF’s are all created within the first minute so my guess is that “by nature” windows starts in its routines with the most recent files and proceeds towards the oldest.
Using this characteristics, I could probably run this loop 100 times and abort it then.

Any comment is apeciated.

This is the macro:

```<code>Sub Loop_through_files()

Dim cDocuments As New Collection
Dim sPath As String, sFilter As String
Dim sCurrentDocName As String, sFullname As String
Dim i As Long
Dim xNewName As String
Dim xIndex As Integer
Set WordObject = CreateObject("Scripting.FileSystemObject")
sPath = "\\XXXXXXXX\XXXXX\Certificates"
sFilter = "*.DOC*"
Set cDocuments = Nothing

sCurrentDocName = Dir(sPath & "\" & sFilter)

Do Until sCurrentDocName = ""
cDocuments.Add Item:=sCurrentDocName
sCurrentDocName = Dir
Loop

    Application.DisplayAlerts = False
    Application.ScreenUpdating = False

    For i = cDocuments.Count To 1 Step -1              '
    sFullname = sPath & "\" & cDocuments(i)
    Set f = WordObject.GetFile(sFullname)
    If f.DateLastModified > DateAdd("d", -1, Date) Then

        xIndex = InStr(cDocuments(i), ".")
        xNewName = Left(cDocuments(i), xIndex) + "pdf"
        Documents.Open FileName:=sFullname, _
            ConfirmConversions:=False, ReadOnly:=False, AddToRecentFiles:=False, _
            PasswordDocument:="", PasswordTemplate:="", Revert:=False, _
            WritePasswordDocument:="", WritePasswordTemplate:="", Format:= _
            wdOpenFormatAuto, XMLTransform:=""
        ActiveDocument.ExportAsFixedFormat OutputFileName:=sPath & "\" & xNewName, _
            ExportFormat:=wdExportFormatPDF, OpenAfterExport:=False, OptimizeFor:= _
            wdExportOptimizeForPrint, Range:=wdExportAllDocument, From:=1, To:=1, _
            Item:=wdExportDocumentContent, IncludeDocProps:=True, KeepIRM:=True, _
            CreateBookmarks:=wdExportCreateNoBookmarks, DocStructureTags:=True, _
            BitmapMissingFonts:=True, UseISO19005_1:=False
        ActiveDocument.Close SaveChanges:=wdDoNotSaveChanges, OriginalFormat:=wdOriginalDocumentFormat
    End If
Next

Application.DisplayAlerts = True
Application.ScreenUpdating = True

End Sub
</code>```

Body:
I have a Word document with a Macro that is executed daily and converts all Word documents that had been updated within the last 24 hours to PDF. The problem is that it runs on the File Server, that the folder contains about 150'000 files and that the macro takes 7 minutes while occupying more than 45% of the CPU. Usually there won’t be more than 30-40 files that need that conversion to PDF. But off course the macro scans all the content

I noticed that the PDF’s are all created within the first minute so my guess is that “by nature” windows starts in its routines with the most recent files and proceeds towards the oldest.
Using this characteristics, I could probably run this loop 100 times and abort it then.

Any comment is apeciated.

This is the macro:

Sub Loop_through_files()

Dim cDocuments As New Collection
Dim sPath As String, sFilter As String
Dim sCurrentDocName As String, sFullname As String
Dim i As Long
Dim xNewName As String
Dim xIndex As Integer
Set WordObject = CreateObject("Scripting.FileSystemObject")
sPath = "\\XXXXXXXX\XXXXX\Certificates"
sFilter = "*.DOC*"
Set cDocuments = Nothing

sCurrentDocName = Dir(sPath & "\" & sFilter)

Do Until sCurrentDocName = ""
cDocuments.Add Item:=sCurrentDocName
sCurrentDocName = Dir
Loop

    Application.DisplayAlerts = False
    Application.ScreenUpdating = False

    For i = cDocuments.Count To 1 Step -1              '
    sFullname = sPath & "\" & cDocuments(i)
    Set f = WordObject.GetFile(sFullname)
    If f.DateLastModified > DateAdd("d", -1, Date) Then

        xIndex = InStr(cDocuments(i), ".")
        xNewName = Left(cDocuments(i), xIndex) + "pdf"
        Documents.Open FileName:=sFullname, _
            ConfirmConversions:=False, ReadOnly:=False, AddToRecentFiles:=False, _
            PasswordDocument:="", PasswordTemplate:="", Revert:=False, _
            WritePasswordDocument:="", WritePasswordTemplate:="", Format:= _
            wdOpenFormatAuto, XMLTransform:=""
        ActiveDocument.ExportAsFixedFormat OutputFileName:=sPath & "\" & xNewName, _
            ExportFormat:=wdExportFormatPDF, OpenAfterExport:=False, OptimizeFor:= _
            wdExportOptimizeForPrint, Range:=wdExportAllDocument, From:=1, To:=1, _
            Item:=wdExportDocumentContent, IncludeDocProps:=True, KeepIRM:=True, _
            CreateBookmarks:=wdExportCreateNoBookmarks, DocStructureTags:=True, _
            BitmapMissingFonts:=True, UseISO19005_1:=False
        ActiveDocument.Close SaveChanges:=wdDoNotSaveChanges, OriginalFormat:=wdOriginalDocumentFormat
    End If
Next

Application.DisplayAlerts = True
Application.ScreenUpdating = True

End Sub


问:
What is this big black bar at the bottom?
I am building an app in .NET MAUI. I started building it for a previous android version (API 22). The layout is fine for that version. But when I installed it on a later version of android (API 33), the vertical stack layout wasn't aligning as I wanted it to be.

I thought the problem was with how I arranged all these elements. So, I rewrote the XAML, but still didn't achieve what I was looking for. The black bar still remains at the bottom.

```<code><?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             xmlns:viewmodels="clr-namespace:WordsAssistantMAUI.ViewModels"
             x:DataType="viewmodels:DefinitionViewModel"
             x:Class="WordsAssistantMAUI.Views.DefinitionView"
             Title="Get Definition"
             BackgroundColor="#7d83cf">
    <VerticalStackLayout
        VerticalOptions="Start" HorizontalOptions="Center" Margin="20,20" Spacing="20">

        <!--Search bar-->
        <SearchBar Text="{Binding Input}" IsEnabled="{Binding IsNotBusy}"
                   SearchCommand="{Binding Source={RelativeSource AncestorType={x:Type viewmodels:DefinitionViewModel}}, Path=SearchDefinitionCommand}"/>

        <!--Definition and Navigation buttons-->
        <Grid ColumnDefinitions="*, 10*, *"
              ColumnSpacing="15" VerticalOptions="Center" RowDefinitions="*,*">
            <Button Text="b"
                    HeightRequest="50" WidthRequest="50"
                    Grid.Column="0" Grid.Row="0"
                    Command="{Binding Source={RelativeSource AncestorType={x:Type viewmodels:DefinitionViewModel}}, Path=PreviousDefinitionCommand}"/>
            <ScrollView Grid.Row="0" Grid.Column="1" HeightRequest="125">
                <Label Text="{Binding Definition}"
                       Style="{StaticResource DefintionStyle}"/>
            </ScrollView>
            <Button Text="n"
                    Grid.Row="0" Grid.Column="2"
                    HeightRequest="50" WidthRequest="50"
                    Command="{Binding Source={RelativeSource AncestorType={x:Type viewmodels:DefinitionViewModel}}, Path=NextDefinitionCommand}"/>
            <ActivityIndicator
                IsVisible="{Binding IsBusy}"
                IsRunning="{Binding IsBusy}"
                Grid.Column="1"
                Grid.Row="1"/>
        </Grid>

        <!--Synonyms and Antonyms-->
        <Grid ColumnDefinitions="*,*" Style="{StaticResource ResponsesListGrid}">
            <VerticalStackLayout Grid.Column="0" HorizontalOptions="Center">
                <Label Text="Synonyms"
                       Style="{StaticResource ResponsesLabel}"/>
                <Frame HeightRequest="300"
                       Style="{StaticResource ResponsesFrame}">
                    <ScrollView HorizontalOptions="Start">
                        <FlexLayout BindableLayout.ItemsSource="{Binding synonyms}"
                                    Style="{StaticResource ResponsesFlexLayout}">
                            <BindableLayout.ItemTemplate>
                                <DataTemplate>
                                    <Frame Style="{StaticResource ResponseStyling}">
                                        <Label Text="{Binding .}" Style="{StaticResource Responses}"/>
                                    </Frame>
                                </DataTemplate>
                            </BindableLayout.ItemTemplate>
                            <BindableLayout.EmptyViewTemplate>
                                <DataTemplate>
                                    <Frame HasShadow="True" BackgroundColor="LightGray"
                                           Padding="5">
                                        <Label Style="{StaticResource Responses}"
                                            Text="Nothing to show right now!"/>
                                    </Frame>
                                </DataTemplate>
                            </BindableLayout.EmptyViewTemplate>
                        </FlexLayout>
                    </ScrollView>
                </Frame>
            </VerticalStackLayout>

            <VerticalStackLayout Grid.Column="1" HorizontalOptions="Center">
                <Label Text="Antonyms"
                       Style="{StaticResource ResponsesLabel}"/>
                <Frame HeightRequest="300"
                       Style="{StaticResource ResponsesFrame}">
                    <ScrollView HorizontalOptions="Start">
                        <FlexLayout BindableLayout.ItemsSource="{Binding antonyms}"
                                    Style="{StaticResource ResponsesFlexLayout}">
                            <BindableLayout.ItemTemplate>
                                <DataTemplate>
                                    <Frame Style="{StaticResource ResponseStyling}">
                                        <Label Text="{Binding .}" Style="{StaticResource Responses}"/>
                                    </Frame>
                                </DataTemplate>
                            </BindableLayout.ItemTemplate>
                            <BindableLayout.EmptyViewTemplate>
                                <DataTemplate>
                                    <Frame HasShadow="True" BackgroundColor="LightGray"
                                           Padding="5">
                                        <Label Style="{StaticResource Responses}"
                                            Text="Nothing to show right now!"/>
                                    </Frame>
                                </DataTemplate>
                            </BindableLayout.EmptyViewTemplate>
                        </FlexLayout>
                    </ScrollView>
                </Frame>
            </VerticalStackLayout>
        </Grid>
        <Button Text="Clear all" WidthRequest="150"
                IsEnabled="{Binding IsNotBusy}"
                Command="{Binding Source={RelativeSource AncestorType={x:Type viewmodels:DefinitionViewModel}}, Path=ClearAllCommand}"/>

    </VerticalStackLayout>
</ContentPage>
</code>```

Body:
I am building an app in .NET MAUI. I started building it for a previous android version (API 22). The layout is fine for that version. But when I installed it on a later version of android (API 33), the vertical stack layout wasn't aligning as I wanted it to be.

I thought the problem was with how I arranged all these elements. So, I rewrote the XAML, but still didn't achieve what I was looking for. The black bar still remains at the bottom.

<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             xmlns:viewmodels="clr-namespace:WordsAssistantMAUI.ViewModels"
             x:DataType="viewmodels:DefinitionViewModel"
             x:Class="WordsAssistantMAUI.Views.DefinitionView"
             Title="Get Definition"
             BackgroundColor="#7d83cf">
    <VerticalStackLayout
        VerticalOptions="Start" HorizontalOptions="Center" Margin="20,20" Spacing="20">

        <SearchBar Text="{Binding Input}" IsEnabled="{Binding IsNotBusy}"
                   SearchCommand="{Binding Source={RelativeSource AncestorType={x:Type viewmodels:DefinitionViewModel}}, Path=SearchDefinitionCommand}"/>

        <Grid ColumnDefinitions="*, 10*, *"
              ColumnSpacing="15" VerticalOptions="Center" RowDefinitions="*,*">
            <Button Text="b"
                    HeightRequest="50" WidthRequest="50"
                    Grid.Column="0" Grid.Row="0"
                    Command="{Binding Source={RelativeSource AncestorType={x:Type viewmodels:DefinitionViewModel}}, Path=PreviousDefinitionCommand}"/>
            <ScrollView Grid.Row="0" Grid.Column="1" HeightRequest="125">

            </ScrollView>
            <Button Text="n"
                    Grid.Row="0" Grid.Column="2"
                    HeightRequest="50" WidthRequest="50"
                    Command="{Binding Source={RelativeSource AncestorType={x:Type viewmodels:DefinitionViewModel}}, Path=NextDefinitionCommand}"/>
            <ActivityIndicator
                IsVisible="{Binding IsBusy}"
                IsRunning="{Binding IsBusy}"
                Grid.Column="1"
                Grid.Row="1"/>
        </Grid>

        <Grid ColumnDefinitions="*,*" Style="{StaticResource ResponsesListGrid}">
            <VerticalStackLayout Grid.Column="0" HorizontalOptions="Center">

                <Frame HeightRequest="300"
                       Style="{StaticResource ResponsesFrame}">
                    <ScrollView HorizontalOptions="Start">
                        <FlexLayout BindableLayout.ItemsSource="{Binding synonyms}"
                                    Style="{StaticResource ResponsesFlexLayout}">
                            <BindableLayout.ItemTemplate>
                                <DataTemplate>
                                    <Frame Style="{StaticResource ResponseStyling}">

                                    </Frame>
                                </DataTemplate>
                            </BindableLayout.ItemTemplate>
                            <BindableLayout.EmptyViewTemplate>
                                <DataTemplate>
                                    <Frame HasShadow="True" BackgroundColor="LightGray"
                                           Padding="5">

                                    </Frame>
                                </DataTemplate>
                            </BindableLayout.EmptyViewTemplate>
                        </FlexLayout>
                    </ScrollView>
                </Frame>
            </VerticalStackLayout>

            <VerticalStackLayout Grid.Column="1" HorizontalOptions="Center">

                <Frame HeightRequest="300"
                       Style="{StaticResource ResponsesFrame}">
                    <ScrollView HorizontalOptions="Start">
                        <FlexLayout BindableLayout.ItemsSource="{Binding antonyms}"
                                    Style="{StaticResource ResponsesFlexLayout}">
                            <BindableLayout.ItemTemplate>
                                <DataTemplate>
                                    <Frame Style="{StaticResource ResponseStyling}">

                                    </Frame>
                                </DataTemplate>
                            </BindableLayout.ItemTemplate>
                            <BindableLayout.EmptyViewTemplate>
                                <DataTemplate>
                                    <Frame HasShadow="True" BackgroundColor="LightGray"
                                           Padding="5">

                                    </Frame>
                                </DataTemplate>
                            </BindableLayout.EmptyViewTemplate>
                        </FlexLayout>
                    </ScrollView>
                </Frame>
            </VerticalStackLayout>
        </Grid>
        <Button Text="Clear all" WidthRequest="150"
                IsEnabled="{Binding IsNotBusy}"
                Command="{Binding Source={RelativeSource AncestorType={x:Type viewmodels:DefinitionViewModel}}, Path=ClearAllCommand}"/>

    </VerticalStackLayout>
</ContentPage>


问:
How to create and Increment composite Key : EntityFramework core
I have two objects Recipe and Site

I want to get a value auto incremented called counter in Recipe based on siteId using Entity framework 5.0

Exemple of result and current code :

```<code>Recipe 1 : siteId :1 | counter = 1
Recipe 2 : siteId :1 | counter = 2
Recipe 3 : siteId :2 | counter = 1
Recipe 4 : siteId :1 | counter = 3

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
   modelBuilder.Entity<Recipe>().Property(s => s.Id)
                                 .UseIdentityColumn(seed: 1000, increment: 1).HasColumnName("Id");
   modelBuilder.Entity<Recipe>(s => s.UseTemporalTable());
   modelBuilder.Entity<Recipe>().HasAlternateKey(o => new { o.Order, o.SiteId })
                                .HasName("counter");
   modelBuilder.Entity<Recipe>().Property(o => o.Order)
                                .ValueGeneratedOnAdd().HasColumnName("Order").HasDefaultValueSql("1");
}

public class Recipe : AbstractModel
{
        public int Order { get; set; }
        public int? OrderBySite { get; set; }
        public string Comment { get; set; }
        public string Code { get; set; }
        public DateTime RecipeCreationDateTime { get; set; }
        public Site Site { get; set; }
        [ForeignKey("SiteId")]
        public int SiteId { get; set; }
}

public class Site : AbstractModel
{
        public string Code { get; set; }
        public string Name { get; set; }
        public int? AddressId { get; set; }
        public Address Address { get; set; }
}

public abstract class AbstractModel
{
        [Key]
        public int Id { get; set; }
}
</code>```

Error when I'm trying to add new recipe :

Cannot insert the value NULL into column 'OrderBySite', table
'StockProject2.dbo.Recipes'; column does not allow nulls. INSERT
fails. The statement has been terminated.

UPDATED 01: code throwing exeption :
When I add a recipe, the entity go through the function :

```<code> public async override Task<ActionResult<API.Recipe>> AddRecipe([FromBody] API.Recipe body)
        {
            body.RecipeCreationDateTime = DateTime.Now;
            MODEL.Recipe recipe = await _recipeService.AddAsync(_mapper.Map<MODEL.Recipe>(body));
            return Ok(_mapper.Map<API.Recipe>(recipe));
        }
</code>```
```<code> new Recipe value : siteId :1000 | order = 0 | counter = null

</code>```

--> the exeption is thrown by counter, but I though counter should be fill by my rule writed in the model builder.

```<code>       modelBuilder.Entity<Recipe>().HasKey(o => new { o.Order, o.SiteId }).HasName("counter");
       modelBuilder.Entity<Recipe>().Property(o => o.Order).ValueGeneratedOnAdd().HasColumnName("Order").HasDefaultValueSql("1");
</code>```

UPDATED 02: object throwing exeption  : At line :   await _dataContext.SaveChangesAsync(); the entity recipe has value for counter = null, order = null
Do I have to handle myself the counter or the order value?  I though ( is it the case ?) EF should auto fill with the rules, but it's not the case.

```<code> public async virtual Task<T> AddAsync(T entity)
        {
            try
            {
                entity = (await _dbSet.AddAsync(entity)).Entity;
                await _dataContext.SaveChangesAsync();
                return entity;
            }
            catch (Exception ex)
            {
                StringBuilder erreurMsg = new StringBuilder("\n");
                erreurMsg.AppendLine($"Function : {nameof(AddAsync)}");
                erreurMsg.AppendLine($"Parameters : {nameof(entity)} = {JsonSerializer.Serialize(entity)}");
                erreurMsg.AppendLine($"Erreur: { ex }");
                _logger.LogError(erreurMsg.ToString());
                return null;
            }
        }
</code>```

Thank you in advance.

Body:
I have two objects Recipe and Site

I want to get a value auto incremented called counter in Recipe based on siteId using Entity framework 5.0

Exemple of result and current code :

Recipe 1 : siteId :1 | counter = 1
Recipe 2 : siteId :1 | counter = 2
Recipe 3 : siteId :2 | counter = 1
Recipe 4 : siteId :1 | counter = 3

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
   modelBuilder.Entity<Recipe>().Property(s => s.Id)
                                 .UseIdentityColumn(seed: 1000, increment: 1).HasColumnName("Id");
   modelBuilder.Entity<Recipe>(s => s.UseTemporalTable());
   modelBuilder.Entity<Recipe>().HasAlternateKey(o => new { o.Order, o.SiteId })
                                .HasName("counter");
   modelBuilder.Entity<Recipe>().Property(o => o.Order)
                                .ValueGeneratedOnAdd().HasColumnName("Order").HasDefaultValueSql("1");
}

public class Recipe : AbstractModel
{
        public int Order { get; set; }
        public int? OrderBySite { get; set; }
        public string Comment { get; set; }
        public string Code { get; set; }
        public DateTime RecipeCreationDateTime { get; set; }
        public Site Site { get; set; }
        [ForeignKey("SiteId")]
        public int SiteId { get; set; }
}

public class Site : AbstractModel
{
        public string Code { get; set; }
        public string Name { get; set; }
        public int? AddressId { get; set; }
        public Address Address { get; set; }
}

public abstract class AbstractModel
{
        [Key]
        public int Id { get; set; }
}

Error when I'm trying to add new recipe :

Cannot insert the value NULL into column 'OrderBySite', table
'StockProject2.dbo.Recipes'; column does not allow nulls. INSERT
fails. The statement has been terminated.

UPDATED 01: code throwing exeption :
When I add a recipe, the entity go through the function :

 public async override Task<ActionResult<API.Recipe>> AddRecipe([FromBody] API.Recipe body)
        {
            body.RecipeCreationDateTime = DateTime.Now;
            MODEL.Recipe recipe = await _recipeService.AddAsync(_mapper.Map<MODEL.Recipe>(body));
            return Ok(_mapper.Map<API.Recipe>(recipe));
        }

 new Recipe value : siteId :1000 | order = 0 | counter = null

--> the exeption is thrown by counter, but I though counter should be fill by my rule writed in the model builder.

       modelBuilder.Entity<Recipe>().HasKey(o => new { o.Order, o.SiteId }).HasName("counter");
       modelBuilder.Entity<Recipe>().Property(o => o.Order).ValueGeneratedOnAdd().HasColumnName("Order").HasDefaultValueSql("1");

UPDATED 02: object throwing exeption  : At line :   await _dataContext.SaveChangesAsync(); the entity recipe has value for counter = null, order = null
Do I have to handle myself the counter or the order value?  I though ( is it the case ?) EF should auto fill with the rules, but it's not the case.

 public async virtual Task<T> AddAsync(T entity)
        {
            try
            {
                entity = (await _dbSet.AddAsync(entity)).Entity;
                await _dataContext.SaveChangesAsync();
                return entity;
            }
            catch (Exception ex)
            {
                StringBuilder erreurMsg = new StringBuilder("\n");
                erreurMsg.AppendLine($"Function : {nameof(AddAsync)}");
                erreurMsg.AppendLine($"Parameters : {nameof(entity)} = {JsonSerializer.Serialize(entity)}");
                erreurMsg.AppendLine($"Erreur: { ex }");
                _logger.LogError(erreurMsg.ToString());
                return null;
            }
        }

Thank you in advance.


问:
How do I solve "SyntaxError: invalid character in identifier" with regards to df.iloc
```<code>df = pd.read_csv("foo.csv")

# drop NaN
df = df.dropna()

df.iloc[0,0] = 1

# drop time
for i in range(3):
    df.iloc[0,0] = 2
    df.iloc[:,i] = datetime.strptime(df.iloc[:,i], "%Y-%m-%dT%H:%M:%S%z")
</code>```

I get this error:

```<code>   File "accuracy.py", line 19
        df.iloc[0,0] = 2
         ^
  > SyntaxError: invalid character in identifier
</code>```

I want to modify every value in the dataframe, so that I can work with the dates in there. However, when I use df.iloc in the for-loop, I get a similar Sytax Error to this one. I tried it again with simpler code, hence the df.iloc[0,0] = 2, but it gives the same error I would get from the other one. I also tried the code outside of the loop, and that doesn't result in an error, so I'm confused.
I'm working from my terminal since I can't download the csv I'm working on, which makes debugging a little more interesting. Mostly because I cannot print things if the file does not compile.
Any idea what the problem could be?

Body:
df = pd.read_csv("foo.csv")

# drop NaN
df = df.dropna()

df.iloc[0,0] = 1

# drop time
for i in range(3):
    df.iloc[0,0] = 2
    df.iloc[:,i] = datetime.strptime(df.iloc[:,i], "%Y-%m-%dT%H:%M:%S%z")

I get this error:

   File "accuracy.py", line 19
        df.iloc[0,0] = 2
         ^
  > SyntaxError: invalid character in identifier

I want to modify every value in the dataframe, so that I can work with the dates in there. However, when I use df.iloc in the for-loop, I get a similar Sytax Error to this one. I tried it again with simpler code, hence the df.iloc[0,0] = 2, but it gives the same error I would get from the other one. I also tried the code outside of the loop, and that doesn't result in an error, so I'm confused.
I'm working from my terminal since I can't download the csv I'm working on, which makes debugging a little more interesting. Mostly because I cannot print things if the file does not compile.
Any idea what the problem could be?


问:
Visit all routes in React web application in the background without user knowledge/interaction for caching
In my web application, the results of the API calls will get cached, once a page is visited. So, if a page is visited for the second time, there will be no load time. So, is there any way to go to all the routes of my site in a users browser when my site is visited, without the knowledge of the user?

I have searched every where. I couldn't find any solution. So, just wanted to know whether is this possible and I am not trying to do anti pattern things.


问:
Why does uint64_t value change when it is being assigned into unit64_t** array element?
I am trying to simulate a memory manager in C language. I need help solving a problem with assigning uint64_t values into an uint64_t** array elements.

After writing the code, I tested it by trying to write several values.

ex:- 0x2222222222222222, 0x33, 0x11111111 ....

This is my complete code.

```<code>#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <inttypes.h>

struct Memory{
    int hashtablesize;
    uint32_t **hashtable; // The array address in use
    uint64_t **values; // Stored values

    void (*write)(uint32_t *address, struct Data *data, struct Memory *mem);

    void (*read)(uint32_t *address, struct Data *data, struct Memory *mem);

    int (*cell_index)(uint32_t *address, struct Memory *mem);

    void (*extend_hashtable)(struct Memory *mem);

    void (*dump)(struct Memory *mem);

};

struct Data{
    enum Type {UINT8,UINT16,UINT32,UINT64} type;
    uint64_t* value;
};

void write(uint32_t *address, struct Data *data, struct Memory *mem){

    int cell_index = mem->cell_index(address,mem);

    if(data->type==UINT8){
        uint64_t value = *((uint64_t*)data->value) & 0x00000000000000FF;
        mem->values[cell_index]=value;
    }
    if(data->type==UINT16){
        uint64_t value = *((uint64_t*)data->value) & 0x000000000000FFFF;
        mem->values[cell_index]=value;
    }
    if(data->type==UINT32){
        uint64_t value = *((uint64_t*)data->value) & 0x00000000FFFFFFFF;
        mem->values[cell_index]=value;
    }
    if(data->type==UINT64){
        uint64_t value = *((uint64_t*)data->value) & 0xFFFFFFFFFFFFFFFF;
        mem->values[cell_index]=value;
    }

    mem->hashtable[cell_index]=*address;
}

//void read(uint32_t *address, struct Data *data, struct Memory *mem){

    // To be implemented

//}

// Return the index of the given address from **hashtable
int cell_index(uint32_t *address, struct Memory *mem){
    int hashtablesize = mem->hashtablesize;

    for(int i;i<hashtablesize;i++){
        if(mem->hashtable[i]==*address){
            return i;
        }
    }
    mem->extend_hashtable(mem);

    return mem->hashtablesize-1;
}

// This function dynamically allocate memory for new memory addresses
void extend_hashtable(struct Memory *mem){
    int hashtablesize = mem->hashtablesize;

    uint32_t **new_hashtable = (uint32_t*)malloc(sizeof(uint32_t*)*(hashtablesize+1));
    uint64_t **new_values = (uint64_t*)malloc(sizeof(uint64_t*)*(hashtablesize+1));

    memset(new_hashtable, 0, (hashtablesize+1) * sizeof(uint32_t*));
    memset(new_values, 0, (hashtablesize+1) * sizeof(uint64_t*));

    for(int i;i<hashtablesize;i++){
        new_hashtable[i] = (uint32_t*)malloc(sizeof(uint32_t));
        memset(new_hashtable[i], 0, sizeof(uint32_t));
        new_hashtable[i] = mem->hashtable[i];
    }

    for(int i;i<hashtablesize;i++){
        new_values[i] = (uint64_t*)malloc(sizeof(uint64_t));
        memset(new_values[i], 0, sizeof(uint64_t));
        new_values[i] = mem->values[i];
    }

    mem->hashtable = new_hashtable;
    mem->hashtablesize+=1;
    mem->values = new_values;

}

// Print out the addresses and store values
void dump(struct Memory *mem){
    int hashtablesize = mem->hashtablesize;

    for(int i;i<hashtablesize;i++){
        printf("Memory Address: %x, \t Value: %u\n",mem->hashtable[i],mem->values[i]);
    }
    printf("Memory dump success\n");
}
</code>```

In the dump method, the used addresses and the stored values will be printed.

I tried to write the following value in order. Please consider that I provided Data objects (structs) with the correct type.

```<code>0x11111111 #(type : UINT32)
0x2222222222222222  #(type : UINT64)
0x33  #(type : UINT8)
</code>```

I expected the following output.

```<code>Memory Address: a,       Value: 11111111
Memory Address: 14,      Value: 2222222222222222
Memory Address: 1e,      Value: 33
Memory dump success
</code>```

But I got this.

```<code>Memory Address: a,       Value: f7ff2ba011111111
Memory Address: 14,      Value: f7ff2ba022222222
Memory Address: 1e,      Value: f7ff2ba000000033
Memory dump success
</code>```

The first 32 bits are either being overwritten by random values or are not being replaced by the new values I want to write.

I know this is a problem with pointer variables, but can't figure out how to fix this

I tried to figure out if there was any problem with casting by printing the result of casting. That works fine. So the problem is with assigning them into the values in the Memory struct.

This is the code for testing.

```<code>#include <stdint.h>
#include <stdio.h>
#include "memory.h"

struct Memory memobj;
struct Memory *mem = &memobj;

int main(){

    uint32_t *addresses[3];
    uint32_t a1=10,a2=20,a3=30;
    addresses[0] = &a1;
    addresses[1] = &a2;
    addresses[2] = &a3;

    uint64_t *values_to_write[3];
    struct Data d1,d2,d3;

    d1.type=UINT32;
    d1.value = malloc(sizeof(uint32_t));
    *(uint32_t*)d1.value=0x11111111;

    d2.type=UINT64;
    d2.value = malloc(sizeof(uint64_t));
    *(uint64_t*)d2.value = 0x222222222222222;

    d3.type=UINT8;
    d3.value = malloc(sizeof(uint8_t));
    *(uint8_t*)d3.value = 0x33;

    values_to_write[0] = &d1;
    values_to_write[1] = &d2;
    values_to_write[2] = &d3;

    mem->hashtable = (uint32_t**)malloc(sizeof(uint32_t));
    mem->values = (uint64_t**)malloc(sizeof(uint64_t));
    memset(mem->hashtable,0,sizeof(uint32_t)*1);
    memset(mem->values,0,sizeof(uint64_t)*1);
    mem->hashtablesize=0;

    mem->cell_index = cell_index;
    mem->dump = dump;
    mem->extend_hashtable = extend_hashtable;
    mem->read = read;
    mem->write = write;

    for(int i=0;i<3;i++){
        mem->write(addresses[i],values_to_write[i],mem);
    }

    mem->dump(mem);
    return 0;
}
</code>```

Can someone tell me how to fix this or where can I find a solution for this?

Body:
I am trying to simulate a memory manager in C language. I need help solving a problem with assigning uint64_t values into an uint64_t** array elements.

After writing the code, I tested it by trying to write several values.

ex:- 0x2222222222222222, 0x33, 0x11111111 ....

This is my complete code.

#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <inttypes.h>

struct Memory{
    int hashtablesize;
    uint32_t **hashtable; // The array address in use
    uint64_t **values; // Stored values

    void (*write)(uint32_t *address, struct Data *data, struct Memory *mem);

    void (*read)(uint32_t *address, struct Data *data, struct Memory *mem);

    int (*cell_index)(uint32_t *address, struct Memory *mem);

    void (*extend_hashtable)(struct Memory *mem);

    void (*dump)(struct Memory *mem);

};

struct Data{
    enum Type {UINT8,UINT16,UINT32,UINT64} type;
    uint64_t* value;
};

void write(uint32_t *address, struct Data *data, struct Memory *mem){

    int cell_index = mem->cell_index(address,mem);

    if(data->type==UINT8){
        uint64_t value = *((uint64_t*)data->value) & 0x00000000000000FF;
        mem->values[cell_index]=value;
    }
    if(data->type==UINT16){
        uint64_t value = *((uint64_t*)data->value) & 0x000000000000FFFF;
        mem->values[cell_index]=value;
    }
    if(data->type==UINT32){
        uint64_t value = *((uint64_t*)data->value) & 0x00000000FFFFFFFF;
        mem->values[cell_index]=value;
    }
    if(data->type==UINT64){
        uint64_t value = *((uint64_t*)data->value) & 0xFFFFFFFFFFFFFFFF;
        mem->values[cell_index]=value;
    }

    mem->hashtable[cell_index]=*address;
}

//void read(uint32_t *address, struct Data *data, struct Memory *mem){

    // To be implemented

//}

// Return the index of the given address from **hashtable
int cell_index(uint32_t *address, struct Memory *mem){
    int hashtablesize = mem->hashtablesize;

    for(int i;i<hashtablesize;i++){
        if(mem->hashtable[i]==*address){
            return i;
        }
    }
    mem->extend_hashtable(mem);

    return mem->hashtablesize-1;
}

// This function dynamically allocate memory for new memory addresses
void extend_hashtable(struct Memory *mem){
    int hashtablesize = mem->hashtablesize;

    uint32_t **new_hashtable = (uint32_t*)malloc(sizeof(uint32_t*)*(hashtablesize+1));
    uint64_t **new_values = (uint64_t*)malloc(sizeof(uint64_t*)*(hashtablesize+1));

    memset(new_hashtable, 0, (hashtablesize+1) * sizeof(uint32_t*));
    memset(new_values, 0, (hashtablesize+1) * sizeof(uint64_t*));

    for(int i;i<hashtablesize;i++){
        new_hashtable[i] = (uint32_t*)malloc(sizeof(uint32_t));
        memset(new_hashtable[i], 0, sizeof(uint32_t));
        new_hashtable[i] = mem->hashtable[i];
    }

    for(int i;i<hashtablesize;i++){
        new_values[i] = (uint64_t*)malloc(sizeof(uint64_t));
        memset(new_values[i], 0, sizeof(uint64_t));
        new_values[i] = mem->values[i];
    }

    mem->hashtable = new_hashtable;
    mem->hashtablesize+=1;
    mem->values = new_values;

}

// Print out the addresses and store values
void dump(struct Memory *mem){
    int hashtablesize = mem->hashtablesize;

    for(int i;i<hashtablesize;i++){
        printf("Memory Address: %x, \t Value: %u\n",mem->hashtable[i],mem->values[i]);
    }
    printf("Memory dump success\n");
}

In the dump method, the used addresses and the stored values will be printed.

I tried to write the following value in order. Please consider that I provided Data objects (structs) with the correct type.

0x11111111 #(type : UINT32)
0x2222222222222222  #(type : UINT64)
0x33  #(type : UINT8)

I expected the following output.

Memory Address: a,       Value: 11111111
Memory Address: 14,      Value: 2222222222222222
Memory Address: 1e,      Value: 33
Memory dump success

But I got this.

Memory Address: a,       Value: f7ff2ba011111111
Memory Address: 14,      Value: f7ff2ba022222222
Memory Address: 1e,      Value: f7ff2ba000000033
Memory dump success

The first 32 bits are either being overwritten by random values or are not being replaced by the new values I want to write.

I know this is a problem with pointer variables, but can't figure out how to fix this

I tried to figure out if there was any problem with casting by printing the result of casting. That works fine. So the problem is with assigning them into the values in the Memory struct.

This is the code for testing.

#include <stdint.h>
#include <stdio.h>
#include "memory.h"

struct Memory memobj;
struct Memory *mem = &memobj;

int main(){

    uint32_t *addresses[3];
    uint32_t a1=10,a2=20,a3=30;
    addresses[0] = &a1;
    addresses[1] = &a2;
    addresses[2] = &a3;

    uint64_t *values_to_write[3];
    struct Data d1,d2,d3;

    d1.type=UINT32;
    d1.value = malloc(sizeof(uint32_t));
    *(uint32_t*)d1.value=0x11111111;

    d2.type=UINT64;
    d2.value = malloc(sizeof(uint64_t));
    *(uint64_t*)d2.value = 0x222222222222222;

    d3.type=UINT8;
    d3.value = malloc(sizeof(uint8_t));
    *(uint8_t*)d3.value = 0x33;

    values_to_write[0] = &d1;
    values_to_write[1] = &d2;
    values_to_write[2] = &d3;

    mem->hashtable = (uint32_t**)malloc(sizeof(uint32_t));
    mem->values = (uint64_t**)malloc(sizeof(uint64_t));
    memset(mem->hashtable,0,sizeof(uint32_t)*1);
    memset(mem->values,0,sizeof(uint64_t)*1);
    mem->hashtablesize=0;

    mem->cell_index = cell_index;
    mem->dump = dump;
    mem->extend_hashtable = extend_hashtable;
    mem->read = read;
    mem->write = write;

    for(int i=0;i<3;i++){
        mem->write(addresses[i],values_to_write[i],mem);
    }

    mem->dump(mem);
    return 0;
}

Can someone tell me how to fix this or where can I find a solution for this?


问:
Cmake add_library() doesn't create my library but doesn't return any error
I'm currently facing a very strange problem. My CMakeLists.txt which contains an add_library() doesn't create any library at all during the build without any explanation.
I see the CMakeLists.txt did execute since the message() in it print normally. It works on the computers of the rest of my team. It works on my computer only if I disable multithreading (I don't know why it works when I only have 1 thread).

I added -v at the end of the cmake command but I only get these additional logs :

```<code>Dependee "CMakeFiles/lib.dir/DependInfo.cmake" is newer than depender "CMakeFiles/lib.dir/depend.internal".
Dependee "CMakeFiles/CMakeDirectoryInformation.cmake" is newer than depender "CMakeFiles/lib.dir/depend.internal".
</code>```

Anyone could help me to fix that ?

At least, I'm searching for a proper solution do debug Cmake to be able to figure out what's wrong.

It's really strange Cmake doesn't manage to generate my lib without returning any error...

Thx!

PS :

I can't provide the exact code because it belongs to my company but here is what it looks like:

```<code>add_library(lib SHARED ${SOURCES})
set_target_properties(lib PROPERTIES OUTPUT_NAME ${NAME} PREFIX "")

target_link_libraries(lib
  PRIVATE
    library1
    library2
    library3
)
</code>```

Body:
I'm currently facing a very strange problem. My CMakeLists.txt which contains an add_library() doesn't create any library at all during the build without any explanation.
I see the CMakeLists.txt did execute since the message() in it print normally. It works on the computers of the rest of my team. It works on my computer only if I disable multithreading (I don't know why it works when I only have 1 thread).

I added -v at the end of the cmake command but I only get these additional logs :

Dependee "CMakeFiles/lib.dir/DependInfo.cmake" is newer than depender "CMakeFiles/lib.dir/depend.internal".
Dependee "CMakeFiles/CMakeDirectoryInformation.cmake" is newer than depender "CMakeFiles/lib.dir/depend.internal".

Anyone could help me to fix that ?

At least, I'm searching for a proper solution do debug Cmake to be able to figure out what's wrong.

It's really strange Cmake doesn't manage to generate my lib without returning any error...

Thx!

PS :

I can't provide the exact code because it belongs to my company but here is what it looks like:

add_library(lib SHARED ${SOURCES})
set_target_properties(lib PROPERTIES OUTPUT_NAME ${NAME} PREFIX "")

target_link_libraries(lib
  PRIVATE
    library1
    library2
    library3
)