问:
Frequency cipher in F#
I'm currently working on a frequency-substitution cipher in F#. Meaning that I count all the occurrences of each letter in a text and when that is done I want to replace the letters based on the letter frequency in the english alphabet.

What i've done so far is that i've created a (char * float * char) list that contains (letter, frequency percentage, recommended letter). Let's say the letter P is the most occurring letter in my ciphered text (13.5 percent of letters are P) and E is the most used letter in english texts our list element will look like this ('P', 13.5, 'E'). This procedure is done all letters in the text, so we will end up with a list of all letters and their recommended replacement.

The problem I have is that I don't really know how to replace the letters in the cipher text with their recommended replacements.

```<code>Letter frequency in the english alphabet.
[(' ', 20.0); ('E', 12.02); ('T', 9.1); ('A', 8.12); ('O', 7.68); ('I', 7.31);
 ('N', 6.95); ('S', 6.28); ('R', 6.02); ('H', 5.92); ('D', 4.32); ('L', 3.98);
 ('U', 2.88); ('C', 2.71); ('M', 2.61); ('F', 2.3); ('Y', 2.11); ('W', 2.09);
 ('G', 2.03); ('P', 1.82); ('B', 1.49); ('V', 1.11); ('K', 0.69); ('X', 0.17);
 ('Q', 0.11); ('J', 0.1); ('Z', 0.07)]

Letter frequency in cipher.
[('W', 21.18); ('Z', 8.31); ('I', 7.7); ('P', 6.96); ('Y', 5.5); ('H', 5.48);
 ('G', 5.35); ('K', 5.3); ('N', 4.31); ('O', 4.31); ('M', 3.66); (' ', 2.83);
 ('A', 2.58); ('T', 2.38); ('Q', 2.22); ('B', 2.11); ('F', 2.11); ('.', 2.04);
 ('R', 1.62); ('S', 1.37); ('E', 1.06); ('X', 0.97); ('U', 0.25); ('L', 0.16);
 ('V', 0.11); ('J', 0.07); ('C', 0.02); ('D', 0.02)]

Recommended letter changes.
[('W', 21.18, ' '); ('Z', 8.31, 'E'); ('I', 7.7, 'T'); ('P', 6.96, 'A');
 ('Y', 5.5, 'O'); ('H', 5.48, 'I'); ('G', 5.35, 'N'); ('K', 5.3, 'S');
 ('N', 4.31, 'R'); ('O', 4.31, 'H'); ('M', 3.66, 'D'); (' ', 2.83, ' ');
 ('A', 2.58, 'L'); ('T', 2.38, 'U'); ('Q', 2.22, 'C'); ('B', 2.11, 'M');
 ('F', 2.11, 'F'); ('.', 2.04, 'Y'); ('R', 1.62, 'W'); ('S', 1.37, 'G');
 ('E', 1.06, 'P'); ('X', 0.97, 'B'); ('U', 0.25, 'V'); ('L', 0.16, 'K');
 ('V', 0.11, 'X'); ('J', 0.07, 'Q'); ('C', 0.02, 'J'); ('D', 0.02, 'Z')]
</code>```

If anyone have any ideas that would put me in the right direction on how to tackle the problem i'd be very appreciative since i've been stuck on this problem for some while now.

答:
Most likely you want a mapping operation. Something along the lines of myString |> String.map mappingFunction. Note that mapping function can also be a functor, or a curried higher order function.

The functor approach would allow you to put the frequencies into the object state.

The curried function would allow you to pass the frequencies as the parameter.

It's up to you to choose which approach makes more sense in your application and/or looks more natural.

Title: Frequency cipher in F#

Body:
I'm currently working on a frequency-substitution cipher in F#. Meaning that I count all the occurrences of each letter in a text and when that is done I want to replace the letters based on the letter frequency in the english alphabet.

What i've done so far is that i've created a (char * float * char) list that contains (letter, frequency percentage, recommended letter). Let's say the letter P is the most occurring letter in my ciphered text (13.5 percent of letters are P) and E is the most used letter in english texts our list element will look like this ('P', 13.5, 'E'). This procedure is done all letters in the text, so we will end up with a list of all letters and their recommended replacement.

The problem I have is that I don't really know how to replace the letters in the cipher text with their recommended replacements.

Letter frequency in the english alphabet.
[(' ', 20.0); ('E', 12.02); ('T', 9.1); ('A', 8.12); ('O', 7.68); ('I', 7.31);
 ('N', 6.95); ('S', 6.28); ('R', 6.02); ('H', 5.92); ('D', 4.32); ('L', 3.98);
 ('U', 2.88); ('C', 2.71); ('M', 2.61); ('F', 2.3); ('Y', 2.11); ('W', 2.09);
 ('G', 2.03); ('P', 1.82); ('B', 1.49); ('V', 1.11); ('K', 0.69); ('X', 0.17);
 ('Q', 0.11); ('J', 0.1); ('Z', 0.07)]

Letter frequency in cipher.
[('W', 21.18); ('Z', 8.31); ('I', 7.7); ('P', 6.96); ('Y', 5.5); ('H', 5.48);
 ('G', 5.35); ('K', 5.3); ('N', 4.31); ('O', 4.31); ('M', 3.66); (' ', 2.83);
 ('A', 2.58); ('T', 2.38); ('Q', 2.22); ('B', 2.11); ('F', 2.11); ('.', 2.04);
 ('R', 1.62); ('S', 1.37); ('E', 1.06); ('X', 0.97); ('U', 0.25); ('L', 0.16);
 ('V', 0.11); ('J', 0.07); ('C', 0.02); ('D', 0.02)]

Recommended letter changes.
[('W', 21.18, ' '); ('Z', 8.31, 'E'); ('I', 7.7, 'T'); ('P', 6.96, 'A');
 ('Y', 5.5, 'O'); ('H', 5.48, 'I'); ('G', 5.35, 'N'); ('K', 5.3, 'S');
 ('N', 4.31, 'R'); ('O', 4.31, 'H'); ('M', 3.66, 'D'); (' ', 2.83, ' ');
 ('A', 2.58, 'L'); ('T', 2.38, 'U'); ('Q', 2.22, 'C'); ('B', 2.11, 'M');
 ('F', 2.11, 'F'); ('.', 2.04, 'Y'); ('R', 1.62, 'W'); ('S', 1.37, 'G');
 ('E', 1.06, 'P'); ('X', 0.97, 'B'); ('U', 0.25, 'V'); ('L', 0.16, 'K');
 ('V', 0.11, 'X'); ('J', 0.07, 'Q'); ('C', 0.02, 'J'); ('D', 0.02, 'Z')]

If anyone have any ideas that would put me in the right direction on how to tackle the problem i'd be very appreciative since i've been stuck on this problem for some while now.


来源: stackexchange

问:
Numpy flatten dimension function
I am new to Python and am trying to extract RGB-encoded pixel labels from a numpy array. For example:

```<code>image.shape
>> (256, 256, 3)
</code>```

to be converted to:

```<code>image.shape
>> (256, 256, 1)
</code>```

based on a custom function. In Javascript such a function would be (the exact RGB encoding is, of course, irrelevant - but being able to use a custom function is relevant):

```<code>RGBtoVal = ([r,g,b])=>{
   r = Math.floor(r*9/255);
   g = Math.floor(g*9/255);
   b = Math.floor(b*9/255);
   if (r>0) return r+18;
   if (g>0) return r+9;
   return b;
}
</code>```

I understand that reshape and squeeze are helpful in reducing the dimensionality but without a function. Also, is a numpy matrix of shape (256,256,1) the same as (256,256)?

答:
being able to use a custom function is relevant

Converting a three-channel image into a single-channel image through a function is straightforward. For example:

In [96]: import numpy as np

In [97]: from skimage import data

In [98]: image = data.astronaut()

In [99]: def f(img):
    ...:     r, g, b = map(np.transpose, img.T)
    ...:     return np.floor(r*9/255) + np.sqrt(g) + np.cos(b)

In [100]: x = f(image)

In [101]: image.shape
Out[101]: (512, 512, 3)

In [102]: x.shape
Out[102]: (512, 512)
```

<blockquote>
  <p>is a numpy matrix of shape (256,256,1) the same as (256,256)?</p>
</blockquote>

<p>No. They are arrays of different shapes. </p>

<pre class="lang-py prettyprint-override"><code>In [103]: y = x[:, :, None]

In [104]: y.shape
Out[104]: (512, 512, 1)

In [105]: x[0, 0]
Out[105]: 13.1044921875

In [106]: y[0, 0]
Out[106]: array([13.10449219])

In [107]: y[0, 0, 0]
Out[107]: 13.1044921875
</code>```

The content of x and y is the same but x is two-dimensional whereas y is three-dimensional. It is worth noticing that indexing a three-dimensional array with just two indices yields a one-dimensional array of one element rather than a float value.

ContentLicense: CC BY-SA 4.0

Title: Numpy flatten dimension function

Body:
I am new to Python and am trying to extract RGB-encoded pixel labels from a numpy array. For example:

image.shape
>> (256, 256, 3)

to be converted to:

image.shape
>> (256, 256, 1)

based on a custom function. In Javascript such a function would be (the exact RGB encoding is, of course, irrelevant - but being able to use a custom function is relevant):

RGBtoVal = ([r,g,b])=>{
   r = Math.floor(r*9/255);
   g = Math.floor(g*9/255);
   b = Math.floor(b*9/255);
   if (r>0) return r+18;
   if (g>0) return r+9;
   return b;
}

I understand that reshape and squeeze are helpful in reducing the dimensionality but without a function. Also, is a numpy matrix of shape (256,256,1) the same as (256,256)?

Body:
being able to use a custom function is relevant

Converting a three-channel image into a single-channel image through a function is straightforward. For example:

In [96]: import numpy as np

In [97]: from skimage import data

In [98]: image = data.astronaut()

In [99]: def f(img):
    ...:     r, g, b = map(np.transpose, img.T)
    ...:     return np.floor(r*9/255) + np.sqrt(g) + np.cos(b)

In [100]: x = f(image)

In [101]: image.shape
Out[101]: (512, 512, 3)

In [102]: x.shape
Out[102]: (512, 512)

is a numpy matrix of shape (256,256,1) the same as (256,256)?

No. They are arrays of different shapes.

In [103]: y = x[:, :, None]

In [104]: y.shape
Out[104]: (512, 512, 1)

In [105]: x[0, 0]
Out[105]: 13.1044921875

In [106]: y[0, 0]
Out[106]: array([13.10449219])

In [107]: y[0, 0, 0]
Out[107]: 13.1044921875

The content of x and y is the same but x is two-dimensional whereas y is three-dimensional. It is worth noticing that indexing a three-dimensional array with just two indices yields a one-dimensional array of one element rather than a float value.


问:
how to resolve "Error: No module named 'airflow.www'" while starting airflow websever
Getting below error while starting Airflow webserver

balajee@Balajees-MacBook-Air.local:~$ airflow webserver -p 8080
[2018-12-03 00:29:37,066] {init.py:51} INFO - Using executor SequentialExecutor

[2018-12-03 00:29:38,776] {models.py:271} INFO - Filling up the DagBag from /Users/balajee/airflow/dags
Running the Gunicorn Server with:
Workers: 4 sync
Host: 0.0.0.0:8080
Timeout: 120

Logfiles: - -

Error: No module named 'airflow.www'

答:
I did this steps for the problem happens:

create a separate virtualenv only for airflow (I use anaconda distribution)

activate this env with conda activate

install airflow: pip install apache-airflow

at this moment the error No module named 'airflow.www' was showed for me

To fix follow this steps:

Look for where is your gunicorn in: whereis gunicorn

gunicorn have to stay only in your virtualenv directory: /home/yourname/anaconda3/envs/airflow_env/bin/gunicorn

If it stay in two directories, let it just in your airflow enviroment. Remove it all from another.

Another way to verify if gunicorn is in another directories is printing your PATH variable: echo $PATH. Look for gunicorn in /home/yourname/.local/bin and another anaconda directories from PATH. Remove all references. Remove gunicorn from conda base env as well: pip uninstall gunicorn.

With this steps, I think your problem will be solved.

I used anaconda distribution, but I think the same process can be done without it. I used airflow 1.10.0 and python 3.6.


问:
Please explain this code
Trying to make sense of the code below, as I want to customise it a bit.
As per the comments, the callback function is passed the last image to load as an argument. Can someone please explain how the callback is passed only to the last image (I understand why, I just don't know how)? From the way I'm reading the code it seems to be passed to all of them.

Cheers.

// $('img.photo',this).imagesLoaded(myFunction)
// execute a callback when all images have loaded.
// needed because .load() doesn't work on cached images

// mit license. paul irish. 2010.
// webkit fix from Oren Solomianik. thx!

// callback function is passed the last image to load
//   as an argument, and the collection as 'this'

$.fn.imagesLoaded = function(callback){
  var elems = this.filter('img'),
      len   = elems.length,
      blank = 'data:image/gif;base64,' +
          'R0lGODlhAQABAIAAAAAAAP///ywAAAAAAQABAAACAUwAOw==';

  elems.bind('load',function(){
      if (--len <= 0 && this.src !== blank){ callback.call(elems,this); }
  }).each(function(){
     // cached images don't fire load sometimes, so we reset src.
     if (this.complete || this.complete === undefined){
        var src = this.src;
        // webkit hack from
        // groups.google.com/group/jquery-dev/browse_thread/thread/eee6ab7b2da50e1f
        // data uri bypasses webkit log warning (thx doug jones)
        this.src = blank;
        this.src = src;
     }
  });

  return this;
};
```

答:
The evaluation for firing on the last element and resulting call to the callback func is found here

```<code>if (--len <= 0 && this.src !== blank){ callback.call(elems,this); }
</code>```

Note that it is bound to each item in elems, to fire off on the load event -- the code to do this is:

```<code>elems.bind('load',function(){ //.. Basically binds the following function to every item in elemns on load.
</code>```

So basically, this means that when an image loads, it will de-increment the len variable (--len) and check if that's less than or equal to zero, and make sure this element has an src; if both of those conditions are satisfied, which pretty much has to mean it is the last element in the set to fire the load event, then the callback func will fire.

ContentLicense: CC BY-SA 3.0

Title: Please explain this code

Body:
The evaluation for firing on the last element and resulting call to the callback func is found here

if (--len <= 0 && this.src !== blank){ callback.call(elems,this); }

Note that it is bound to each item in elems, to fire off on the load event -- the code to do this is:

elems.bind('load',function(){ //.. Basically binds the following function to every item in elemns on load.

So basically, this means that when an image loads, it will de-increment the len variable (--len) and check if that's less than or equal to zero, and make sure this element has an src; if both of those conditions are satisfied, which pretty much has to mean it is the last element in the set to fire the load event, then the callback func will fire.


问:
Discord.py bot dont have certificate
Yesterday I made a bot and everything was working, today when I try to run my code I have this error:

ClientConnectorCertificateError(aiohttp.client_exceptions.ClientConnectorCertificateError:
  Cannot connect to host discordapp.com:443 ssl:True
  [SSLCertVerificationError: (1, '[SSL: CERTIFICATE_VERIFY_FAILED]
  certificate verify failed: certificate has expired (_ssl.c:1108)')]

I am using win10, python 3.8, and pycharm.
I saw a similar problem on StackOverflow but the solution Is not working for me.

答:
Create a virtual environment in Anaconda and adding it as an interpreter in Pycharm.

Creation of the environment

```<code>conda create -n test_env python=3.8 anaconda
</code>```

Documentation of conda:

-n test_env sets the name of the environment to test_env

python=3.8 anaconda says that you want to use in this environment python in version 3.8. You can put there all the things you need, separated with spaces, e.g. sqlite matplotlib requests and specify their versions the same way as for python.

Activation

```<code>conda activate test_env
</code>```

Deactivation

```<code>conda deactivate
</code>```

Getting rid of it

```<code>conda remove -n test_env --all
</code>```

Add env to pycharm

1.In the Settings/Preferences dialog Ctrl+Alt+S, select Project  | Project Interpreter. Click the The Configure project interpreter icon and select Add.

In the left-hand pane of the Add Python Interpreter dialog, select Virtualenv Environment. The following actions depend on whether the virtual environment existed before.

here
Please check this github issue here.

Basically navigate to your Applications/Python 3.8/ folder and double
  click the Install Certificates.command.

Try running this same program on 3.8 and run the install certificates command.

You can directly run below instruction in conda prompt or terminal:

```<code>pip install certifi
</code>```

Or download this script and run it.

Title: Discord.py bot dont have certificate

Body:
Create a virtual environment in Anaconda and adding it as an interpreter in Pycharm.

Creation of the environment

conda create -n test_env python=3.8 anaconda

Documentation of conda:

-n test_env sets the name of the environment to test_env

python=3.8 anaconda says that you want to use in this environment python in version 3.8. You can put there all the things you need, separated with spaces, e.g. sqlite matplotlib requests and specify their versions the same way as for python.

Activation

conda activate test_env

Deactivation

conda deactivate

Getting rid of it

conda remove -n test_env --all

Add env to pycharm

1.In the Settings/Preferences dialog Ctrl+Alt+S, select Project  | Project Interpreter. Click the The Configure project interpreter icon and select Add.

In the left-hand pane of the Add Python Interpreter dialog, select Virtualenv Environment. The following actions depend on whether the virtual environment existed before.

here
Please check this github issue here.

Basically navigate to your Applications/Python 3.8/ folder and double
  click the Install Certificates.command.

Try running this same program on 3.8 and run the install certificates command.

You can directly run below instruction in conda prompt or terminal:

pip install certifi

Or download this script and run it.


问:
How to share message via LInkedin
I am trying create share button for sharing via Linkedin include title and description

I figured out that it possible to do via Custom URL, like that:
https://www.linkedin.com/shareArticle?mini=true&url=http://developer.linkedin.com&title=LinkedIn%20Developer%20Network&summary=My%20favorite%20developer%20program&source=LinkedIn

Request parameters:

if i try make it for my cause, it share only link not title and description:

https://www.linkedin.com/shareArticle?mini=true&url=https://www.athenatools.com/&title=ATHENA%20TOOLS&summary=THAT%20IS%20MY%20EXAMPLE&source=athenatools

Info i take from here: https://developer.linkedin.com/docs/share-on-linkedin

In conclusion, my question is how to make sharing include title, description and link at the site which i want

答:
As stated by Marcin, you must do URL encoding when passing one URL as a parameter to another URL's GET parameters (not just at LinkedIn URLs, but with all URLs).  But there's actually still a bit more here to solve!

You seem to be using an old format of the LinkedIn share API.  Since being acquired by Microsoft, much of LinkedIn's documentation (especially the up-to-date stuff) can be found on the Microsoft developer sites.  Take a look: Official Microsoft LinkedIn Sharing Documentation.  So, your URL should look like...

```<code>https://www.linkedin.com/sharing/share-offsite/?url={url}
</code>```

You are trying to also send a title and other parameters, but the only supported parameter is url.

You probably want to share title, etc., information, though, right?  In that case, set the og: tags in the  block of your HTML page, like so...

<meta property='og:title' content='Title of the article"/>

<meta property='og:image' content='//media.example.com/ 1234567.jpg"/>

<meta property='og:description' content='Description that will show in the preview"/>

<meta property='og:url' content='//www.example.com/URL of the article" />

Source: LinkedIn Documentation: Making Your Website Shareable on LinkedIn.

og: tags really are a good-standards practice, so why not?  If you want to know that you set up everything correctly, LinkedIn has you covered there, too:

LinkedIn Post Inspector : Check the URL you are trying to share to make sure everything is properly configured, with the right og: tags, etc..  Input the URL you are sharing, i.e., example.com/YourSite/ThisPageIsWhatYouWantToBeSharedOnLinkedIn.

Hope this helps!

Title: How to share message via LInkedin

Body:
As stated by Marcin, you must do URL encoding when passing one URL as a parameter to another URL's GET parameters (not just at LinkedIn URLs, but with all URLs).  But there's actually still a bit more here to solve!

You seem to be using an old format of the LinkedIn share API.  Since being acquired by Microsoft, much of LinkedIn's documentation (especially the up-to-date stuff) can be found on the Microsoft developer sites.  Take a look: Official Microsoft LinkedIn Sharing Documentation.  So, your URL should look like...

https://www.linkedin.com/sharing/share-offsite/?url={url}

You are trying to also send a title and other parameters, but the only supported parameter is url.

You probably want to share title, etc., information, though, right?  In that case, set the og: tags in the <head> block of your HTML page, like so...

<meta property='og:title' content='Title of the article"/>

<meta property='og:image' content='//media.example.com/ 1234567.jpg"/>

<meta property='og:description' content='Description that will show in the preview"/>

<meta property='og:url' content='//www.example.com/URL of the article" />

Source: LinkedIn Documentation: Making Your Website Shareable on LinkedIn.

og: tags really are a good-standards practice, so why not?  If you want to know that you set up everything correctly, LinkedIn has you covered there, too:

LinkedIn Post Inspector : Check the URL you are trying to share to make sure everything is properly configured, with the right og: tags, etc..  Input the URL you are sharing, i.e., example.com/YourSite/ThisPageIsWhatYouWantToBeSharedOnLinkedIn.

Hope this helps!


问:
SQL TIMESTAMP DEFAULT CURRENT TIMESTAMP: How to remove miliseconds?
Problem: When I print time in my HTML code it shows like this: 2020-05-31 03:29:50.617897

Code: https://i.stack.imgur.com/HTIXy.png

Question: How to get rid of decimal .617897? Thank you. I'm new to programming.

答:
In Postgres, you can use date_trunc():

```<code>select date_trunc('second', current_timestamp)
</code>```

Body:
In Postgres, you can use date_trunc():

select date_trunc('second', current_timestamp)


问:
cert in /etc/ssl/cert.pem expired today (MacOS Mojave)
The cert that is stored in /etc/ssl/cert.pem expired today on my Mojave computer, which has caused problems with my curl commands.  Is there anyway to update it?  I see that my Catalina computer has a newer certificate.  Can I just copy it over to my Mojave computer?</p>

答:
I think you have problem with AddTrust CA

What You Need to Do
  For most use cases, including certificates serving modern client or server systems, no action is required, whether or not you have issued certificates cross-chained to the AddTrust root.

As of April 30, 2020:  For business processes that depend on very old systems,  Sectigo has made available (by default in the certificate bundles) a new legacy root for cross-signing, the “AAA Certificate Services” root. However, please use extreme caution about any process that depends on very old legacy systems. Systems that have not received the updates necessary to support newer roots such as  Sectigo’s COMODO root will inevitably be missing other essential security updates and should be considered insecure. If you would still like to cross-sign to the AAA Certificate Services root, please contact Sectigo directly.

https://support.sectigo.com/articles/Knowledge/Sectigo-AddTrust-External-CA-Root-Expiring-May-30-2020


问:
Use default value with C# method overload
What is the best way to achieve this:
I have a class with 2 method overloads which I create n object from.
If I define b it will used and if not the default.
Where/How do I use this default without changing it permanently in the object.
What I did is the following but there must be a simpler way.</p>

```<code>.
.
.
private int b = 100;
private readonly int defualt_b = 100;

public void Press(int a)
{
...do something...
   Send(a, b);
}

public void Press(int a int new_b)
{
...do something...
    b = new_b; //set b to be used
     Press(a);
    b = default_b; //reset back to its default value
}
</code>```

答:
The context is not completely clear so I am not sure if I understood the problem correctly. Specifically is the private int b used anywhere else and thus needs to be set to some particular value ? Or is it just a helper field ? If the latter, then just change the dependency between the two overloads :

```<code>private const int DefualtB = 100;

public void Press(int a)
{
   Press(a, DefualtB);
}

public void Press(int a int new_b)
{
   ...do something...
   Send(a, new_b);
}
</code>```

EDIT: Also this assumes that those "..do something.." blocks in the original code were meant to be the same and done once. If not , then this will be somewhat more complicated.

Body:
What is the best way to achieve this:
I have a class with 2 method overloads which I create n object from.
If I define b it will used and if not the default.
Where/How do I use this default without changing it permanently in the object.
What I did is the following but there must be a simpler way.

.
.
.
private int b = 100;
private readonly int defualt_b = 100;

public void Press(int a)
{
...do something...
   Send(a, b);
}

public void Press(int a int new_b)
{
...do something...
    b = new_b; //set b to be used
     Press(a);
    b = default_b; //reset back to its default value
}

Body:
The context is not completely clear so I am not sure if I understood the problem correctly. Specifically is the private int b used anywhere else and thus needs to be set to some particular value ? Or is it just a helper field ? If the latter, then just change the dependency between the two overloads :

private const int DefualtB = 100;

public void Press(int a)
{
   Press(a, DefualtB);
}

public void Press(int a int new_b)
{
   ...do something...
   Send(a, new_b);
}

EDIT: Also this assumes that those "..do something.." blocks in the original code were meant to be the same and done once. If not , then this will be somewhat more complicated.


问:
how to optimize the best value for 'k' in FourierSeries
I am try to forecast 700 different product using autoARIMA in pmdarima package.
For seasonality, Fourier Series makes it easier, because all products pattern are different.

But, how can I select different values of "k", based on product in a loop.
Is there any test, or optimization function to do so?

```<code>pipe = Pipeline([
            ("fourier", FourierFeaturizer(m=12, k=3)),
            ("arima",   pm.AutoARIMA(exogenous=None, start_p=1, d=None, start_q=1, max_p=3,
                        max_d=2, max_q=3, start_P=1, D=None, start_Q=1, max_P=2,
                        max_D=1, max_Q=2, max_order=10, m=12, seasonal=False,
                        stationary=False, information_criterion='aic', alpha=0.05,
                        test='kpss', seasonal_test='ocsb', stepwise=False, n_jobs=1,
                        start_params=None, trend=None, method=None, transparams=True,
                        solver='nm', maxiter=None, disp=0, callback=None,
                        offset_test_args=None, seasonal_test_args=None,
                        suppress_warnings=True, error_action='warn', trace=True,
                        random=False, random_state=20, n_fits=30,`enter code here`
                        return_valid_fits=False, out_of_sample_size=0, scoring='mse',
                        scoring_args=None, with_intercept=True))])
</code>```

Please suggest. Thank you.

答:
Below is the loop created to get the  value of K for fourier transformation using minimal AIC. My data is at month frequency. It works for me.</p>

```<code> aic_best = np.inf
 len_k = 0
      trans = FourierFeaturizer(12, k)
                y_prime, exog = trans.fit_transform(y_train)
                model_auto_arima =  auto_arima(y_train, exogenous=exog, start_p=1, d=None, start_q=1, max_p=4, max_d=3, max_q=4, start_P=1,
                                    D=None, start_Q=1, max_P=2, max_D=1, max_Q=2, max_order=10, m=12, seasonal=False, stationary=False,
                                    information_criterion='aic', alpha=0.05, test='kpss', seasonal_test='ocsb', stepwise=False, n_jobs=1,
                                    start_params=None, trend=None, method='lbfgs', maxiter=50, offset_test_args=None, seasonal_test_args=None,
                                    suppress_warnings=True, error_action='warn', trace=False, random=False, random_state=20, n_fits=30,
                                    return_valid_fits=False, out_of_sample_size=0, scoring='mse', scoring_args=None, with_intercept=True,
                                    sarimax_kwargs=None)
                # aic_value = model_auto_arima.fit(y_train,exog).aic()
                aic_value = model_auto_arima.aic()
                print(aic_value)
                if aic_value < aic_best:
                    aic_best =  aic_value
                    len_k = k
                else:
                    pass
</code>```

Body:
I am try to forecast 700 different product using autoARIMA in pmdarima package.
For seasonality, Fourier Series makes it easier, because all products pattern are different.

But, how can I select different values of "k", based on product in a loop.
Is there any test, or optimization function to do so?

pipe = Pipeline([
            ("fourier", FourierFeaturizer(m=12, k=3)),
            ("arima",   pm.AutoARIMA(exogenous=None, start_p=1, d=None, start_q=1, max_p=3,
                        max_d=2, max_q=3, start_P=1, D=None, start_Q=1, max_P=2,
                        max_D=1, max_Q=2, max_order=10, m=12, seasonal=False,
                        stationary=False, information_criterion='aic', alpha=0.05,
                        test='kpss', seasonal_test='ocsb', stepwise=False, n_jobs=1,
                        start_params=None, trend=None, method=None, transparams=True,
                        solver='nm', maxiter=None, disp=0, callback=None,
                        offset_test_args=None, seasonal_test_args=None,
                        suppress_warnings=True, error_action='warn', trace=True,
                        random=False, random_state=20, n_fits=30,`enter code here`
                        return_valid_fits=False, out_of_sample_size=0, scoring='mse',
                        scoring_args=None, with_intercept=True))])

Please suggest. Thank you.

Body:
Below is the loop created to get the  value of K for fourier transformation using minimal AIC. My data is at month frequency. It works for me.

 aic_best = np.inf
 len_k = 0
      trans = FourierFeaturizer(12, k)
                y_prime, exog = trans.fit_transform(y_train)
                model_auto_arima =  auto_arima(y_train, exogenous=exog, start_p=1, d=None, start_q=1, max_p=4, max_d=3, max_q=4, start_P=1,
                                    D=None, start_Q=1, max_P=2, max_D=1, max_Q=2, max_order=10, m=12, seasonal=False, stationary=False,
                                    information_criterion='aic', alpha=0.05, test='kpss', seasonal_test='ocsb', stepwise=False, n_jobs=1,
                                    start_params=None, trend=None, method='lbfgs', maxiter=50, offset_test_args=None, seasonal_test_args=None,
                                    suppress_warnings=True, error_action='warn', trace=False, random=False, random_state=20, n_fits=30,
                                    return_valid_fits=False, out_of_sample_size=0, scoring='mse', scoring_args=None, with_intercept=True,
                                    sarimax_kwargs=None)
                # aic_value = model_auto_arima.fit(y_train,exog).aic()
                aic_value = model_auto_arima.aic()
                print(aic_value)
                if aic_value < aic_best:
                    aic_best =  aic_value
                    len_k = k
                else:
                    pass


问:
Print specific "columns" of text file that has a somewhat inconsistent format
I'm trying to extract three columns from a text file that looks like this:

```<code><Record type="HKQuantityTypeIdentifierHeartRate" sourceName="Michael’s Apple Watch" sourceVersion="6.2.5" device="<<HKDevice: 0x2877dc870>, name:WHOOP 3A020013, manufacturer:WHOOP Inc., localIdentifier:80A56B86-0DEC-A6C3-7B22-077BD4BE4C8D>" unit="count/min" creationDate="2020-05-30 07:26:39 -0400" startDate="2020-05-30 07:26:39 -0400" endDate="2020-05-30 07:26:39 -0400" value="72">
<Record type="HKQuantityTypeIdentifierHeartRate" sourceName="Wahoo" sourceVersion="3135" unit="count/min" creationDate="2020-05-30 07:37:05 -0400" startDate="2020-05-30 07:35:46 -0400" endDate="2020-05-30 07:37:01 -0400" value="83"/>
</code>```

This is the information I'd like to extract:

```<code>sourceName, creationDate, value
"Michael’s Apple Watch", "2020-05-30 07:26:39", "72"
"Wahoo", "2020-05-30 07:37:05", "83"
</code>```

So I basically need the source name, full creationDate and value in a comma-separated format.

The issue I'm having is that sourceName itself has multiple nested "fields" and creationDate has spaces. So my previous attempts using grep and awk all failed :)

Any help would be greatly appreciated.

答:
It's much better to use an XML parser like in the answer of Cyrus.

But if all of your data is consistent with the small sample you provided, this might work for you:

```<code>BEGIN { q="\""; FS="="; OFS=","; print "sourceName,creationDate,value" }
{
    for (i=1; i<NF; ++i) {
        v = $(i+1)
        split(v, a, q)
        if ($i ~ / sourceName$/) sourceName = q a[2] q
        else if ($i ~ / creationDate$/) creationDate = q a[2] q
        else if ($i ~ / value$/) value = q a[2] q
    }
    print sourceName, creationDate, value
}
</code>```

==

```<code>$ awk -f a.awk file
sourceName,creationDate,value
"Michael’s Apple Watch","2020-05-30 07:26:39 -0400","72"
"Wahoo","2020-05-30 07:37:05 -0400","83"
</code>```

Body:
I'm trying to extract three columns from a text file that looks like this:

<Record type="HKQuantityTypeIdentifierHeartRate" sourceName="Michael’s Apple Watch" sourceVersion="6.2.5" device="<<HKDevice: 0x2877dc870>, name:WHOOP 3A020013, manufacturer:WHOOP Inc., localIdentifier:80A56B86-0DEC-A6C3-7B22-077BD4BE4C8D>" unit="count/min" creationDate="2020-05-30 07:26:39 -0400" startDate="2020-05-30 07:26:39 -0400" endDate="2020-05-30 07:26:39 -0400" value="72">
<Record type="HKQuantityTypeIdentifierHeartRate" sourceName="Wahoo" sourceVersion="3135" unit="count/min" creationDate="2020-05-30 07:37:05 -0400" startDate="2020-05-30 07:35:46 -0400" endDate="2020-05-30 07:37:01 -0400" value="83"/>

This is the information I'd like to extract:

sourceName, creationDate, value
"Michael’s Apple Watch", "2020-05-30 07:26:39", "72"
"Wahoo", "2020-05-30 07:37:05", "83"

So I basically need the source name, full creationDate and value in a comma-separated format.

The issue I'm having is that sourceName itself has multiple nested "fields" and creationDate has spaces. So my previous attempts using grep and awk all failed :)

Any help would be greatly appreciated.

Body:
It's much better to use an XML parser like in the answer of Cyrus.

But if all of your data is consistent with the small sample you provided, this might work for you:

BEGIN { q="\""; FS="="; OFS=","; print "sourceName,creationDate,value" }
{
    for (i=1; i<NF; ++i) {
        v = $(i+1)
        split(v, a, q)
        if ($i ~ / sourceName$/) sourceName = q a[2] q
        else if ($i ~ / creationDate$/) creationDate = q a[2] q
        else if ($i ~ / value$/) value = q a[2] q
    }
    print sourceName, creationDate, value
}

==

$ awk -f a.awk file
sourceName,creationDate,value
"Michael’s Apple Watch","2020-05-30 07:26:39 -0400","72"
"Wahoo","2020-05-30 07:37:05 -0400","83"


问:
Is there an equivalent of canvas's toDataURL method for SVG?
I am trying to load an svg image into canvas for pixel manipulation
I need a method like toDataURL or getImageData for svg

on Chrome/Safari I can try doing it through and image and canvas

```<code>var img = new Image()
img.onload = function(){
  ctx.drawImage(img,0,0) //this correctly draws the svg image to the canvas! however...
  var dataURL = canvas.toDataURL(); //SECURITY_ERR: DOM Exception 18
  var data = ctx.getImageData(0,0,img.width, img.height).data //also SECURITY_ERR: DOM Exception 18
  }
  img.src = "image.svg" //that is an svg file. (same domain as html file :))
</code>```

But I get security errors.
Any other way?

Here is a live demo of the problem http://clstff.appspot.com/gist/462846 (you can view source)

答:
Illustrating Hubert OG 's answer with code; 2 remarks first.

First (thank you, Robert Longson), it might work without encodeURIComponent, but you better include it (for example, if you have something like fill="url(#pattern)" the encodeURIComponent is necessary, because of the # character)

Second, the SVG namespace is not optional, but it might not be included in svgElt.outerHTML. Especially, if you have created your svg node via createElementNS, like so

```<code>svgElt = document.createElementNS("http://www.w3.org/2000/svg", 'svg')
</code>```

then a subsequent call to svgElt.outerHTML will not contain the namespace attribute, and this would result in not working code, unless you include the namespace attribute later in some fashion

var imgEnc    = new Image();
var imgEncNS  = new Image();
var prefix    = 'data:image/svg+xml,';
var svgOpen   = '<svg width="200" height="30">';
var svgClose  = '</svg>';
var svgOpenNS = '<svg xmlns="http://www.w3.org/2000/svg" width="200" height="30">';
var rect      = '<rect width="200" height="30" fill="black"/>';
var html      = svgOpen + rect + svgClose;
var htmlNS    = svgOpenNS + rect + svgClose;
var htmlEnc   = window.encodeURIComponent(html);
var htmlEncNS = window.encodeURIComponent(htmlNS);
imgEnc.src   = prefix + htmlEnc;
imgEncNS.src = prefix + htmlEncNS;
function T(txt){
  document.body.appendChild(document.createTextNode(txt));
}
function HR(){ document.body.appendChild(document.createElement('hr')); }
function BR(){ document.body.appendChild(document.createElement('br')); }
function A(arg){ document.body.appendChild(arg); }
T('without namespace'); BR(); A(imgEnc); HR();
T('with namespace'); BR(); A(imgEncNS);```
</div>
</div>
</p>

<p>you can fix the missing namespace issue by using function <code>outerXHTML</code> from my answer to this question</p>

<p>or like this</p>

```function imgFromSVGnode(node){
    function setNS(elt, parentNS){
        var namespace = elt.namespaceURI;
        if (namespace!==parentNS){
            elt.setAttribute('xmlns', namespace);
        }
        for (var i=0; i<elt.childNodes.length; i++){
            setNS(elt.childNodes[i], namespace);
        }
    }
    setNS(node, null);
    var html = node.outerHTML;
    var dataURL = 'data:image/svg+xml,' + window.encodeURIComponent(html);
    var img = new Image();
    img.src = dataURL;
    return img;
};
```

ContentLicense: CC BY-SA 2.5

Body:
I am trying to load an svg image into canvas for pixel manipulation
I need a method like toDataURL or getImageData for svg

on Chrome/Safari I can try doing it through and image and canvas

var img = new Image()
img.onload = function(){
  ctx.drawImage(img,0,0) //this correctly draws the svg image to the canvas! however...
  var dataURL = canvas.toDataURL(); //SECURITY_ERR: DOM Exception 18
  var data = ctx.getImageData(0,0,img.width, img.height).data //also SECURITY_ERR: DOM Exception 18
  }
  img.src = "image.svg" //that is an svg file. (same domain as html file :))

But I get security errors.
Any other way?

Here is a live demo of the problem http://clstff.appspot.com/gist/462846 (you can view source)

Body:
Illustrating Hubert OG 's answer with code; 2 remarks first.

First (thank you, Robert Longson), it might work without encodeURIComponent, but you better include it (for example, if you have something like fill="url(#pattern)" the encodeURIComponent is necessary, because of the # character)

Second, the SVG namespace is not optional, but it might not be included in svgElt.outerHTML. Especially, if you have created your svg node via createElementNS, like so

svgElt = document.createElementNS("http://www.w3.org/2000/svg", 'svg')

then a subsequent call to svgElt.outerHTML will not contain the namespace attribute, and this would result in not working code, unless you include the namespace attribute later in some fashion

var imgEnc    = new Image();
var imgEncNS  = new Image();
var prefix    = 'data:image/svg+xml,';
var svgOpen   = '<svg width="200" height="30">';
var svgClose  = '</svg>';
var svgOpenNS = '<svg xmlns="http://www.w3.org/2000/svg" width="200" height="30">';
var rect      = '<rect width="200" height="30" fill="black"/>';
var html      = svgOpen + rect + svgClose;
var htmlNS    = svgOpenNS + rect + svgClose;
var htmlEnc   = window.encodeURIComponent(html);
var htmlEncNS = window.encodeURIComponent(htmlNS);
imgEnc.src   = prefix + htmlEnc;
imgEncNS.src = prefix + htmlEncNS;
function T(txt){
  document.body.appendChild(document.createTextNode(txt));
}
function HR(){ document.body.appendChild(document.createElement('hr')); }
function BR(){ document.body.appendChild(document.createElement('br')); }
function A(arg){ document.body.appendChild(arg); }
T('without namespace'); BR(); A(imgEnc); HR();
T('with namespace'); BR(); A(imgEncNS);

you can fix the missing namespace issue by using function outerXHTML from my answer to this question

or like this

function imgFromSVGnode(node){
    function setNS(elt, parentNS){
        var namespace = elt.namespaceURI;
        if (namespace!==parentNS){
            elt.setAttribute('xmlns', namespace);
        }
        for (var i=0; i<elt.childNodes.length; i++){
            setNS(elt.childNodes[i], namespace);
        }
    }
    setNS(node, null);
    var html = node.outerHTML;
    var dataURL = 'data:image/svg+xml,' + window.encodeURIComponent(html);
    var img = new Image();
    img.src = dataURL;
    return img;
};


问:
Product boxes with the same width and height, despite the size of the images
I was trying to create cards for different products, and the idea is that they should be all the same size in all directions, independent from the original size of the images, but now all the images are exceeding the limits that I thought I had placed.

Also, I started studying HTML and CSS about two weeks ago, so, sorry if it's just a simple thing.

image of my problem

#products-btn{
 outline: none;
 border-radius: 18px;
 background: transparent;
 border:2px solid black;
 font-size: 20px;
 width: 60%;
 height: 45px;
 cursor: pointer;
 margin: 10px;
}

#products-btn:hover{
 background-color:black;
 color: white;
}

#products-btn:active{
 opacity: 0.7;
}

#products{
 width: 100%;
 max-width: 1280px;
 text-align: center;

}

#cards{
 display: inline-block;
 border:1px solid black;
 max-width: 250px;
 text-align: center;
 font-family: arial;
 box-shadow: 2px 0 3px 4px #ccc;
}

#cards:not(:last-child){
 margin-right: 20px;
}

/*#cards img{
 border:1px solid black;
}
*/```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="products">

     <div id="cards" class="Product1">
      <img src="images/products/img1.jpg">
      <h1>Travel 1</h1>
      <p class="price">$240.00</p>
      <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed placerat lectus vitae risus.</p>
      <p><button id="products-btn">Travel now!</button></p>
     </div><!-- product one -->

     <div id="cards" class="Product2">
      <img src="images/products/img2.jpg">
      <h1>Travel 2</h1>
      <p class="price">$300.00</p>
      <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed placerat lectus vitae risus.</p>
      <p><button id="products-btn">Travel now!</button></p>
     </div><!-- product two -->

     <div id="cards" class="Product3">
      <img src="images/products/img3.jpg">
      <h1>Travel 3</h1>
      <p class="price">$280.00</p>
      <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed placerat lectus vitae risus.</p>
      <p><button id="products-btn">Travel now!</button></p>
     </div><!-- product three -->

    </div><!-- products container --></code>```

答:
Just add image width in css as</p>

```<code>img{
    width : 250px;
}
</code>```

Body:
I was trying to create cards for different products, and the idea is that they should be all the same size in all directions, independent from the original size of the images, but now all the images are exceeding the limits that I thought I had placed.

Also, I started studying HTML and CSS about two weeks ago, so, sorry if it's just a simple thing.

image of my problem

#products-btn{
 outline: none;
 border-radius: 18px;
 background: transparent;
 border:2px solid black;
 font-size: 20px;
 width: 60%;
 height: 45px;
 cursor: pointer;
 margin: 10px;
}

#products-btn:hover{
 background-color:black;
 color: white;
}

#products-btn:active{
 opacity: 0.7;
}

#products{
 width: 100%;
 max-width: 1280px;
 text-align: center;

}

#cards{
 display: inline-block;
 border:1px solid black;
 max-width: 250px;
 text-align: center;
 font-family: arial;
 box-shadow: 2px 0 3px 4px #ccc;
}

#cards:not(:last-child){
 margin-right: 20px;
}

/*#cards img{
 border:1px solid black;
}
*/

Travel 1

$240.00

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed placerat lectus vitae risus.

<button id="products-btn">Travel now!</button>

Travel 2

$300.00

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed placerat lectus vitae risus.

<button id="products-btn">Travel now!</button>

Travel 3

$280.00

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed placerat lectus vitae risus.

<button id="products-btn">Travel now!</button>

Body:
Just add image width in css as

img{
    width : 250px;
}


问:
how to combine generic `detailsView` and `CreateView` in a single view in django
I'm trying to combine detail and create  in a single view in Django generic views, here is my code :

models.py

class Supplier(models.Model):
    person_name = models.CharField(max_length=850)
    company_name = models.CharField(max_length=1200)
    phone = models.CharField(max_length=15)
    email = models.EmailField(max_length=250, null=True)
    address = models.CharField(max_length=2200)

    def __str__(self):
        return self.company_name

    def get_absolute_url(self):
        return reverse('supplier_details', args=[str(self.id)])

class SupplierItem(models.Model):
    supplier = models.ForeignKey(Supplier, on_delete=CASCADE)
    item = models.ForeignKey(Item, on_delete=CASCADE)
    unit_price = models.DecimalField(max_digits=19, decimal_places=10, default=00.00)

    def __str__(self):
        return self.item.name
```

<p><strong>urls.py</strong></p>

<pre class="lang-py prettyprint-override"><code>    path('<int:pk>/details', views.SupplierItemsView.as_view(), name="supplier_details"),
</code>```

views.py

class SupplierItemsView(View):
    def get(self, request, *args, **kwargs):
        view = SupplierDetailsView.as_view()
        return view(request, *args, **kwargs)

    def post(self, request, *args, **kwargs):
        view = SupplierItemCreate.as_view()
        return view(request, *args, **kwargs)

class SupplierDetailsView(DetailView):
    model = Supplier

class SupplierItemCreate(CreateView):
    model = SupplierItem
    fields = ['item', 'unit_price']

```

<p>Now I want the detail view to be viewed including the create view inside of it, I've tried to render the HTML like this :</p>

<p><strong>templates/appName/supplieritem_forms.html</strong></p>

```<form method="post">

    {{ form }}

</form>
```

<p><strong>templates/appName/supplier_detail.html</strong></p>

```....
{% include 'profiture_supplier/supplieritem_form.html' %}
....
```

The result that it shows the details HTML view rendered perfect, but the form is never shown

答:
I've created a form and used it by mixing both views like this :

class SupplierDetailsView(FormView, DetailView):
    model = Supplier
    form_class = SupplierItemForm

    def get_context_data(self, **kwargs):
        context = super(SupplierDetailsView, self).get_context_data(**kwargs)
        context['form'] = self.get_form()
        return context

    def post(self, request, *args, **kwargs):
        return FormView.post(self, request, *args, **kwargs)

```

Body:
I'm trying to combine detail and create  in a single view in Django generic views, here is my code :

models.py

class Supplier(models.Model):
    person_name = models.CharField(max_length=850)
    company_name = models.CharField(max_length=1200)
    phone = models.CharField(max_length=15)
    email = models.EmailField(max_length=250, null=True)
    address = models.CharField(max_length=2200)

    def __str__(self):
        return self.company_name

    def get_absolute_url(self):
        return reverse('supplier_details', args=[str(self.id)])

class SupplierItem(models.Model):
    supplier = models.ForeignKey(Supplier, on_delete=CASCADE)
    item = models.ForeignKey(Item, on_delete=CASCADE)
    unit_price = models.DecimalField(max_digits=19, decimal_places=10, default=00.00)

    def __str__(self):
        return self.item.name

urls.py

    path('<int:pk>/details', views.SupplierItemsView.as_view(), name="supplier_details"),

views.py

class SupplierItemsView(View):
    def get(self, request, *args, **kwargs):
        view = SupplierDetailsView.as_view()
        return view(request, *args, **kwargs)

    def post(self, request, *args, **kwargs):
        view = SupplierItemCreate.as_view()
        return view(request, *args, **kwargs)

class SupplierDetailsView(DetailView):
    model = Supplier

class SupplierItemCreate(CreateView):
    model = SupplierItem
    fields = ['item', 'unit_price']

Now I want the detail view to be viewed including the create view inside of it, I've tried to render the HTML like this :

templates/appName/supplieritem_forms.html

<form method="post">

    {{ form }}

</form>

templates/appName/supplier_detail.html

....
{% include 'profiture_supplier/supplieritem_form.html' %}
....

The result that it shows the details HTML view rendered perfect, but the form is never shown


问:
search in datagridview C# winfom
I want to put a search option in DataGridView, i.e., User types the string or int in TextBox and similar records the DataGridView should be highlighted. I tried it using KeyPress event but didn't work.

```<code>  if (Char.IsLetter(e.KeyChar))
  {
     for (int i = 0; i < (dgemployee.Rows.Count); i++)
     {
         if (dgemployee.Rows[i].Cells["Employee"].Value.ToString().
                    StartsWith(e.KeyChar.ToString(), true,
                    CultureInfo.InvariantCulture))
         {
             dgemployee.Rows[i].Cells[0].Selected = true;
             return;
         }
      }
</code>```

Actually, I need to search the whole DataGridView, not only one column and row. So any best solution?

答:
Use the DataView.RowFilter property.

Also take a look at DataTable.DefaultView

Take a look at this article I wrote some time back on filtering data real time.

Title: search in datagridview C# winfom

Body:
I want to put a search option in DataGridView, i.e., User types the string or int in TextBox and similar records the DataGridView should be highlighted. I tried it using KeyPress event but didn't work.

  if (Char.IsLetter(e.KeyChar))
  {
     for (int i = 0; i < (dgemployee.Rows.Count); i++)
     {
         if (dgemployee.Rows[i].Cells["Employee"].Value.ToString().
                    StartsWith(e.KeyChar.ToString(), true,
                    CultureInfo.InvariantCulture))
         {
             dgemployee.Rows[i].Cells[0].Selected = true;
             return;
         }
      }

Actually, I need to search the whole DataGridView, not only one column and row. So any best solution?


问:
Checkbox show/hide changes not displaying on angular page
When user clicks on the checkbox, I want to hide some contents.

Below is my code,

```<code><input id="IsBlock" class="e-field e-input" type="checkbox" name="IsBlock" style="width: 100%" #check>
</code>```

And to hide based on checkbox checked

```<code><ng-container *ngIf="!check.checked">
</code>```

Above code works only if I perform some mouse action like clicking on page.

Please help.

答:
Angular only updates bindings if there are some changes in the state of the app so you need to bind some action to the checkbox. By simply adding

```<code>(change)="true"
</code>```

to your checkbox will solve your problem.

Body:
When user clicks on the checkbox, I want to hide some contents.

Below is my code,

<input id="IsBlock" class="e-field e-input" type="checkbox" name="IsBlock" style="width: 100%" #check>

And to hide based on checkbox checked

<ng-container *ngIf="!check.checked">

Above code works only if I perform some mouse action like clicking on page.

Please help.

Body:
Angular only updates bindings if there are some changes in the state of the app so you need to bind some action to the checkbox. By simply adding

(change)="true"

to your checkbox will solve your problem.


问:
Running a combn function on different columns of a dataframe, one row at a time
I have the following data frame :

```<code># A tibble: 3 x 4
  index number_1 number_2 number_3
  <int> <chr>    <chr>    <chr>
1     1 32       16       29
2     2 13       50       47
3     3 37       19       18
</code>```

I would like to run a combn function with an parameter of 2 to every line of that tibble between the 3 columns number; that would yield a result along the lines of :

```<code># A tibble: 3 x 2
  index combn
  <dbl> <chr>
1     1 32,16
2     1 32,29
3     1 16,29
4     2 13,50
.............
</code>```

I have thought of something like

```<code>theTibble %>%
               (
               select(., number_1 : nulber_3) %>% lapply(FUN = combn,2)
               ) %>% View
</code>```

but to no avail.

I would like a pipe friendly solution.
What a possible solution would be?

Thank you for your help

答:
Here is an option with pmap to loop over the 'number' columns in each row, get the combn by selecting 2 elements, paste them together with str_c or paste and unnest the list column

```<code>library(dplyr)
library(purrr)
library(tidyr)
library(stringr)
df1 %>%
    transmute(index, Combn = pmap(select(., starts_with('number')), ~
            combn(c(...), 2, str_c, collapse ="," )))  %>%
    unnest(c(Combn))
# A tibble: 9 x 2
#  index Combn
#  <int> <chr>
#1     1 32,16
#2     1 32,29
#3     1 16,29
#4     2 13,50
#5     2 13,47
#6     2 50,47
#7     3 37,19
#8     3 37,18
#9     3 19,18
</code>```

Or with gather

```<code>df1 %>%
   gather(key, val, -index) %>%
   group_by(index) %>%
   summarise(combn = list(combn(val, 2, toString))) %>%
   unnest(combn)
</code>```

Or using base R with apply

```<code>lst1 <- apply(df1[-1], 1, combn, 2, paste, collapse=",", simplify = FALSE)
data.frame(index = rep(df1$index, lengths(lst1)), Combn = unlist(lst1))
</code>```

data

```<code>df1 <- tibble(index = 1:3, number_1 = as.character(c(32, 13, 37)),
   number_2 = as.character(c(16, 50, 19)), number_3 = as.character(c(29, 47, 18)))
</code>```

Body:
I have the following data frame :

# A tibble: 3 x 4
  index number_1 number_2 number_3
  <int> <chr>    <chr>    <chr>
1     1 32       16       29
2     2 13       50       47
3     3 37       19       18

I would like to run a combn function with an parameter of 2 to every line of that tibble between the 3 columns number; that would yield a result along the lines of :

# A tibble: 3 x 2
  index combn
  <dbl> <chr>
1     1 32,16
2     1 32,29
3     1 16,29
4     2 13,50
.............

I have thought of something like

theTibble %>%
               (
               select(., number_1 : nulber_3) %>% lapply(FUN = combn,2)
               ) %>% View

but to no avail.

I would like a pipe friendly solution.
What a possible solution would be?

Thank you for your help

Body:
Here is an option with pmap to loop over the 'number' columns in each row, get the combn by selecting 2 elements, paste them together with str_c or paste and unnest the list column

library(dplyr)
library(purrr)
library(tidyr)
library(stringr)
df1 %>%
    transmute(index, Combn = pmap(select(., starts_with('number')), ~
            combn(c(...), 2, str_c, collapse ="," )))  %>%
    unnest(c(Combn))
# A tibble: 9 x 2
#  index Combn
#  <int> <chr>
#1     1 32,16
#2     1 32,29
#3     1 16,29
#4     2 13,50
#5     2 13,47
#6     2 50,47
#7     3 37,19
#8     3 37,18
#9     3 19,18

Or with gather

df1 %>%
   gather(key, val, -index) %>%
   group_by(index) %>%
   summarise(combn = list(combn(val, 2, toString))) %>%
   unnest(combn)

Or using base R with apply

lst1 <- apply(df1[-1], 1, combn, 2, paste, collapse=",", simplify = FALSE)
data.frame(index = rep(df1$index, lengths(lst1)), Combn = unlist(lst1))

data

df1 <- tibble(index = 1:3, number_1 = as.character(c(32, 13, 37)),
   number_2 = as.character(c(16, 50, 19)), number_3 = as.character(c(29, 47, 18)))


问:
Cannot update props passed via react navigation
I have a container where the API calls happen. I need to pass the response I get to another component which is not the child of the above container. I can't pass in props like how you usually do since it is not a child component of the above container. What I do is, I pass the response to the above container's child component and from there I use :

this.props.navigation.navigate('Whatever',{
  reason: this.state.reason
});```

To pass in the reason as prop to the "Whatever" component. Now, the problem is this "reason" prop does not get updated when it changes in the container from where it is being passed.

Now, I am aware that since we are not passing props like how they are usually passed that's why we won't be able to get the updated props in whatever component. I am aware that I might have to change the structure of my app as well, but I cannot afford that right now.

Is there any way via which I can update the reason prop in the whatever component?

Thanks in advance.

答:
You can use params in react navigation

--updating params https://reactnavigation.org/docs/params/#updating-params

--passing params https://reactnavigation.org/docs/params/#passing-params-to-a-previous-screen

--passing params to nested component https://reactnavigation.org/docs/params/#passing-params-to-nested-navigators

Body:
I have a container where the API calls happen. I need to pass the response I get to another component which is not the child of the above container. I can't pass in props like how you usually do since it is not a child component of the above container. What I do is, I pass the response to the above container's child component and from there I use :

this.props.navigation.navigate('Whatever',{
  reason: this.state.reason
});

To pass in the reason as prop to the "Whatever" component. Now, the problem is this "reason" prop does not get updated when it changes in the container from where it is being passed.

Now, I am aware that since we are not passing props like how they are usually passed that's why we won't be able to get the updated props in whatever component. I am aware that I might have to change the structure of my app as well, but I cannot afford that right now.

Is there any way via which I can update the reason prop in the whatever component?

Thanks in advance.


问:
dragablz TabablzControl disable tab
Hello I am working with dragablz:TabablzControl and I need disable a tab but I can't.

This is my code:

```<code><dragablz:TabablzControl
        FixedHeaderCount="4"
        Grid.Row="1"
        Grid.Column="0"
        Grid.ColumnSpan="2"
        BorderThickness="0"
        SelectedIndex="{Binding SelectedTab}">
        <TabItem Header="{Resx ApplicationView_mnuStatus}" IsEnabled="false"  Visibility="Hidden" >
            <views:StatusView>
                <views:StatusView.DataContext>
                    <viewmodels:StatusViewModel />
                </views:StatusView.DataContext>
            </views:StatusView>
        </TabItem>
        <TabItem Header="{Resx ApplicationView_mnuServers}" IsEnabled="false"  Visibility="Hidden" >
            <views:ServersMainView>
                <views:ServersMainView.DataContext>
                    <viewmodels:ServersMainViewModel />
                </views:ServersMainView.DataContext>
            </views:ServersMainView>
        </TabItem>
    </dragablz:TabablzControl>
</code>```

Visibility = "hidden" doesn't work
isEnabled = "false" does't work

Please help! Thanks!

答:
you can simply remove tab item in code behind :</p>

```<code>TabablzControl1.Items.Remove(tabitem1);
</code>```

Title: dragablz TabablzControl disable tab

Body:
Hello I am working with dragablz:TabablzControl and I need disable a tab but I can't.

This is my code:

<dragablz:TabablzControl
        FixedHeaderCount="4"
        Grid.Row="1"
        Grid.Column="0"
        Grid.ColumnSpan="2"
        BorderThickness="0"
        SelectedIndex="{Binding SelectedTab}">
        <TabItem Header="{Resx ApplicationView_mnuStatus}" IsEnabled="false"  Visibility="Hidden" >
            <views:StatusView>
                <views:StatusView.DataContext>
                    <viewmodels:StatusViewModel />
                </views:StatusView.DataContext>
            </views:StatusView>
        </TabItem>
        <TabItem Header="{Resx ApplicationView_mnuServers}" IsEnabled="false"  Visibility="Hidden" >
            <views:ServersMainView>
                <views:ServersMainView.DataContext>
                    <viewmodels:ServersMainViewModel />
                </views:ServersMainView.DataContext>
            </views:ServersMainView>
        </TabItem>
    </dragablz:TabablzControl>

Visibility = "hidden" doesn't work
isEnabled = "false" does't work

Please help! Thanks!

Body:
you can simply remove tab item in code behind :

TabablzControl1.Items.Remove(tabitem1);


问:
How to set grid (vector or arrows) lines in gnuplot
The location of the grid lines (parallel to Y-axis) at X-axis are defined at third row of a files, for example.

The third lines has the points

```<code>#   0.00000000 0.08329780 0.11683890 0.20013670 0.23367770
</code>```

I can get the Ymax from another file defined as FILE with

```<code>set table $Dummy
plot FILE u ($0==1?(Ymax=$2): NaN) w table # i have updated this line. This will be used only for height of the grid line. Here FILE is a data file with two columns only which will be plotted in X-Y format.

unset table
</code>```

How I can set grid lines at above locations that should end to Ymax ?

I need something like:

```<code>for i in 0.00000000 0.08329780 0.11683890 0.20013670 0.23367770
do
set arrow $i, Ymax lc rgb "black" dt 2 nohead
done
</code>```

答:
As @Ethan already pointed out, gridlines are bound to major or minor tics and span the whole graph.
But you can plot something with vectors.

By the way, note that with your code

```<code>set table $Dummy
    plot FILE u ($0==1?(Ymin=$1,Ymax=$2):NaN,Xmax=$8) w table
unset table
</code>```

Ymin and Ymax will be the values of of the first and second column of the second line(row) of the last dataset. If your data has no empty lines then the last dataset is also the first. Xmax will be the overall last value of the 8th column.

For you task, one solution could be the following below. No need for sed or awk, etc.
Since I don't have example data from you I assume something.

get the x positions for your "grid lines" from one datafile

extract Ymin,Ymax,Xmax from another datafile

plot your data with linespoints and the "grid lines" with vectors

Note that in earlier gnuplot versions there was a limitation of strcol() to (I guess) 63 characters. With gnuplot 5.2.7 this has been fixed.

Code:

```<code>### use vector plot to plot "grid lines"
reset session

$Data1 <<EOD
# first line
# second line
# 0.00000000 0.08329780 0.11683890 0.20013670 0.23367770
# below this line data starts
1  4
2  5
3  6
EOD

$Data2 <<EOD
1.1  2.7  0  0  1.2  0  0  0.00
1.2  2.6  0  0  1.8  0  0  0.05
1.3  2.5  0  0  2.5  0  0  0.10
1.4  2.4  0  0  2.1  0  0  0.15
1.5  2.3  0  0  1.6  0  0  0.17
1.6  2.2  0  0  1.7  0  0  0.20
1.7  2.1  0  0  2.4  0  0  0.25
EOD

set table $Dummy
    set datafile commentschars ''       # all lines will be data line
    set datafile separator '\n'         # in order to get full lines
    plot $Data1 u (xValues = strcol(1)) index 0 every ::2::2 w table   # get the complete 3rd line
    set datafile commentschars '#'      # reset the comment character
    set datafile separator whitespace   # reset the column separator
    plot t=0 $Data2 u (t==0?(Ymin=$1,Ymax=$2,t=1):NaN,Xmax=$8) w table  # get Ymin,Ymax,Xmax
unset table
print Ymin, Ymax, Xmax, xValues

xValue(n) = real(word(xValues,n+1))   # function to extract xValue

set xrange[-0.05:0.3]
set samples words(xValues)-1    # set number of datapoints of special datafile '+'

plot '+' u (xValue(int($0+1))):(Ymin):(0):(Ymax-Ymin) w vectors lc rgb "black" dt 2 nohead not, \
     $Data2 u 8:5 w lp pt 7 lc rgb "red" title "Data"
### end of code
</code>```

Result:

Addition:

Above I've shown you how to extract the necessary values with gnuplot.
Yes, that's not so easy to understand and not the shortest way, but it's gnuplot only! If you prefer to use sed, awk or the like feel free, but there I cannot help.

Another approach instead of plotting vectors is drawing arrows. The assumption is that you have your data in your variables already.

Code:

```<code>### draw arrows from a data string
reset session

xValues = "0.00000000 0.08329780 0.11683890 0.20013670 0.23367770"

Ymin = 0.2
Ymax = 0.9
Xmax = 0.25

i=0
do for [xValue in xValues] {
    i=i+1
    set arrow i from xValue,Ymin to xValue,Ymax nohead dt 2
}

set xrange[-0.05:0.4]
set yrange[0:1]

plot x
### end of code
</code>```

Result:

Body:
The location of the grid lines (parallel to Y-axis) at X-axis are defined at third row of a files, for example.

The third lines has the points

#   0.00000000 0.08329780 0.11683890 0.20013670 0.23367770

I can get the Ymax from another file defined as FILE with

set table $Dummy
plot FILE u ($0==1?(Ymax=$2): NaN) w table # i have updated this line. This will be used only for height of the grid line. Here FILE is a data file with two columns only which will be plotted in X-Y format.

unset table

How I can set grid lines at above locations that should end to Ymax ?

I need something like:

for i in 0.00000000 0.08329780 0.11683890 0.20013670 0.23367770
do
set arrow $i, Ymax lc rgb "black" dt 2 nohead
done

Body:
As @Ethan already pointed out, gridlines are bound to major or minor tics and span the whole graph.
But you can plot something with vectors.

By the way, note that with your code

set table $Dummy
    plot FILE u ($0==1?(Ymin=$1,Ymax=$2):NaN,Xmax=$8) w table
unset table

Ymin and Ymax will be the values of of the first and second column of the second line(row) of the last dataset. If your data has no empty lines then the last dataset is also the first. Xmax will be the overall last value of the 8th column.

For you task, one solution could be the following below. No need for sed or awk, etc.
Since I don't have example data from you I assume something.

get the x positions for your "grid lines" from one datafile

extract Ymin,Ymax,Xmax from another datafile

plot your data with linespoints and the "grid lines" with vectors

Note that in earlier gnuplot versions there was a limitation of strcol() to (I guess) 63 characters. With gnuplot 5.2.7 this has been fixed.

Code:

### use vector plot to plot "grid lines"
reset session

$Data1 <<EOD
# first line
# second line
# 0.00000000 0.08329780 0.11683890 0.20013670 0.23367770
# below this line data starts
1  4
2  5
3  6
EOD

$Data2 <<EOD
1.1  2.7  0  0  1.2  0  0  0.00
1.2  2.6  0  0  1.8  0  0  0.05
1.3  2.5  0  0  2.5  0  0  0.10
1.4  2.4  0  0  2.1  0  0  0.15
1.5  2.3  0  0  1.6  0  0  0.17
1.6  2.2  0  0  1.7  0  0  0.20
1.7  2.1  0  0  2.4  0  0  0.25
EOD

set table $Dummy
    set datafile commentschars ''       # all lines will be data line
    set datafile separator '\n'         # in order to get full lines
    plot $Data1 u (xValues = strcol(1)) index 0 every ::2::2 w table   # get the complete 3rd line
    set datafile commentschars '#'      # reset the comment character
    set datafile separator whitespace   # reset the column separator
    plot t=0 $Data2 u (t==0?(Ymin=$1,Ymax=$2,t=1):NaN,Xmax=$8) w table  # get Ymin,Ymax,Xmax
unset table
print Ymin, Ymax, Xmax, xValues

xValue(n) = real(word(xValues,n+1))   # function to extract xValue

set xrange[-0.05:0.3]
set samples words(xValues)-1    # set number of datapoints of special datafile '+'

plot '+' u (xValue(int($0+1))):(Ymin):(0):(Ymax-Ymin) w vectors lc rgb "black" dt 2 nohead not, \
     $Data2 u 8:5 w lp pt 7 lc rgb "red" title "Data"
### end of code

Result:

Addition:

Above I've shown you how to extract the necessary values with gnuplot.
Yes, that's not so easy to understand and not the shortest way, but it's gnuplot only! If you prefer to use sed, awk or the like feel free, but there I cannot help.

Another approach instead of plotting vectors is drawing arrows. The assumption is that you have your data in your variables already.

Code:

### draw arrows from a data string
reset session

xValues = "0.00000000 0.08329780 0.11683890 0.20013670 0.23367770"

Ymin = 0.2
Ymax = 0.9
Xmax = 0.25

i=0
do for [xValue in xValues] {
    i=i+1
    set arrow i from xValue,Ymin to xValue,Ymax nohead dt 2
}

set xrange[-0.05:0.4]
set yrange[0:1]

plot x
### end of code

Result:


问:
Protecting Github branches from Admins
I am asking this here because the Github docs do not have the answer, and I cannot find another answer anywhere else.

I want to stop people from pushing to my master or development branches on github.

Github appears to have this option but it doesn't work.

Here are the steps I followed:

Go to the github repo settings page

Select 'Branch Protection Rules'

Enter the branch name I wish to protect

Click 'include administrators' - everyone on the repo is an admin

Click 'restrict who can push to matching branches'

Leave the 'restrict who...' empty, indicating that nobody can be
exempt from the rule

Click Save.

Go to the protected branch on my local repo, make a change, commit and
push to the remote protected branch

The result: the change has been pushed to my protected branch.

Expected result: the change should be rejected from pushing to my protected branch

Am I doing something wrong, or is this a bug?

Thanks in advance for any help.

答:
I'm seeing the same behavior.  Maybe this is a new bug?

We ended up create a pre-commit hook and essentially enforcing it ourselves.

The only way I could force my admin account to make a PR using this interface was to require at least one review from another user.  Unfortunately that's too risky for us.

Title: Protecting Github branches from Admins


问:
Error when passing a laravel route as a props in VueJS
I want to use the blade syntax route() in a vue js component so i thought i should use something like this :

```<code><nav-bar
:user="{{ json_encode(Auth::user()) }}"
:authPath= "{{ route('auth') }}">

</nav-bar>
</code>```

but an error apear in the console :
app.js:86258 [Vue warn]: Error compiling template:

invalid expression: Unexpected token ':' in

What did i do wrong?

答:
as @Digvijay said you dont need that : for authPath because its not a vue variable before its passed to vue it will converted to string (also @MuktiRaniGosh way is works too).

but you have another problem and thats is the " for user prop because of json syntax. use ' instead so the code will be

```<code><nav-bar
:user='@json(Auth::user())'
authPath="{{ route('auth') }}">

</nav-bar>
</code>```

Body:
I want to use the blade syntax route() in a vue js component so i thought i should use something like this :

but an error apear in the console :
app.js:86258 [Vue warn]: Error compiling template:

invalid expression: Unexpected token ':' in

What did i do wrong?

Body:
as @Digvijay said you dont need that : for authPath because its not a vue variable before its passed to vue it will converted to string (also @MuktiRaniGosh way is works too).

but you have another problem and thats is the " for user prop because of json syntax. use ' instead so the code will be

<nav-bar
:user='@json(Auth::user())'
authPath="{{ route('auth') }}">

</nav-bar>


问:
How can I replace a hash key with another key?
I have a condition that gets a hash.

```<code>  hash = {"_id"=>"4de7140772f8be03da000018", .....}
</code>```

Yet, I want to rename the key of that hash as follows.

```<code>  hash = {"id"=>"4de7140772f8be03da000018", ......}
</code>```

P.S. I don't know what keys are in the hash; they are random. Some keys are prefixed with an underscore that I would like to remove.

Body:
I have a condition that gets a hash.

  hash = {"_id"=>"4de7140772f8be03da000018", .....}

Yet, I want to rename the key of that hash as follows.

  hash = {"id"=>"4de7140772f8be03da000018", ......}

P.S. I don't know what keys are in the hash; they are random. Some keys are prefixed with an underscore that I would like to remove.

Body: h.inject({}) { |m, (k,v)| m[k.sub(/^_/,'')] = v; m }


问:
Need to compare two arrays with a callback and return an object in Javascript
Construct a function objOfMatches that accepts two arrays and a callback. objOfMatches will build an object and return it. To build the object, objOfMatches will test each element of the first array using the callback to see if the output matches the corresponding element (by index) of the second array. If there is a match, the element from the first array becomes a key in an object, and the element from the second array becomes the corresponding value. I got this so far:

```<code>const objOfMatches = (arr1,arr2,call) => {
let result = {};
for(let i = 0; i < arr1.length; i++){
 //Don't know how to check each element using the callback
}
return result
}

const arr1 = ['hi', 'howdy', 'bye', 'later', 'hello'];
const arr2 = ['HI', 'Howdy', 'BYE', 'later', 'HELLO'];
function uppercaser(str) { return str.toUpperCase(); }
console.log(objOfMatches(arr1, arr2, uppercaser));
// should log: { hi: 'HI', bye: 'BYE', hello: 'HELLO' }
</code>```

答:
const objOfMatches = (arr1,arr2,call) => {
  let result = {};
  arr1.forEach((item, i) => {
     if(call(item) === arr2[i]) {
      result[item] = arr2[i]
     }
  })
  return result;
}

const arr1 = ['hi', 'howdy', 'bye', 'later', 'hello'];
const arr2 = ['HI', 'Howdy', 'BYE', 'later', 'HELLO'];
function uppercaser(str) { return str.toUpperCase(); }
console.log(objOfMatches(arr1, arr2, uppercaser));
// should log: { hi: 'HI', bye: 'BYE', hello: 'HELLO' }```

Body:
Construct a function objOfMatches that accepts two arrays and a callback. objOfMatches will build an object and return it. To build the object, objOfMatches will test each element of the first array using the callback to see if the output matches the corresponding element (by index) of the second array. If there is a match, the element from the first array becomes a key in an object, and the element from the second array becomes the corresponding value. I got this so far:

const objOfMatches = (arr1,arr2,call) => {
let result = {};
for(let i = 0; i < arr1.length; i++){
 //Don't know how to check each element using the callback
}
return result
}

const arr1 = ['hi', 'howdy', 'bye', 'later', 'hello'];
const arr2 = ['HI', 'Howdy', 'BYE', 'later', 'HELLO'];
function uppercaser(str) { return str.toUpperCase(); }
console.log(objOfMatches(arr1, arr2, uppercaser));
// should log: { hi: 'HI', bye: 'BYE', hello: 'HELLO' }


问:
How do I combine an IF formula with a dropdown in Excel?
Here's what I am trying to achieve. If a student earns a grade 1* or a 1, they do not get a key. If they earn a grade 2 or 3, the teacher then chooses from these keys:
A - Attendance
B - Behaviour
C - Classwork
L - Lateness
O - Organization
H - Homework.

What I want to do is, create a  drop-down with the options 1*,1,2,3. If the teacher selects 2 or 3, it will then provide another drop down with the keys(A,B,C,H,L,O). I know this can somehow be done using dependent drop downs but somehow this doesn't work for me.

What I have done so far:
I have a column labelled "Grades" with a dropdown menu listing 1*,1,2,3.
I then created another column with the label "key" and used the data validation method and the formula "=INDIRECT".

What happens then is that the "key" column doesnt give me a dropdown menu. It's just a blank cell.

What am I doing wrong?

答:
Here is a workaround,

use a table, I use the name "tbl_gradechoose" for it.
For every grade a column.
Use the Datavalidation, choose List and as source the formula

```<code>=INDIRECT("tbl_gradechoose[" & A1 &"]")
</code>```

Here shown in englisch Excel Version:

Here shown in the German Version in Excle:

Body:
Here is a workaround,

use a table, I use the name "tbl_gradechoose" for it.
For every grade a column.
Use the Datavalidation, choose List and as source the formula

=INDIRECT("tbl_gradechoose[" & A1 &"]")

Here shown in englisch Excel Version:

Here shown in the German Version in Excle:


问:
fgets() gets more than it should in file reading - C
Currently I'm doing a practical work to collage in witch I have to read data from a file.

The file data structure is: "id name sex"

example:

```
nm0025630   Vikas Anand M
nm0418131   Victor Janson   M
nm0411451   Dick Israel M
nm0757820   Leopoldo Salcedo    M
```

To read the currently I'm using this code:

```<code>    fh = NULL;
    fh = fopen(ACTORS, "r");
    if (!fh) {
        exit(1);
    }
    while (!feof(fh)) {
        char sex, name[100], id[10];

        fgets(id, 10, fh);
        fgets(name, 100, fh);
        fgetc(sex);

        if (!feof(fh)) {
            hash_update_node(hash, get_id_num(id), name, sex);
            count++;
        }
    }
</code>```

The problem is that it reads the name and the sex together.
Any help is appreciated.

答:
It seems the fields are separated by TAB characters in the file. If this is correct, you can parse the file with fscanf():

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

int local_file(void) {
    char sex, name[100], id[10];
    int count = 0;

    FILE *fh = fopen(ACTORS, "r");
    if (!fh) {
        exit(1);
    }
    while (fscanf("%9[^\t]%*1[\t]%99[^\t]%*1[\t]%c", id, name, &sex) == 3) {
        hash_update_node(hash, get_id_num(id), name, sex);
        count++;
    }
    return count;
}
```

Note however that this code will fail if any of the fields are empty.

Body:
Currently I'm doing a practical work to collage in witch I have to read data from a file.

The file data structure is: "id name sex"

example:

nm0025630   Vikas Anand M
nm0418131   Victor Janson   M
nm0411451   Dick Israel M
nm0757820   Leopoldo Salcedo    M

To read the currently I'm using this code:

    fh = NULL;
    fh = fopen(ACTORS, "r");
    if (!fh) {
        exit(1);
    }
    while (!feof(fh)) {
        char sex, name[100], id[10];

        fgets(id, 10, fh);
        fgets(name, 100, fh);
        fgetc(sex);

        if (!feof(fh)) {
            hash_update_node(hash, get_id_num(id), name, sex);
            count++;
        }
    }

The problem is that it reads the name and the sex together.
Any help is appreciated.

Body:
It seems the fields are separated by TAB characters in the file. If this is correct, you can parse the file with fscanf():

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

int local_file(void) {
    char sex, name[100], id[10];
    int count = 0;

    FILE *fh = fopen(ACTORS, "r");
    if (!fh) {
        exit(1);
    }
    while (fscanf("%9[^\t]%*1[\t]%99[^\t]%*1[\t]%c", id, name, &sex) == 3) {
        hash_update_node(hash, get_id_num(id), name, sex);
        count++;
    }
    return count;
}

Note however that this code will fail if any of the fields are empty.


问:
Filtering and Searching Data with JavaScript
Where would I start to learn how to filter data like you would see in a product listing page on a shopping site like Nordstrom, Bestbuy, Whirlpool? I want to know how someone would do it with javascript and category and product json data.

https://bestbuyapis.github.io/api-documentation/?shell#categorizations

https://marketplace.intel.com/s/search?search=%7B%22cat%22%3Anull%2C%22q%22%3A%22%22%2C%22type%22%3A%22all%22%7D&language=en_US - This one is kind of confusing to me how they use checkboxes with children. Is this an example of recursion?

Best answer would provide helpful links and an example with explanation. But honestly anything helps!

TIA - just trying to become a better developer!

答:
I'm going to assume your JSON represents an array of products, each of which is assigned to zero or more categories, like so:

```<code>[
  {
    "name": "Apple",
    "category": "fruit",
    "color": "red"
  },
  {
    "name": "Carrot",
    "category": "vegetable",
    "color": "orange"
  },
  {
    "name": "Traffic cone",
    "color": "orange",
  }
]

</code>```

so:

```<code>const products = JSON.parse(...); // generates an array

</code>```

Javascript's Array methods are your primary tools, in this case. For example, Array.filter can be used to filter by color:

```<code>function filterByColor(color) {
  return products.filter( (product) => {
    return product.color === color;
  });
}
</code>```

If you want to use checkboxes to select more than one color, you could extend it, as follows:

```<code>function filterByColors(desiredColors) {
  return products.filter( (product) => {
    const { color } = product;
    return desiredColors.includes(color);
  });
}

</code>```

Does this point you in the right direction?

Body:
I'm going to assume your JSON represents an array of products, each of which is assigned to zero or more categories, like so:

[
  {
    "name": "Apple",
    "category": "fruit",
    "color": "red"
  },
  {
    "name": "Carrot",
    "category": "vegetable",
    "color": "orange"
  },
  {
    "name": "Traffic cone",
    "color": "orange",
  }
]

so:

const products = JSON.parse(...); // generates an array

Javascript's Array methods are your primary tools, in this case. For example, Array.filter can be used to filter by color:

function filterByColor(color) {
  return products.filter( (product) => {
    return product.color === color;
  });
}

If you want to use checkboxes to select more than one color, you could extend it, as follows:

function filterByColors(desiredColors) {
  return products.filter( (product) => {
    const { color } = product;
    return desiredColors.includes(color);
  });
}

Does this point you in the right direction?


答:
Here is a functional programming solution:

const objOfMatches = (arr1, arr2, call) =>
    Object.fromEntries(arr1.map((v,i) => [v, arr2[i]])
                           .filter(([a,b]) => call(a) === b));

const arr1 = ['hi', 'howdy', 'bye', 'later', 'hello'];
const arr2 = ['HI', 'Howdy', 'BYE', 'later', 'HELLO'];
const uppercaser = str => str.toUpperCase();
console.log(objOfMatches(arr1, arr2, uppercaser)); ```
</div>
</div>
</p>
<h2>Explanation</h2>
<p><code>objOfMatches</code> is a function defined with arrow syntax, where the part that follows the (first) <code>=></code> is the expression that determines the function's return value. The same arrow syntax is used for all other functions in this solution as well.</p>
<p>First the two arrays are "zipped" into one array of pairs, using <code>arr1.map((v,i) => [v, arr2[i]])</code>. This takes every value <code>v</code> from <code>arr1</code> and pairs it with the value from <code>arr2</code> that sits at the same index. So for the example input, this produces the following:</p>
```[
  ['hi', 'HI'],
  ['howdy', 'Howdy'],
  ['bye', 'BYE'],
  ['later', 'later'],
  ['hello', 'HELLO']
]
```
<p>Then <code>.filter</code> is called on this intermediate result, only keeping the pairs <code>[a,b]</code> where <code>call(a) === b</code>. So then we have:</p>
```[
  ['hi', 'HI'],
  ['bye', 'BYE'],
  ['hello', 'HELLO']
]
```

Finally, this is passed as argument to the Object.fromEntries function, which turns an array of key/value pairs into a plain object having those keys and values.

Title: Need to compare two arrays with a callback and return an object in Javascript

Body:
Here is a functional programming solution:

const objOfMatches = (arr1, arr2, call) =>
    Object.fromEntries(arr1.map((v,i) => [v, arr2[i]])
                           .filter(([a,b]) => call(a) === b));

const arr1 = ['hi', 'howdy', 'bye', 'later', 'hello'];
const arr2 = ['HI', 'Howdy', 'BYE', 'later', 'HELLO'];
const uppercaser = str => str.toUpperCase();
console.log(objOfMatches(arr1, arr2, uppercaser));

Explanation

objOfMatches is a function defined with arrow syntax, where the part that follows the (first) => is the expression that determines the function's return value. The same arrow syntax is used for all other functions in this solution as well.

First the two arrays are "zipped" into one array of pairs, using arr1.map((v,i) => [v, arr2[i]]). This takes every value v from arr1 and pairs it with the value from arr2 that sits at the same index. So for the example input, this produces the following:

[
  ['hi', 'HI'],
  ['howdy', 'Howdy'],
  ['bye', 'BYE'],
  ['later', 'later'],
  ['hello', 'HELLO']
]

Then .filter is called on this intermediate result, only keeping the pairs [a,b] where call(a) === b. So then we have:

[
  ['hi', 'HI'],
  ['bye', 'BYE'],
  ['hello', 'HELLO']
]

Finally, this is passed as argument to the Object.fromEntries function, which turns an array of key/value pairs into a plain object having those keys and values.


问:
Fixed size queue which automatically dequeues old values upon new enqueues
I'm using ConcurrentQueue for a shared data structure which purpose is holding the last N objects passed to it (kind of history).

Assume we have a browser and we want to have the last 100 browsed Urls. I want a queue which automatically drop (dequeue) the oldest (first) entry upon new entry insertion (enqueue) when the capacity gets full (100 addresses in history).

How can I accomplish that using System.Collections ?

答:
Just because no one's said it yet.. you can use a LinkedList<T> and add the thread safety:

```<code>public class Buffer<T> : LinkedList<T>
{
    private int capacity;

    public Buffer(int capacity)
    {
        this.capacity = capacity;
    }

    public void Enqueue(T item)
    {
        // todo: add synchronization mechanism
        if (Count == capacity) RemoveLast();
        AddFirst(item);
    }

    public T Dequeue()
    {
        // todo: add synchronization mechanism
        var last = Last.Value;
        RemoveLast();
        return last;
    }
}
</code>```

One thing to note is the default enumeration order will be LIFO in this example. But that can be overridden if necessary.

Body:
Just because no one's said it yet.. you can use a LinkedList<T> and add the thread safety:

public class Buffer<T> : LinkedList<T>
{
    private int capacity;

    public Buffer(int capacity)
    {
        this.capacity = capacity;
    }

    public void Enqueue(T item)
    {
        // todo: add synchronization mechanism
        if (Count == capacity) RemoveLast();
        AddFirst(item);
    }

    public T Dequeue()
    {
        // todo: add synchronization mechanism
        var last = Last.Value;
        RemoveLast();
        return last;
    }
}

One thing to note is the default enumeration order will be LIFO in this example. But that can be overridden if necessary.


问:
Generate ID from string in Python
I'm struggling a bit to generate ID of type integer for given string in Python.

I thought the built-it hash function is perfect but it appears that the IDs are too long sometimes. It's a problem since I'm limited to 64bits as maximum length.

My code so far: hash(s) % 10000000000.
The input string(s) which I can expect will be in range of 12-512 chars long.

Requirements are:

integers only

generated from provided string

ideally up to 10-12 chars long (I'll have ~5 million items only)

low probability of collision..?

I would be glad if someone can provide any tips / solutions.

答:
If you're not allowed to add extra dependency, you can continue using hash function in the following way:

```<code>>>> my_string = "whatever"
>>> str(hash(my_string))[1:13]
'460440266319'
</code>```

NB:

I am ignoring 1st character as it may be the negative sign.

hash may return different values for same string, as PYTHONHASHSEED Value will change everytime you run your program. You may want to set it to some fixed value. Read here

Title: Generate ID from string in Python

Body:
If you're not allowed to add extra dependency, you can continue using hash function in the following way:

>>> my_string = "whatever"
>>> str(hash(my_string))[1:13]
'460440266319'

NB:

I am ignoring 1st character as it may be the negative sign.

hash may return different values for same string, as PYTHONHASHSEED Value will change everytime you run your program. You may want to set it to some fixed value. Read here


问:
Maintain Firebase Authentication state after exiting app on iOS
I am using the following class to handle the authentication state and login for users:

```<code>class AuthenticationState: NSObject, ObservableObject {

     // MARK: Properties
    let db = Firestore.firestore()

    @Published var loggedInUser: FirebaseAuth.User?
    @Published var isAuthenticating = false
    @Published var error: NSError?

    static let shared = AuthenticationState()

    private let authState = Auth.auth()
    fileprivate var currentNonce: String?

    // MARK: Methods
    func login(with loginOption: LoginOption) {
        self.isAuthenticating = true
        self.error = nil

        switch loginOption {
            case .signInWithApple:
                handleSignInWithApple()

            case let .emailAndPassword(email, password):
                handleSignInWith(email: email, password: password)
        }
    }

    private func handleSignInWith(email: String, password: String) {
        authState.signIn(withEmail: email, password: password, completion: handleAuthResultCompletion)
    }

    func signup(email: String, password: String, passwordConfirmation: String) {
        guard password == passwordConfirmation else {
            self.error = NSError(domain: "", code: 9210, userInfo: [NSLocalizedDescriptionKey: "Password and confirmation does not match"])
            return
        }

        self.isAuthenticating = true
        self.error = nil

        authState.createUser(withEmail: email, password: password, completion: handleAuthResultCompletion)
    }

    private func handleAuthResultCompletion(auth: AuthDataResult?, error: Error?) {
        DispatchQueue.main.async {
        self.isAuthenticating = false
            if let user = auth?.user {
                self.loggedInUser = user
            } else if let error = error {
                self.error = error as NSError
            }
        }
    }

    func signout() {
        try? authState.signOut()
        self.loggedInUser = nil
    }
}

// Extension Below that handles sign in with apple, etc.
</code>```

This works great for handling a variety of sign in methods, however when the user exits the app, the logged in state no longer persists. What would be the best way to keep the user logged in after exiting the application?

答:
There are multiple ways you can do what you wanna do. Save your data, any kind of data - it's up to you in your local storage, such as:

Defaults

Keychain

Core Data

and whatnot....

Alternatively, in my opinion, you could just try to check the currentUser, like so:

```<code>let user = Auth.auth().currentUser
</code>```

doc: https://firebase.google.com/docs/auth/ios/manage-users

and for javascript: (Authentication State Persistence
) https://firebase.google.com/docs/auth/web/auth-state-persistence

Body:
I am using the following class to handle the authentication state and login for users:

class AuthenticationState: NSObject, ObservableObject {

     // MARK: Properties
    let db = Firestore.firestore()

    @Published var loggedInUser: FirebaseAuth.User?
    @Published var isAuthenticating = false
    @Published var error: NSError?

    static let shared = AuthenticationState()

    private let authState = Auth.auth()
    fileprivate var currentNonce: String?

    // MARK: Methods
    func login(with loginOption: LoginOption) {
        self.isAuthenticating = true
        self.error = nil

        switch loginOption {
            case .signInWithApple:
                handleSignInWithApple()

            case let .emailAndPassword(email, password):
                handleSignInWith(email: email, password: password)
        }
    }

    private func handleSignInWith(email: String, password: String) {
        authState.signIn(withEmail: email, password: password, completion: handleAuthResultCompletion)
    }

    func signup(email: String, password: String, passwordConfirmation: String) {
        guard password == passwordConfirmation else {
            self.error = NSError(domain: "", code: 9210, userInfo: [NSLocalizedDescriptionKey: "Password and confirmation does not match"])
            return
        }

        self.isAuthenticating = true
        self.error = nil

        authState.createUser(withEmail: email, password: password, completion: handleAuthResultCompletion)
    }

    private func handleAuthResultCompletion(auth: AuthDataResult?, error: Error?) {
        DispatchQueue.main.async {
        self.isAuthenticating = false
            if let user = auth?.user {
                self.loggedInUser = user
            } else if let error = error {
                self.error = error as NSError
            }
        }
    }

    func signout() {
        try? authState.signOut()
        self.loggedInUser = nil
    }
}

// Extension Below that handles sign in with apple, etc.

This works great for handling a variety of sign in methods, however when the user exits the app, the logged in state no longer persists. What would be the best way to keep the user logged in after exiting the application?

Body:
There are multiple ways you can do what you wanna do. Save your data, any kind of data - it's up to you in your local storage, such as:

Defaults

Keychain

Core Data

and whatnot....

Alternatively, in my opinion, you could just try to check the currentUser, like so:

let user = Auth.auth().currentUser

doc: https://firebase.google.com/docs/auth/ios/manage-users

and for javascript: (Authentication State Persistence
) https://firebase.google.com/docs/auth/web/auth-state-persistence


问:
Implementing empty iterators
I have this code:

```<code>    public IEnumerable<int> Iterator {
        get { if (false) yield return -1; }
    }
</code>```

It is fairly ugly, but when you try to refactor it to:

```<code>    public IEnumerable<int> Iterator {
        get { return null; }
    }
</code>```

The following code breaks:

```<code>foreach (var item in obj.Iterator) {
}
</code>```

How would you go about cleaning this up?

答:
```<code>public IEnumerable<int> Iterator {
    get { yield break; }
}
</code>```

Title: Implementing empty iterators

Body:
I have this code:

    public IEnumerable<int> Iterator {
        get { if (false) yield return -1; }
    }

It is fairly ugly, but when you try to refactor it to:

    public IEnumerable<int> Iterator {
        get { return null; }
    }

The following code breaks:

foreach (var item in obj.Iterator) {
}

How would you go about cleaning this up?

OwnerDisplayName: Mehrdad Afshari


问:
PL/SQL Oracle_home directory contents of listener.ora
I'm trying to write the contents of listener.ora to another file without hardcoding in the directory.

Originally it worked when I specified the directory as:

```<code>'C:\app\OracleDB11g\product\11.2.0\dbhome_1\NETWORK\ADMIN'
</code>```

But I don't want to hard-code because this script will be used different machines/DBs.

```<code>CREATE OR REPLACE DIRECTORY LISTENERDIR AS '%ORACLE_HOME%/NETWORK/ADMIN/';
declare
f utl_file.file_type;
fOUT utl_file.file_type;
s varchar2(200);
begin
f := utl_file.fopen('LISTENERDIR','listener.ora','R');
loop
    utl_file.get_line(f,s);
    fOUT := utl_file.fopen('OUTPUT','oraDBoutput.txt','A');
    utl_file.put_line(fOUT,s);
    utl_file.fclose(fOUT);
end loop;
exception
when NO_DATA_FOUND then
    utl_file.fclose(f);
end;
/

drop directory LISTENERDIR;
</code>```

I have tried using the other slashes, small caps, different variations such as \NETWORK\ADMIN, and even assigning a variable from the dbms_system.get_env() but no avail.

答:
See if this works for you:

```<code>SELECT SUBSTR(file_spec, 1, INSTR(file_spec, '\', -1, 2) -1)
FROM dba_libraries
WHERE library_name = 'DBMS_SUMADV_LIB';
</code>```

Found it here. And here.

This will programmatically get you the ORACLE_HOME, from there you can create your Oracle directory object:

```<code>DECLARE
  dir VARCHAR2(2000);
BEGIN
   SELECT 'CREATE OR REPLACE DIRECTORY  LISTENERDIR AS '''||
          SUBSTR(file_spec, 1, INSTR(file_spec, '\', -1, 2) -1) ||''''
    INTO dir
    FROM dba_libraries
    WHERE library_name = 'DBMS_SUMADV_LIB';

   EXECUTE IMMEDIATE dir;
   ... do your stuff here...
   EXECUTE IMMEDIATE 'DROP DIRECTORY LISTENERDIR';
END;
/
</code>```

Body:
I'm trying to write the contents of listener.ora to another file without hardcoding in the directory.

Originally it worked when I specified the directory as:

'C:\app\OracleDB11g\product\11.2.0\dbhome_1\NETWORK\ADMIN'

But I don't want to hard-code because this script will be used different machines/DBs.

CREATE OR REPLACE DIRECTORY LISTENERDIR AS '%ORACLE_HOME%/NETWORK/ADMIN/';
declare
f utl_file.file_type;
fOUT utl_file.file_type;
s varchar2(200);
begin
f := utl_file.fopen('LISTENERDIR','listener.ora','R');
loop
    utl_file.get_line(f,s);
    fOUT := utl_file.fopen('OUTPUT','oraDBoutput.txt','A');
    utl_file.put_line(fOUT,s);
    utl_file.fclose(fOUT);
end loop;
exception
when NO_DATA_FOUND then
    utl_file.fclose(f);
end;
/

drop directory LISTENERDIR;

I have tried using the other slashes, small caps, different variations such as \NETWORK\ADMIN, and even assigning a variable from the dbms_system.get_env() but no avail.

Body:
See if this works for you:

SELECT SUBSTR(file_spec, 1, INSTR(file_spec, '\', -1, 2) -1)
FROM dba_libraries
WHERE library_name = 'DBMS_SUMADV_LIB';

Found it here. And here.

This will programmatically get you the ORACLE_HOME, from there you can create your Oracle directory object:

DECLARE
  dir VARCHAR2(2000);
BEGIN
   SELECT 'CREATE OR REPLACE DIRECTORY  LISTENERDIR AS '''||
          SUBSTR(file_spec, 1, INSTR(file_spec, '\', -1, 2) -1) ||''''
    INTO dir
    FROM dba_libraries
    WHERE library_name = 'DBMS_SUMADV_LIB';

   EXECUTE IMMEDIATE dir;
   ... do your stuff here...
   EXECUTE IMMEDIATE 'DROP DIRECTORY LISTENERDIR';
END;
/