问:
react-select dropdown to be required
I am new to react.

I am trying to use below library to use dropdown.

When I added 'required' attribute, it doesn't validate it with the form tag.

https://www.npmjs.com/package/react-select

```<code>import React from 'react';
import Select from 'react-select';

const options = [{
        value: 'chocolate',
        label: 'Chocolate'
    },
    {
        value: 'strawberry',
        label: 'Strawberry'
    },
    {
        value: 'vanilla',
        label: 'Vanilla'
    },
];

class App extends React.Component {
    state = {
        selectedOption: null,
    };
    handleChange = selectedOption => {
        this.setState({
            selectedOption
        });
        console.log(`Option selected:`, selectedOption);
    };
    render() {
        const {
            selectedOption
        } = this.state;

        return ( <
            Select value = {
                selectedOption
            }
            onChange = {
                this.handleChange
            }
            options = {
                options
            }
            //required
            />
        );
    }
}
</code>```

When I looked at it from the console, it shows that input tag is wrapped with bunch of div. Is there a way to access the input from  Component? or is there a javascript code that I can access to input tag in order to add required directly?

答:
You should use form library like Formik and use Yup for form validation. Yup has powerful validation methods and is completely supported by Formik.
You can also write your own validation schema.</p>

Title: react-select dropdown to be required

Body:
I am new to react.

I am trying to use below library to use dropdown.

When I added 'required' attribute, it doesn't validate it with the form tag.

https://www.npmjs.com/package/react-select

import React from 'react';
import Select from 'react-select';

const options = [{
        value: 'chocolate',
        label: 'Chocolate'
    },
    {
        value: 'strawberry',
        label: 'Strawberry'
    },
    {
        value: 'vanilla',
        label: 'Vanilla'
    },
];

class App extends React.Component {
    state = {
        selectedOption: null,
    };
    handleChange = selectedOption => {
        this.setState({
            selectedOption
        });
        console.log(`Option selected:`, selectedOption);
    };
    render() {
        const {
            selectedOption
        } = this.state;

        return ( <
            Select value = {
                selectedOption
            }
            onChange = {
                this.handleChange
            }
            options = {
                options
            }
            //required
            />
        );
    }
}

When I looked at it from the console, it shows that input tag is wrapped with bunch of div. Is there a way to access the input from  Component? or is there a javascript code that I can access to input tag in order to add required directly?


来源: stackexchange

问:
How to refresh state when navigating back
I would like to be able to navigate to the previous page in my app but I don't want the page to keep it's previous state. How would I go about doing this?</p>

答:
Which state management do you use ?

In case of classic stful stless, you might need a callback.

Assuming you are on the next page :

```<code>             onPressed: () {
                // return to the parent ancestor the [value]
                Navigator.pop(context, value);
              },
</code>```

You get back with the previous page with some "value";
You need to modify the Navigator who let you handle the push to the next page;

```<code> onPressed: () async {
                  var value = await Navigator.push(
                    context,
                    MaterialPageRoute(
                      builder: (context) {
                        return SecondPage();
                      },
                    ),
                  );
                  // get the callback
                  // handle error
                  if (value != null) {
                    try {
                      setState(() {
                        // update your current state by the value you get from the second page
                         myUserName = value;
                      });
                    } catch (e) {
                      print('Errors');
                    }
                  }
                },
</code>```

You can handle many ways to achieve this. In case you are using other state management let me know.

ContentLicense: CC BY-SA 4.0

Body:
Which state management do you use ?

In case of classic stful stless, you might need a callback.

Assuming you are on the next page :

             onPressed: () {
                // return to the parent ancestor the [value]
                Navigator.pop(context, value);
              },

You get back with the previous page with some "value";
You need to modify the Navigator who let you handle the push to the next page;

 onPressed: () async {
                  var value = await Navigator.push(
                    context,
                    MaterialPageRoute(
                      builder: (context) {
                        return SecondPage();
                      },
                    ),
                  );
                  // get the callback
                  // handle error
                  if (value != null) {
                    try {
                      setState(() {
                        // update your current state by the value you get from the second page
                         myUserName = value;
                      });
                    } catch (e) {
                      print('Errors');
                    }
                  }
                },

You can handle many ways to achieve this. In case you are using other state management let me know.


问:
Can pseudo elements be incorporated in MJML?
I'm pretty new working with MJML, and I'm working on an email project where the visited links are a different color... Thus far, my understanding is that you cannot use pseudo-elements in MJML.  Does anyone know a way to do this?

For example, the link is normally blue, but once it's been clicked it becomes gray.

Thank you!!

答:
This seems to work:

```<code><mjml>
  <mj-head>
    <mj-style>
        a.blah:hover {
          color: #00ff00!important;
        }
      </mj-style>
  </mj-head>
  <mj-body>
    <mj-section>
      <mj-column>
        <mj-text font-size="20px" color="#F45E43" font-family="Verdana" >Hello <a href="#" class="blah">World</a></mj-text>
      </mj-column>
    </mj-section>
  </mj-body>
</mjml>
</code>```

You don't need the class necessarily (i.e. a:hover, and )

See also their documentation href="https://mjml.io/documentation/#mjml-style" rel="nofollow noreferrer">https://mjml.io/documentation/#mjml-style

Body:
This seems to work:

<mjml>
  <mj-head>
    <mj-style>
        a.blah:hover {
          color: #00ff00!important;
        }
      </mj-style>
  </mj-head>
  <mj-body>
    <mj-section>
      <mj-column>
        <mj-text font-size="20px" color="#F45E43" font-family="Verdana" >Hello <a href="#" class="blah">World</a></mj-text>
      </mj-column>
    </mj-section>
  </mj-body>
</mjml>

You don't need the class necessarily (i.e. a:hover, and <a href="#">)

See also their documentation https://mjml.io/documentation/#mjml-style


问:
How to add words in aspell dictionary?
I am using aspell in my application for spell checking. I don't have any idea about how to add words in aspell. Is it any way to add words </p>

答:
Songy's example echo "*WORD\n#" | aspell -a worked for me for a single word.  I was able to add text file (input.txt) containing a list of words using this command:

```<code>cat input.txt | while read word; do echo -e "*${word}\n#" | aspell -a; done
</code>```

Title: How to add words in aspell dictionary?

Body:
Songy's example echo "*WORD\n#" | aspell -a worked for me for a single word.  I was able to add text file (input.txt) containing a list of words using this command:

cat input.txt | while read word; do echo -e "*${word}\n#" | aspell -a; done


问:
How to split a list to certain number of lists

with open(path) as file:
    h=file.read().split('\n')
links = list(filter(None, h)) #147 length
chunks = [i.tolist() for i in np.array_split(links, 10) if i.size>0]
```

<p>How can I achieve the same output without using <code>numpy</code> or any external library (not pre-installed with python3)?</p>

<p>A reproducible code without any external libraries would be:</p>

<pre class="lang-py prettyprint-override"><code>links=range(147)
chunks = [i.tolist() for i in np.array_split(links, 10) if i.size>0]
</code>```

The desired output is 10 sub-lists: first 7 sub-list's lengths would be 15 and last 3 sub-list's length would be 14.

答:
Input:

```<code>links = list(range(147))
k = 10
</code>```

Iterator solution:

```<code>from itertools import islice
q, r = divmod(len(links), k)
it = iter(links)
chunks = [list(islice(it, q + (i < r))) for i in range(k)]
</code>```

Walrus solution:

```<code>q, r = divmod(len(links), k)
i = 0
chunks = [links[i : (i := i + q + (j < r))] for j in range(k)]
</code>```

Body:
with open(path) as file:
    h=file.read().split('\n')
links = list(filter(None, h)) #147 length
chunks = [i.tolist() for i in np.array_split(links, 10) if i.size>0]

How can I achieve the same output without using numpy or any external library (not pre-installed with python3)?

A reproducible code without any external libraries would be:

links=range(147)
chunks = [i.tolist() for i in np.array_split(links, 10) if i.size>0]

The desired output is 10 sub-lists: first 7 sub-list's lengths would be 15 and last 3 sub-list's length would be 14.

Body:
Input:

links = list(range(147))
k = 10

Iterator solution:

from itertools import islice
q, r = divmod(len(links), k)
it = iter(links)
chunks = [list(islice(it, q + (i < r))) for i in range(k)]

Walrus solution:

q, r = divmod(len(links), k)
i = 0
chunks = [links[i : (i := i + q + (j < r))] for j in range(k)]


问:
Is there any terraform module to create folders within a Bucket (GCP)
Is there any terraform module to create folders within a Bucket (GCP) ?
That is to say, I already know that with the module google_storage_bucket we can create GCS buckets in GCP.
But, is there any way to create folders within a bucket (GCP) by using terraform ?

thanks,

答: Object storage  is completely flat. There are no folders. When you see a folder in the UI or output from a command, it's just metadata describing how to show it to you.</p>


问:
using python in c++ basics
can anyone show me a basic program that includes python in a c++ program? i have gotten #include <Python.h> to work, but thats about it. how do you create a string, int, and include a module that is not part of the python library?

答: I suggest Boost Python, since you're using C++ rather than C.  The documentation is decent, but note that you can skip much of the "Hello World" example if your platform has Boost packages already built for it (so you don't need to build Boost yourself using bjam).</p>

ContentLicense: CC BY-SA 3.0

Title: using python in c++ basics


问:
Why can I not mutably borrow separate fields from a mutex guard?
Trying to get mutable references to separate fields through a MutexGuard:

```<code>struct MyObject {
    pub a: i32,
    pub b: i32,
}

fn func_1(mtx: &Mutex<MyObject>) {
    let mut obj = mtx.lock().unwrap();
    let a = &mut obj.a;
    let b = &mut obj.b;

    *a += 1;
    *b *= 2;
}
</code>```

results in an error:

```<code>error[E0499]: cannot borrow `obj` as mutable more than once at a time
  --> src/main.rs:11:18
   |
10 |     let a = &mut obj.a;
   |                  --- first mutable borrow occurs here
11 |     let b = &mut obj.b;
   |                  ^^^ second mutable borrow occurs here
12 |
13 |     *a += 1;
   |     ------- first borrow later used here
</code>```

This has me a bit confused. This works when obj is a simple mutable reference (&mut MyObject). I thought maybe the Deref trait was the one causing the problem, but it also works if obj is a &mut Box<MyObject>.

See it on the Rust Playground.

What am I missing?

答:
Mutex::lock returns a RAII lock guard in addition of ways to deal with its contained value. To get its contained value as &mut (and subsequently "split borrow"), you need to:

save the guard (returned by lock) in a separate value, as the lock needs to live as long as the value is accessed.

extract the value as &mut from the guard with MutexGuard::deref_mut.

Here's an updated func_1:

```<code>use std::ops::DerefMut;

fn func_1(mtx: &Mutex<MyObject>) {
    let mut guard = mtx.lock().unwrap();
    let obj = guard.deref_mut();
    let a = &mut obj.a;
    let b = &mut obj.b;

    *a += 1;
    *b *= 2;
}
</code>```

Body:
Trying to get mutable references to separate fields through a MutexGuard:

struct MyObject {
    pub a: i32,
    pub b: i32,
}

fn func_1(mtx: &Mutex<MyObject>) {
    let mut obj = mtx.lock().unwrap();
    let a = &mut obj.a;
    let b = &mut obj.b;

    *a += 1;
    *b *= 2;
}

results in an error:

error[E0499]: cannot borrow `obj` as mutable more than once at a time
  --> src/main.rs:11:18
   |
10 |     let a = &mut obj.a;
   |                  --- first mutable borrow occurs here
11 |     let b = &mut obj.b;
   |                  ^^^ second mutable borrow occurs here
12 |
13 |     *a += 1;
   |     ------- first borrow later used here

This has me a bit confused. This works when obj is a simple mutable reference (&mut MyObject). I thought maybe the Deref trait was the one causing the problem, but it also works if obj is a &mut Box<MyObject>.

See it on the Rust Playground.

What am I missing?

Body:
Mutex::lock returns a RAII lock guard in addition of ways to deal with its contained value. To get its contained value as &mut (and subsequently "split borrow"), you need to:

save the guard (returned by lock) in a separate value, as the lock needs to live as long as the value is accessed.

extract the value as &mut from the guard with MutexGuard::deref_mut.

Here's an updated func_1:

use std::ops::DerefMut;

fn func_1(mtx: &Mutex<MyObject>) {
    let mut guard = mtx.lock().unwrap();
    let obj = guard.deref_mut();
    let a = &mut obj.a;
    let b = &mut obj.b;

    *a += 1;
    *b *= 2;
}


问:
AppleScript: dialog with multiple rows of buttons
A code like this display dialog "choose" buttons {"yes", "no"} creates a dialog with 2 buttons, in a single row, as expected.

I am trying to find out if it is possible to create more than one row of buttons.

For example, first row could have buttons {"red", "yellow", "blue"}, second row could be {"large", "small"}, and a third row could just be {"cancel"}.

Is it possible?

答:
You may want to take a look at Dialog Toolkit. It is a scripting addition which can be used in Script Editor:

Dialog Toolkit Plus v1.0.1 and Dialog Toolkit v2.0.3

Dialog Toolkit and Dialog Toolkit Plus are ASObjC-based script libraries for showing enhanced dialogs. Add multiple text entry fields, checkboxes, popup menus, radio buttons, path controls, extra buttons and rules to dialogs. Dialog Toolkit v2.0.3 is a compatible update that fixes an issue with macOS High Sierra (10.13), while Dialog Toolkit Plus is an enhanced version that gives greater flexibility but requires macOS 10.10 or later. You can download the libraries and documentation here. (Direct Download Link)

Here are some screenshots of sample dialogs created using the Dialog Tool Kit script library, in Script Editor.app


问:
How do I make a program in C that will read ad print specific lines from a file?
```<code>#include <stdio.h>
#include <stdlib.h>

int main(void)
{
  FILE * ofile;

  char fname[100], c;

  printf("Please enter a file name: \n");
  scanf("%s", fname);

  ofile = fopen(fname, "r+");
  if (ofile == NULL)
    {
      printf("This file cannot be opened!\n");
      exit(0);
    }
  c = fgetc(ofile);
  while (c != EOF)
    {
      printf("%c", c);
      c = fgetc(ofile);
    }

  fclose(ofile);

  return 0;

}
</code>```

This is what I have, and it just prints everything. I can't find any resources that tell me how to make it print just the first or last three lines, or how to specify lines at all. I don't need to specify by what the lines contain, just where they are.

答:
You can manually track which line you are on and compare. </p>

```<code>int line = 0;
while (c != EOF)
{
    if (c == '\n')
    {
        line++;
    }
    if (line != 0)
    {
        printf("%c", c);
    }
    c = fgetc(ofile);
}
</code>```

<p>This addition will skip the first line, but print the rest. It can be modified as you like. </p>

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

int main(void)
{
  FILE * ofile;

  char fname[100], c;

  printf("Please enter a file name: \n");
  scanf("%s", fname);

  ofile = fopen(fname, "r+");
  if (ofile == NULL)
    {
      printf("This file cannot be opened!\n");
      exit(0);
    }
  c = fgetc(ofile);
  while (c != EOF)
    {
      printf("%c", c);
      c = fgetc(ofile);
    }

  fclose(ofile);

  return 0;

}

This is what I have, and it just prints everything. I can't find any resources that tell me how to make it print just the first or last three lines, or how to specify lines at all. I don't need to specify by what the lines contain, just where they are.

Body:
You can manually track which line you are on and compare.

int line = 0;
while (c != EOF)
{
    if (c == '\n')
    {
        line++;
    }
    if (line != 0)
    {
        printf("%c", c);
    }
    c = fgetc(ofile);
}

This addition will skip the first line, but print the rest. It can be modified as you like.


问:
T-SQL: Deleting all duplicate rows but keeping one
I have a table with a very large amount of rows. Duplicates are not allowed but due to a problem with how the rows were created I know there are some duplicates in this table.
I need to eliminate the extra rows from the perspective of the key columns. Some other columns may have slightly different data but I do not care about that. I still need to keep one of these rows however. SELECT DISTINCT won't work because it operates on all columns and I need to suppress duplicates based on the key columns.

How can I delete the extra rows but still keep one efficiently?

答:
Here's my twist on it, with a runnable example. Note this will only work in the situation where Id is unique, and you have duplicate values in other columns.

```<code>DECLARE @SampleData AS TABLE (Id int, Duplicate varchar(20))

INSERT INTO @SampleData
SELECT 1, 'ABC' UNION ALL
SELECT 2, 'ABC' UNION ALL
SELECT 3, 'LMN' UNION ALL
SELECT 4, 'XYZ' UNION ALL
SELECT 5, 'XYZ'

DELETE FROM @SampleData WHERE Id IN (
    SELECT Id FROM (
        SELECT
            Id
            ,ROW_NUMBER() OVER (PARTITION BY [Duplicate] ORDER BY Id) AS [ItemNumber]
            -- Change the partition columns to include the ones that make the row distinct
        FROM
            @SampleData
    ) a WHERE ItemNumber > 1 -- Keep only the first unique item
)

SELECT * FROM @SampleData
</code>```

And the results:

```<code>Id          Duplicate
----------- ---------
1           ABC
3           LMN
4           XYZ
</code>```

Not sure why that's what I thought of first... definitely not the simplest way to go but it works.

Body:
Here's my twist on it, with a runnable example. Note this will only work in the situation where Id is unique, and you have duplicate values in other columns.

DECLARE @SampleData AS TABLE (Id int, Duplicate varchar(20))

INSERT INTO @SampleData
SELECT 1, 'ABC' UNION ALL
SELECT 2, 'ABC' UNION ALL
SELECT 3, 'LMN' UNION ALL
SELECT 4, 'XYZ' UNION ALL
SELECT 5, 'XYZ'

DELETE FROM @SampleData WHERE Id IN (
    SELECT Id FROM (
        SELECT
            Id
            ,ROW_NUMBER() OVER (PARTITION BY [Duplicate] ORDER BY Id) AS [ItemNumber]
            -- Change the partition columns to include the ones that make the row distinct
        FROM
            @SampleData
    ) a WHERE ItemNumber > 1 -- Keep only the first unique item
)

SELECT * FROM @SampleData

And the results:

Id          Duplicate
----------- ---------
1           ABC
3           LMN
4           XYZ

Not sure why that's what I thought of first... definitely not the simplest way to go but it works.


问:
Fill input value inside a v-for
I'm trying to set the value for each input inside a v-for, but the value is not shown in the input.  {{slideshow.timeout}} is printing the value, but the v-model is not working.
 Am I missing something? I'm new to Vue.

```<code><tr v-for="(slideshow, index) in slideshows">
      <td>{{slideshow.timeout}}</td>
      <td>
         <input type="text" :model="slideshow.timeout" class="form-control">
      </td>

</tr>
</code>```

答:
Try this out:

```<code>  <input type="text" v-model="slideshows[index].timeout" class="form-control">
</code>```

since v-model is a directive et it's not a bound attribute

Title: Fill input value inside a v-for

Body:
I'm trying to set the value for each input inside a v-for, but the value is not shown in the input.  {{slideshow.timeout}} is printing the value, but the v-model is not working.
 Am I missing something? I'm new to Vue.

      {{slideshow.timeout}}

         <input type="text" :model="slideshow.timeout" class="form-control">

Body:
Try this out:

  <input type="text" v-model="slideshows[index].timeout" class="form-control">

since v-model is a directive et it's not a bound attribute


问:
How to remove thousand separator in a list of tuple?
I have a master_list which contains a list of lists, I'm trying to turn it into a list of tuples that only contains line[3]: the numbers of games played, and line[0]: the players' names. The list will be sorted on games played (highest to lowest) and only the top ten are
returned, i.e. the list contains ten tuples in decreasing, sorted order.
And I must  remove the comma and convert to an integer before sorting

The output of my code is correct except the thousand separators are still there. This is my code:

```<code>def games_played(master_list):
container2 = []
for line in master_list:
    try:
        int(line[3])
        continue
    except ValueError:
        for i in line[3]:
            i = i.replace(",", "")
            continue
    container2.append(((line[3]), line[0]))
container2.sort(reverse = True)
container2 = container2[:10]
print(container2)
</code>```

and this is my output:

```<code>[
 ('1,767', 'Gordie Howe'),
 ('1,756', 'Mark Messier'),
 ('1,733', 'Jaromir Jagr'),
 ('1,731', 'Ron Francis'),
 ('1,514', 'Steve Yzerman'),
 ('1,487', 'Wayne Gretzky'),
 ('1,451', 'Teemu Selanne'),
 ('1,409', 'Paul Coffey'),
 ('1,396', 'Stan Mikita'),
 ('1,378', 'Joe Sakic')
]
</code>```

答:
Just add the line (after the last assignment to container2):</p>

```<code>container2 = list(map(lambda x: (int(x[0].replace(',','')),x[1]),container2))
</code>```

Body:
I have a master_list which contains a list of lists, I'm trying to turn it into a list of tuples that only contains line[3]: the numbers of games played, and line[0]: the players' names. The list will be sorted on games played (highest to lowest) and only the top ten are
returned, i.e. the list contains ten tuples in decreasing, sorted order.
And I must  remove the comma and convert to an integer before sorting

The output of my code is correct except the thousand separators are still there. This is my code:

def games_played(master_list):
container2 = []
for line in master_list:
    try:
        int(line[3])
        continue
    except ValueError:
        for i in line[3]:
            i = i.replace(",", "")
            continue
    container2.append(((line[3]), line[0]))
container2.sort(reverse = True)
container2 = container2[:10]
print(container2)

and this is my output:

[
 ('1,767', 'Gordie Howe'),
 ('1,756', 'Mark Messier'),
 ('1,733', 'Jaromir Jagr'),
 ('1,731', 'Ron Francis'),
 ('1,514', 'Steve Yzerman'),
 ('1,487', 'Wayne Gretzky'),
 ('1,451', 'Teemu Selanne'),
 ('1,409', 'Paul Coffey'),
 ('1,396', 'Stan Mikita'),
 ('1,378', 'Joe Sakic')
]

Body:
Just add the line (after the last assignment to container2):

container2 = list(map(lambda x: (int(x[0].replace(',','')),x[1]),container2))


问:
Heading Text and Icon Alignment Issue
I'm having trouble trying to align my heading tag text and font awesome icon in the correct places inside my navigation bar. When my navigation bar expands, I wish for the heading text (sidenav-heading) and icon (sidenav-expand) to be on the same line, while the heading text is on the left (as it is) and the icon on the right (as it is). My code:

let sidenav = document.getElementById("sidenav");
sidenav.onmouseover = function() {
  //expandNav();
  sidenav.style.width = "250px";
  document.getElementById("expand-icon").classList.add("expand");
  document.getElementById("sidenav-expand").style.textAlign = "right";
  document.getElementById("sidenav-heading").style.display = "inline-block";
};
sidenav.onmouseout = function() {
  //closeNav();
  sidenav.style.width = "75px";
  document.getElementById("expand-icon").classList.remove("expand");
  document.getElementById("sidenav-expand").style.textAlign = "center";
  document.getElementById("sidenav-heading").style.display = "none";
};```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#sidenav {
  height: 100%;
  width: 75px;
  position: fixed;
  z-index: 1;
  top: 0;
  left: 0;
  background-color: #1e1e2d;
  overflow-x: hidden;
  color: white;
  transition: 0.8s;
}

#sidenav-brand {
  padding: 25px 10px;
  background-color: aqua;
}

#sidenav-heading {}

#sidenav-expand {
  text-align: center;
}

.expand {
  transform: rotate(180deg);
}</code>```

<!DOCTYPE html>

  <meta charset="UTF-8" />
  <title>Navigation Bar</title>
  <link href="css/style.css" rel="stylesheet" type="text/css" />

Expanded

```

AND a jsfiddle link:
https://jsfiddle.net/khean52w/

答:
Please update #sidenav-brand class as follows, it should work: </p>

```<code>#sidenav-brand {
  padding: 25px 10px;
  background-color: aqua;
  display: flex;
  flex-direction: row;
  justify-content: space-between;
  align-items: center;
}
</code>```

Title: Heading Text and Icon Alignment Issue

Body:
I'm having trouble trying to align my heading tag text and font awesome icon in the correct places inside my navigation bar. When my navigation bar expands, I wish for the heading text (sidenav-heading) and icon (sidenav-expand) to be on the same line, while the heading text is on the left (as it is) and the icon on the right (as it is). My code:

let sidenav = document.getElementById("sidenav");
sidenav.onmouseover = function() {
  //expandNav();
  sidenav.style.width = "250px";
  document.getElementById("expand-icon").classList.add("expand");
  document.getElementById("sidenav-expand").style.textAlign = "right";
  document.getElementById("sidenav-heading").style.display = "inline-block";
};
sidenav.onmouseout = function() {
  //closeNav();
  sidenav.style.width = "75px";
  document.getElementById("expand-icon").classList.remove("expand");
  document.getElementById("sidenav-expand").style.textAlign = "center";
  document.getElementById("sidenav-heading").style.display = "none";
};

#sidenav {
  height: 100%;
  width: 75px;
  position: fixed;
  z-index: 1;
  top: 0;
  left: 0;
  background-color: #1e1e2d;
  overflow-x: hidden;
  color: white;
  transition: 0.8s;
}

#sidenav-brand {
  padding: 25px 10px;
  background-color: aqua;
}

#sidenav-heading {}

#sidenav-expand {
  text-align: center;
}

.expand {
  transform: rotate(180deg);
}

<!DOCTYPE html>

  <meta charset="UTF-8" />
  <title>Navigation Bar</title>
  <link href="css/style.css" rel="stylesheet" type="text/css" />

Expanded

AND a jsfiddle link:
https://jsfiddle.net/khean52w/

Body:
Please update #sidenav-brand class as follows, it should work:

#sidenav-brand {
  padding: 25px 10px;
  background-color: aqua;
  display: flex;
  flex-direction: row;
  justify-content: space-between;
  align-items: center;
}


问:
react-native set ENVFILE file for builds / archives
I'm really confused about production / development builds in react-native.  I can get my app working on both iOS and Android by using the package scripts in the terminal

```<code>ENVFILE='/path/to/.env' react-native run-ios
ENVFILE='/path/to/.env' react-native run-android
</code>```

Thats great for running my app locally, but how do I run this command when creating archives through xcode?

I successfully installed react-native-config and I have the variables I need in the JS and native files, its just the final step of using this is prod or staging builds for devices.

I've managed to create fastlane scripts that build and deploy my app (and I can reference my .env vars in fastlane scripts) but that still doesn't bundle my app with the .env vars inside.  Its probably something obvious but i'm not understanding the concept at all.

Ive been referencing this tutorial here, and noticing the part about adding a pre-script to each Scheme in xcode:

```<code>".env" > /tmp/envfile
</code>```

But I dont know what the current working directory on that script is, and Im using yarn workspaces so my node_modules folder is not at the root of the RN project (doesnt that even matter?). I've tried multiple paths to my .env from here but nothing works, but I also dont know how to test this script.

答:
I've successfully gotten it to work using Fastlane. I followed this guide for the Fastlane setup:

https://github.com/thecodingmachine/react-native-boilerplate/blob/master/documentation/docs/3_Guides/BetaBuild.md

After following the guide, I moved the Fastlane directory to the root of the project (and updated all paths).

And after that added the ENV variable when running the command, for example: ENVFILE=.env.beta fastlane ios, which is easy to add as a script in package.json.

It's also possible to use the dotenv feature in Fastlane, see https://github.com/fastlane/fastlane/issues/13494#issuecomment-428941643.

Bottom line is that Fastlane will use the environment variable when running the packager, meaning that react-native-config will successfully pick it up and use the proper env-file.

Body:
I'm really confused about production / development builds in react-native.  I can get my app working on both iOS and Android by using the package scripts in the terminal

ENVFILE='/path/to/.env' react-native run-ios
ENVFILE='/path/to/.env' react-native run-android

Thats great for running my app locally, but how do I run this command when creating archives through xcode?

I successfully installed react-native-config and I have the variables I need in the JS and native files, its just the final step of using this is prod or staging builds for devices.

I've managed to create fastlane scripts that build and deploy my app (and I can reference my .env vars in fastlane scripts) but that still doesn't bundle my app with the .env vars inside.  Its probably something obvious but i'm not understanding the concept at all.

Ive been referencing this tutorial here, and noticing the part about adding a pre-script to each Scheme in xcode:

".env" > /tmp/envfile

But I dont know what the current working directory on that script is, and Im using yarn workspaces so my node_modules folder is not at the root of the RN project (doesnt that even matter?). I've tried multiple paths to my .env from here but nothing works, but I also dont know how to test this script.


问:
Conditional type for TypeName giving error
The following type is from the TypeScript docs:

```<code>export type TypeName<T> =
  T extends string ? 'string' :
  T extends number ? 'number' :
  T extends boolean ? 'boolean' :
  T extends undefined ? 'undefined' :
  T extends Function ? 'function' :
  'object';
</code>```

However trying to create a function that behaves that way gives an error:

```<code>export type TypeName<T> =
  T extends string ? 'string' :
  T extends number ? 'number' :
  T extends boolean ? 'boolean' :
  T extends undefined ? 'undefined' :
  T extends Function ? 'function' :
  'object';

function typeName<T>(t: T): TypeName<T> {
  return typeof t; // ERROR: type '"string"' is not assignable to type 'TypeName<T>'
}
</code>```

答:
The reason is that conditional types do not follow the control flow within the function.

The relevant issue is : https://github.com/microsoft/TypeScript/issues/33912

e.g. the following (from the mentioned issue) results in a similar error:

```<code>type SomeConditionalType<T> = T extends string ? 1 : -1;
function fn<T>(arg: T): SomeConditionalType<T> {
    if (typeof arg === "string") {
        return 1; // ERROR: not assignable to SomeConditionalType<T>
    } else {
        return -1; // ERROR: not assignable to SomeConditionalType<T>
    }
}
</code>```

Workaround

The simplest workaround is to use a type assertion within the function e.g.

```<code>export type TypeName<T> =
  T extends string ? 'string' :
  T extends number ? 'number' :
  T extends boolean ? 'boolean' :
  T extends undefined ? 'undefined' :
  T extends Function ? 'function' :
  'object';

function typeName<T>(t: T): TypeName<T> {
  return typeof t as TypeName<T>;
}
</code>```

Body:
The following type is from the TypeScript docs:

export type TypeName<T> =
  T extends string ? 'string' :
  T extends number ? 'number' :
  T extends boolean ? 'boolean' :
  T extends undefined ? 'undefined' :
  T extends Function ? 'function' :
  'object';

However trying to create a function that behaves that way gives an error:

export type TypeName<T> =
  T extends string ? 'string' :
  T extends number ? 'number' :
  T extends boolean ? 'boolean' :
  T extends undefined ? 'undefined' :
  T extends Function ? 'function' :
  'object';

function typeName<T>(t: T): TypeName<T> {
  return typeof t; // ERROR: type '"string"' is not assignable to type 'TypeName<T>'
}

Body:
The reason is that conditional types do not follow the control flow within the function.

The relevant issue is : https://github.com/microsoft/TypeScript/issues/33912

e.g. the following (from the mentioned issue) results in a similar error:

type SomeConditionalType<T> = T extends string ? 1 : -1;
function fn<T>(arg: T): SomeConditionalType<T> {
    if (typeof arg === "string") {
        return 1; // ERROR: not assignable to SomeConditionalType<T>
    } else {
        return -1; // ERROR: not assignable to SomeConditionalType<T>
    }
}

Workaround

The simplest workaround is to use a type assertion within the function e.g.

export type TypeName<T> =
  T extends string ? 'string' :
  T extends number ? 'number' :
  T extends boolean ? 'boolean' :
  T extends undefined ? 'undefined' :
  T extends Function ? 'function' :
  'object';

function typeName<T>(t: T): TypeName<T> {
  return typeof t as TypeName<T>;
}


问:
PreferenceScreen class not found
I have this in preferences.xml

```<code><?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android">

    <CheckBoxPreference
        android:key="displayNotification"
        android:title="Display notification"
        />

    <ListPreference
        android:entries="@array/languages"
        android:key="language"
        />
</PreferenceScreen>
</code>```

PreferencesActivity.java, the class that uses this xml

```<code>public class PreferencesActivity extends PreferenceActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);

        setContentView(R.xml.preferences);
    }
}
</code>```

And I have it declared in the manifest like this

```<code><activity android:name="com.tellthetime.PreferencesActivity" />
</code>```

When I start the activity I get a class not found exception, which I don't understand.

```<code>05-17 00:35:13.633: ERROR/AndroidRuntime(212): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.tellthetime/com.tellthetime.PreferencesActivity}: android.view.InflateException: Binary XML file line #2: Error inflating class PreferenceScreen
05-17 00:35:13.633: ERROR/AndroidRuntime(212):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2496)
05-17 00:35:13.633: ERROR/AndroidRuntime(212):     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2512)
05-17 00:35:13.633: ERROR/AndroidRuntime(212):     at android.app.ActivityThread.access$2200(ActivityThread.java:119)
05-17 00:35:13.633: ERROR/AndroidRuntime(212):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1863)
05-17 00:35:13.633: ERROR/AndroidRuntime(212):     at android.os.Handler.dispatchMessage(Handler.java:99)
05-17 00:35:13.633: ERROR/AndroidRuntime(212):     at android.os.Looper.loop(Looper.java:123)
05-17 00:35:13.633: ERROR/AndroidRuntime(212):     at android.app.ActivityThread.main(ActivityThread.java:4363)
05-17 00:35:13.633: ERROR/AndroidRuntime(212):     at java.lang.reflect.Method.invokeNative(Native Method)
05-17 00:35:13.633: ERROR/AndroidRuntime(212):     at java.lang.reflect.Method.invoke(Method.java:521)
05-17 00:35:13.633: ERROR/AndroidRuntime(212):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:860)
05-17 00:35:13.633: ERROR/AndroidRuntime(212):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:618)
05-17 00:35:13.633: ERROR/AndroidRuntime(212):     at dalvik.system.NativeStart.main(Native Method)
05-17 00:35:13.633: ERROR/AndroidRuntime(212): Caused by: android.view.InflateException: Binary XML file line #2: Error inflating class PreferenceScreen
05-17 00:35:13.633: ERROR/AndroidRuntime(212):     at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:576)
05-17 00:35:13.633: ERROR/AndroidRuntime(212):     at android.view.LayoutInflater.inflate(LayoutInflater.java:385)
05-17 00:35:13.633: ERROR/AndroidRuntime(212):     at android.view.LayoutInflater.inflate(LayoutInflater.java:320)
05-17 00:35:13.633: ERROR/AndroidRuntime(212):     at android.view.LayoutInflater.inflate(LayoutInflater.java:276)
05-17 00:35:13.633: ERROR/AndroidRuntime(212):     at com.android.internal.policy.impl.PhoneWindow.setContentView(PhoneWindow.java:198)
05-17 00:35:13.633: ERROR/AndroidRuntime(212):     at android.app.Activity.setContentView(Activity.java:1622)
05-17 00:35:13.633: ERROR/AndroidRuntime(212):     at com.tellthetime.PreferencesActivity.onCreate(PreferencesActivity.java:13)
05-17 00:35:13.633: ERROR/AndroidRuntime(212):     at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
05-17 00:35:13.633: ERROR/AndroidRuntime(212):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2459)
05-17 00:35:13.633: ERROR/AndroidRuntime(212):     ... 11 more
05-17 00:35:13.633: ERROR/AndroidRuntime(212): Caused by: java.lang.ClassNotFoundException: android.view.PreferenceScreen in loader dalvik.system.PathClassLoader@44c067e8
05-17 00:35:13.633: ERROR/AndroidRuntime(212):     at dalvik.system.PathClassLoader.findClass(PathClassLoader.java:243)
05-17 00:35:13.633: ERROR/AndroidRuntime(212):     at java.lang.ClassLoader.loadClass(ClassLoader.java:573)
05-17 00:35:13.633: ERROR/AndroidRuntime(212):     at java.lang.ClassLoader.loadClass(ClassLoader.java:532)
05-17 00:35:13.633: ERROR/AndroidRuntime(212):     at android.view.LayoutInflater.createView(LayoutInflater.java:466)
05-17 00:35:13.633: ERROR/AndroidRuntime(212):     at android.view.LayoutInflater.onCreateView(LayoutInflater.java:544)
05-17 00:35:13.633: ERROR/AndroidRuntime(212):     at com.android.internal.policy.impl.PhoneLayoutInflater.onCreateView(PhoneLayoutInflater.java:66)
05-17 00:35:13.633: ERROR/AndroidRuntime(212):     at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:563)
05-17 00:35:13.633: ERROR/AndroidRuntime(212):     ... 19 more
</code>```

This was already asked here but no one answered. As pointed out in that thread by Heiko Rupp, android is looking for the class in the package android.view, but the class is in android.preferences, this really lost me.

答:
You're getting confused, you're trying to set the preference definition as the layout definition. First set a layout for the Activity, then bind your preferences XML:

```<code>  ...
  setContentView(R.layout.layout);
  addPreferencesFromResource(R.xml.preferences);
  ...
</code>```

Title: PreferenceScreen class not found

Body:
I have this in preferences.xml

<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android">

    <CheckBoxPreference
        android:key="displayNotification"
        android:title="Display notification"
        />

    <ListPreference
        android:entries="@array/languages"
        android:key="language"
        />
</PreferenceScreen>

PreferencesActivity.java, the class that uses this xml

public class PreferencesActivity extends PreferenceActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);

        setContentView(R.xml.preferences);
    }
}

And I have it declared in the manifest like this

<activity android:name="com.tellthetime.PreferencesActivity" />

When I start the activity I get a class not found exception, which I don't understand.

05-17 00:35:13.633: ERROR/AndroidRuntime(212): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.tellthetime/com.tellthetime.PreferencesActivity}: android.view.InflateException: Binary XML file line #2: Error inflating class PreferenceScreen
05-17 00:35:13.633: ERROR/AndroidRuntime(212):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2496)
05-17 00:35:13.633: ERROR/AndroidRuntime(212):     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2512)
05-17 00:35:13.633: ERROR/AndroidRuntime(212):     at android.app.ActivityThread.access$2200(ActivityThread.java:119)
05-17 00:35:13.633: ERROR/AndroidRuntime(212):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1863)
05-17 00:35:13.633: ERROR/AndroidRuntime(212):     at android.os.Handler.dispatchMessage(Handler.java:99)
05-17 00:35:13.633: ERROR/AndroidRuntime(212):     at android.os.Looper.loop(Looper.java:123)
05-17 00:35:13.633: ERROR/AndroidRuntime(212):     at android.app.ActivityThread.main(ActivityThread.java:4363)
05-17 00:35:13.633: ERROR/AndroidRuntime(212):     at java.lang.reflect.Method.invokeNative(Native Method)
05-17 00:35:13.633: ERROR/AndroidRuntime(212):     at java.lang.reflect.Method.invoke(Method.java:521)
05-17 00:35:13.633: ERROR/AndroidRuntime(212):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:860)
05-17 00:35:13.633: ERROR/AndroidRuntime(212):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:618)
05-17 00:35:13.633: ERROR/AndroidRuntime(212):     at dalvik.system.NativeStart.main(Native Method)
05-17 00:35:13.633: ERROR/AndroidRuntime(212): Caused by: android.view.InflateException: Binary XML file line #2: Error inflating class PreferenceScreen
05-17 00:35:13.633: ERROR/AndroidRuntime(212):     at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:576)
05-17 00:35:13.633: ERROR/AndroidRuntime(212):     at android.view.LayoutInflater.inflate(LayoutInflater.java:385)
05-17 00:35:13.633: ERROR/AndroidRuntime(212):     at android.view.LayoutInflater.inflate(LayoutInflater.java:320)
05-17 00:35:13.633: ERROR/AndroidRuntime(212):     at android.view.LayoutInflater.inflate(LayoutInflater.java:276)
05-17 00:35:13.633: ERROR/AndroidRuntime(212):     at com.android.internal.policy.impl.PhoneWindow.setContentView(PhoneWindow.java:198)
05-17 00:35:13.633: ERROR/AndroidRuntime(212):     at android.app.Activity.setContentView(Activity.java:1622)
05-17 00:35:13.633: ERROR/AndroidRuntime(212):     at com.tellthetime.PreferencesActivity.onCreate(PreferencesActivity.java:13)
05-17 00:35:13.633: ERROR/AndroidRuntime(212):     at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
05-17 00:35:13.633: ERROR/AndroidRuntime(212):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2459)
05-17 00:35:13.633: ERROR/AndroidRuntime(212):     ... 11 more
05-17 00:35:13.633: ERROR/AndroidRuntime(212): Caused by: java.lang.ClassNotFoundException: android.view.PreferenceScreen in loader dalvik.system.PathClassLoader@44c067e8
05-17 00:35:13.633: ERROR/AndroidRuntime(212):     at dalvik.system.PathClassLoader.findClass(PathClassLoader.java:243)
05-17 00:35:13.633: ERROR/AndroidRuntime(212):     at java.lang.ClassLoader.loadClass(ClassLoader.java:573)
05-17 00:35:13.633: ERROR/AndroidRuntime(212):     at java.lang.ClassLoader.loadClass(ClassLoader.java:532)
05-17 00:35:13.633: ERROR/AndroidRuntime(212):     at android.view.LayoutInflater.createView(LayoutInflater.java:466)
05-17 00:35:13.633: ERROR/AndroidRuntime(212):     at android.view.LayoutInflater.onCreateView(LayoutInflater.java:544)
05-17 00:35:13.633: ERROR/AndroidRuntime(212):     at com.android.internal.policy.impl.PhoneLayoutInflater.onCreateView(PhoneLayoutInflater.java:66)
05-17 00:35:13.633: ERROR/AndroidRuntime(212):     at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:563)
05-17 00:35:13.633: ERROR/AndroidRuntime(212):     ... 19 more

This was already asked here but no one answered. As pointed out in that thread by Heiko Rupp, android is looking for the class in the package android.view, but the class is in android.preferences, this really lost me.

Body:
You're getting confused, you're trying to set the preference definition as the layout definition. First set a layout for the Activity, then bind your preferences XML:

  ...
  setContentView(R.layout.layout);
  addPreferencesFromResource(R.xml.preferences);
  ...


问:
wkwebview: find out if loaded content in web view is PDF and give download button
I am using wkWebView to load research papers published on IEEE, Science Direct, etc. so when I click on any PDF in the research papers, PDF gets loaded into webview, so is there a way to detect and enable a download icon in wkWebView.

Tried Solution:
I have tried to get the pdf from URLs via URLSession and this is working for like 95% of the times but sometimes I don't get the content of PDF via URLSession and pdf gets loaded into webview because of dynamic URL/PDF creation.

In research, I came across: Get already loaded PDF directly from WKWebView without downloading again But in my case first I need to check if the loaded content is PDF.

A relevant question: add download button for pdf in wkwebview in swift 4 But no answer!!!

To test: open URL: https://www.sciencedirect.com/science/article/pii/S0946672X17308763 in wkWebView and click on the "Download PDF" button this will load the pdf into webview.

In short: Any way to detect if the loaded content is PDF and give a download button to download the pdf content into the documents folder.

Any help appreciated...Thanks

答:
I've tried the link you've provided and it seems like the download button opens PDF in a new window (html tag ) and WKWebView just ignores it.

To make navigation possible you should adopt WKUIDelegate protocol in your view controller and implement a delegate method:

```<code>override func viewDidLoad() {
   super.viewDidLoad()
   self.webView.uiDelegate = self
}

func webView(_ webView: WKWebView, createWebViewWith configuration: WKWebViewConfiguration, for navigationAction: WKNavigationAction, windowFeatures: WKWindowFeatures) -> WKWebView? {
    if navigationAction.targetFrame == nil {
        // Here we load this request manually in current window
        webView.load(navigationAction.request)
    }
    return nil
}
</code>```

In this example the PDF will be loaded directly into web view and you can browse/download it as you do for usual PDF files.
If you then need to download that PDF (after it is loaded) you need to use a Fetch API as described here.

Body:
I've tried the link you've provided and it seems like the download button opens PDF in a new window (html tag ) and WKWebView just ignores it.

To make navigation possible you should adopt WKUIDelegate protocol in your view controller and implement a delegate method:

override func viewDidLoad() {
   super.viewDidLoad()
   self.webView.uiDelegate = self
}

func webView(_ webView: WKWebView, createWebViewWith configuration: WKWebViewConfiguration, for navigationAction: WKNavigationAction, windowFeatures: WKWindowFeatures) -> WKWebView? {
    if navigationAction.targetFrame == nil {
        // Here we load this request manually in current window
        webView.load(navigationAction.request)
    }
    return nil
}

In this example the PDF will be loaded directly into web view and you can browse/download it as you do for usual PDF files.
If you then need to download that PDF (after it is loaded) you need to use a Fetch API as described here.


问:
set `exclude_from_indexes` for Array datatype
I'm storing a list of strings using Array datatype in Datastore(e.g. ["name1", "name2", ...]). As the list grows, I find myself unable to upsert the entry.

INVALID_ARGUMENT: Too many indexed properties

According to https://cloud.google.com/datastore/docs/concepts/entities#array, even if I set the property to be exclude_from_indexes, it gets ignored. The datastore web UI also doesn't have an Index checkmark for me to uncheck.

So the only option I came up with is to convert the Array into a String type and parse to a JSON Object every time I read from DB, and write back stringified.

Was wondering if this is the right approach or if there are better ways to do this I'm not aware of.

Thanks

答: You should set the exclude_from_indexes on each value of the array.  That is what "For a property to be unindexed, the exclude_from_indexes field of Value must be set to true." means.</p>


问:
Fortran 90 producing the incorrect answer, produces 0 when the answer should be 1. Am I overlooking anything?
Here is the Fortran 90 code I have written. It is a function that I am using in a larger code but I am getting incorrect results.

I know mathematically the answer should be 1 (or close to 1 due to computation) but my answer result is 0.

Am I doing something wrong? Is there something that I do not know?

Here is the my code saved as test.f90 that I am compiling and running on windows gfortran:

```<code>program main
    implicit none

    real*8 :: y, t

    t = 0.0
    y = (1/3)*exp(5*t) + (2/3)*exp(-t) + t*t*exp(2*t)

    print*, 'y= ', y

end program main
</code>```

答:
fortran considers 1/3 and 2/3 to be equal to zero. you should add a point to your numbers:</p>

```<code>program main
implicit none

real*8 :: y, t

t = 0.0
y = (1./3.)*exp(5*t) + (2./3.)*exp(-t) + t*t*exp(2*t)

print*, 'y= ', y
</code>```

Body:
Here is the Fortran 90 code I have written. It is a function that I am using in a larger code but I am getting incorrect results.

I know mathematically the answer should be 1 (or close to 1 due to computation) but my answer result is 0.

Am I doing something wrong? Is there something that I do not know?

Here is the my code saved as test.f90 that I am compiling and running on windows gfortran:

program main
    implicit none

    real*8 :: y, t

    t = 0.0
    y = (1/3)*exp(5*t) + (2/3)*exp(-t) + t*t*exp(2*t)

    print*, 'y= ', y

end program main

Body:
fortran considers 1/3 and 2/3 to be equal to zero. you should add a point to your numbers:

program main
implicit none

real*8 :: y, t

t = 0.0
y = (1./3.)*exp(5*t) + (2./3.)*exp(-t) + t*t*exp(2*t)

print*, 'y= ', y


问:
How can I try Google Places API from my browser?
So I would like to try the API Google Places before put it in my code... wanna check out first if that is what I need.

https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=-33.8670522,151.1957362&radius=500&types=food&name=cruise&key=AddYourOwnKeyHere

So this is the link which im trying to test about, I am using my own key that I created from the console. I follow all the stepes but still im getting the error 'REQUEST_DENIED'.

Steps:
-Create my project.
-Select the Google Places Web Service Api and enabled it.
-Go to credentials, new API Key
-Browser key type
-And got it.

Any clues?

答:
It looks like there is no convenient UI for just querying it from the web. Instead, just consult the Places API documentation, and paste a query of the following style, for example, into your browser address bar.

https://maps.googleapis.com/maps/api/place/findplacefromtext/json?key=YOUR_API_KEY&inputtype=textquery&input=Starbucks


问:
How to make specific bit manipulation?
I'm doing practice of bit manipulation in arduino with a 74HC595 shift register.

I would like to create an algorithm that allows the binary digit to perform this way:

1 0 0 0 0 0 0 1

0 1 0 0 0 0 1 0

0 0 1 0 0 1 0 0

.

.

.

1 0 0 0 0 0 0 1

In this type of function the decimal values are: (129,66,36,24,24,36,66,129) and so on in a loop.

How can I perform this type of shifting? I don't have any fluency thinking this type of operation, I have only performed a circular shift with "an algorithm" like:

```<code>//my circular shift

myByte = myByte*128 + myByte/2
</code>```

But I don't know how to perform the output that I showed.

How can I do this? Thanks

答:
For example you can use the following approach

```<code>#include <iostream>
#include <iomanip>
#include <limits>

int main()
{
    unsigned char b = 0b10000001;
    int width = std::numeric_limits<unsigned char>::digits / 2;

    for ( int i = 0; i < width; i++ )
    {
            std::cout << std::hex << static_cast<int>( b ) << " - "
                      << std::dec << static_cast<int>( b ) << '\n';
            b = ( b & ( 0b1111 << width ) ) >> 1 | ( b & 0b1111 ) << 1;
    }

    for ( int i = 0; i < width; i++ )
    {
            std::cout << std::hex << static_cast<int>( b ) << " - "
                      << std::dec << static_cast<int>( b ) << '\n';
            b = ( b & ( 0b1111 << width ) ) << 1 | ( b & 0b1111 ) >> 1;
    }

    return 0;
}
</code>```

The program output is

```<code>81 - 129
42 - 66
24 - 36
18 - 24
18 - 24
24 - 36
42 - 66
81 - 129
</code>```

Title: How to make specific bit manipulation?

Body:
I'm doing practice of bit manipulation in arduino with a 74HC595 shift register.

I would like to create an algorithm that allows the binary digit to perform this way:

1 0 0 0 0 0 0 1

0 1 0 0 0 0 1 0

0 0 1 0 0 1 0 0

.

.

.

1 0 0 0 0 0 0 1

In this type of function the decimal values are: (129,66,36,24,24,36,66,129) and so on in a loop.

How can I perform this type of shifting? I don't have any fluency thinking this type of operation, I have only performed a circular shift with "an algorithm" like:

//my circular shift

myByte = myByte*128 + myByte/2

But I don't know how to perform the output that I showed.

How can I do this? Thanks

Body:
For example you can use the following approach

#include <iostream>
#include <iomanip>
#include <limits>

int main()
{
    unsigned char b = 0b10000001;
    int width = std::numeric_limits<unsigned char>::digits / 2;

    for ( int i = 0; i < width; i++ )
    {
            std::cout << std::hex << static_cast<int>( b ) << " - "
                      << std::dec << static_cast<int>( b ) << '\n';
            b = ( b & ( 0b1111 << width ) ) >> 1 | ( b & 0b1111 ) << 1;
    }

    for ( int i = 0; i < width; i++ )
    {
            std::cout << std::hex << static_cast<int>( b ) << " - "
                      << std::dec << static_cast<int>( b ) << '\n';
            b = ( b & ( 0b1111 << width ) ) << 1 | ( b & 0b1111 ) >> 1;
    }

    return 0;
}

The program output is

81 - 129
42 - 66
24 - 36
18 - 24
18 - 24
24 - 36
42 - 66
81 - 129


问:
Running Complex Samples in R?
I'm starting to use R more and would very much appreciate advice on how I would run a complex samples crosstab.

Here is the SPSS syntax:

```<code>CSTABULATE
 /PLAN FILE='D:\data\data2019.sav'
 /TABLES VARIABLES=income_b BY sex
 /CELLS POPSIZE COLPCT
 /STATISTICS SE CIN(95) DEFF COUNT
 /TEST ODDSRATIO INDEPENDENCE
 /MISSING SCOPE=TABLE CLASSMISSING=EXCLUDE.
</code>```

Any suggestions on how to do this in the R, please?

Many thanks.

答:
You can do it with the survey package. Specifically the svytable function. Here is an example from the package documentation

```<code>  data(api)
  xtabs(~sch.wide+stype, data=apipop)

  dclus1<-svydesign(id=~dnum, weights=~pw, data=apiclus1, fpc=~fpc)
  summary(dclus1)

  (tbl <- svytable(~sch.wide+stype, dclus1))
  svychisq(~sch.wide+stype, dclus1)
  summary(tbl, statistic="Chisq")
  svychisq(~sch.wide+stype, dclus1, statistic="adjWald")
</code>```

Title: Running Complex Samples in R?

Body:
I'm starting to use R more and would very much appreciate advice on how I would run a complex samples crosstab.

Here is the SPSS syntax:

CSTABULATE
 /PLAN FILE='D:\data\data2019.sav'
 /TABLES VARIABLES=income_b BY sex
 /CELLS POPSIZE COLPCT
 /STATISTICS SE CIN(95) DEFF COUNT
 /TEST ODDSRATIO INDEPENDENCE
 /MISSING SCOPE=TABLE CLASSMISSING=EXCLUDE.

Any suggestions on how to do this in the R, please?

Many thanks.

Body:
You can do it with the survey package. Specifically the svytable function. Here is an example from the package documentation

  data(api)
  xtabs(~sch.wide+stype, data=apipop)

  dclus1<-svydesign(id=~dnum, weights=~pw, data=apiclus1, fpc=~fpc)
  summary(dclus1)

  (tbl <- svytable(~sch.wide+stype, dclus1))
  svychisq(~sch.wide+stype, dclus1)
  summary(tbl, statistic="Chisq")
  svychisq(~sch.wide+stype, dclus1, statistic="adjWald")


问:
Using ctrl+d to end caesar cipher
I know there are a few similar questions already posted, but all the solutions I tried did not fix my code. So, my caesar cipher is working as intended. However, I want to be able to exit using ctrl+d, rather than ctrl+c. My code right now is:

```<code>int main (int argc, char *argv[]){
        char code[500], ch;
        int c, key;
        key = atoi(argv[1]);
        printf("%s",code);
        for(;;){
                fgets(code, 500, stdin);
                for(c = 0;code[c] != '\0'; ++c){
                        ch = code[c];
                        if(ch >= 'a' && ch <= 'z'){
                                ch = ch + key;
                                if(ch > 'z'){
                                        ch = ch - 26 ;
                                }
                                else if(ch < 'a'){
                                        ch = ch + 26;
                                }
                                code[c] = ch;
                        }
                        else if(ch >= 'A' && ch <= 'Z'){
                                ch = ch + key;
                                if(ch > 'Z'){
                                        ch = ch - 'Z' + 'A' - 1;
                                }
                                else if(ch < 'A'){
                                        ch = ch + 26;
                                }
                                code[c] = ch;
                        }
                }
                printf("%s\n", code);
        }
        return 0;
}
</code>```

When I compile it, run it, and type

```<code>./a.out 2
abc
</code>```

it returns "cde" and leaves the command line hanging so I can type another string.
However, when I press ctrl+d, it just reiterates the program (if I press ctrl+d after seeing cde, it will return efg), when I want it to exit the program when I press it.

One solution I found was to add a

```<code>if(code == EOF (or '\0' or NULL)) {
   break;
}
</code>```

Aside from warning me that there was point and integer comparison warning, none of them worked.
Does anyone know how to fix this?
Any help is greatly appreciated!

答: Your program isn't reading it directly when you type, your operating system reads everything first, and when it sees a Ctrl+C, it sends an interrupt to the program to stop what its doing.  In order to get this to work, you would have to go into the settings of whatever operating system you are running, and set that up as a hotkey. </p>

Title: Using ctrl+d to end caesar cipher

Body:
I know there are a few similar questions already posted, but all the solutions I tried did not fix my code. So, my caesar cipher is working as intended. However, I want to be able to exit using ctrl+d, rather than ctrl+c. My code right now is:

int main (int argc, char *argv[]){
        char code[500], ch;
        int c, key;
        key = atoi(argv[1]);
        printf("%s",code);
        for(;;){
                fgets(code, 500, stdin);
                for(c = 0;code[c] != '\0'; ++c){
                        ch = code[c];
                        if(ch >= 'a' && ch <= 'z'){
                                ch = ch + key;
                                if(ch > 'z'){
                                        ch = ch - 26 ;
                                }
                                else if(ch < 'a'){
                                        ch = ch + 26;
                                }
                                code[c] = ch;
                        }
                        else if(ch >= 'A' && ch <= 'Z'){
                                ch = ch + key;
                                if(ch > 'Z'){
                                        ch = ch - 'Z' + 'A' - 1;
                                }
                                else if(ch < 'A'){
                                        ch = ch + 26;
                                }
                                code[c] = ch;
                        }
                }
                printf("%s\n", code);
        }
        return 0;
}

When I compile it, run it, and type

./a.out 2
abc

it returns "cde" and leaves the command line hanging so I can type another string.
However, when I press ctrl+d, it just reiterates the program (if I press ctrl+d after seeing cde, it will return efg), when I want it to exit the program when I press it.

One solution I found was to add a

if(code == EOF (or '\0' or NULL)) {
   break;
}

Aside from warning me that there was point and integer comparison warning, none of them worked.
Does anyone know how to fix this?
Any help is greatly appreciated!


问:
twitter4s: how to return future from Action.async in play framework
i am using twitter4s and play-framework-2.4.3

i am fetching tweets sending to the actor for performing some processing on it and the actor needs to send back the response back to the controller Action
here is my code

```<code>def totalTweetCount = Action.async {
    log.debug("in the action tofaltweets")
            def getTweet: PartialFunction[StreamingMessage, Unit] = {
      case tweet: Tweet =>
        future = ask(myActor, TotalNumberOfTweets(tweet)).mapTo[Int]
    }
    val streaming: Future[TwitterStream] = streamingClient.sampleStatuses(stall_warnings = true)(getTweet)
}

class MyActor extends Actor {
//sends back the response to the calling code
}
</code>```

now the problem is below line runs continuously (its the twitter stream) and call's getTweet method continuously and send the tweet object to the actor

```<code>val streaming: Future[TwitterStream] = streamingClient.sampleStatuses(stall_warnings = true)(getTweet)
</code>```

i want to fetch the actor response and display it in Ok block of my Action
when i do something like this i got NullPointerException

```<code>def totalTweetCount = Action.async {
    log.debug("in the action tofaltweets")

      def getTweet: PartialFunction[StreamingMessage, Unit] = {
          case tweet: Tweet =>
            var future: Future[Int] = null
            future = ask(myActor, TotalNumberOfTweets(tweet)).mapTo[Int]

        }
        val streaming: Future[TwitterStream] = streamingClient.sampleStatuses(stall_warnings = true)(getTweet)
    future.map {
              result =>
                Ok("Total number of tweets" + result)
            }
      }
</code>```

if i do this
  def totalTweetCount = Action.async {
    log.debug("in the action tofaltweets")

```<code>def getTweet: PartialFunction[StreamingMessage, Unit] = {
  case tweet: Tweet =>
    var future: Future[Int] = null
    future = ask(actorManager, TotalNumberOfTweets(tweet)).mapTo[Int]
    future.map {
      result =>
        Ok("Total number of tweets" + result)
    }
}
val streaming: Future[TwitterStream] = streamingClient.sampleStatuses(stall_warnings = true)(getTweet)
</code>```

}
its also wrong
so what should be the right approach

答:
I'm not sure what you're trying to do here, but here it goes:

In all solutions, you're calling the streamingClient.sampleStatuses method inside your controller, which doesn't make a lot of sense, since that is a streaming method. Reading twitter4s docs, it seems they have an asynchronous approach for getting tweets.

Now, if what you're trying to do is to receive tweets, store them and them getting the total amount in a separate method, you should:

Call streamingClient.sampleStatuses inside your main method and send the incoming tweet to your actor

streamingClient.sampleStatuses(stall_warnings = true) {
  case t: Tweet => tweetsActor ! t
}
```

<p>That will send all tweet data to your actor class. Supposing your actor's implementations will be something like</p>

<pre class="lang-scala prettyprint-override"><code>class Tweets extends Actor {
  var tweets = ListBuffer[Tweet]()

  def receive = {
    case t: Tweet => tweets += t
    case TotalTweetCount = sender() ! tweets.length
  }
}
</code>```

Your controller method will look like this:

import akka.pattern.ask_

def totalTweetCount = Action.async {
  (tweetActor ? TotalTweetCount).mapTo[Int]
}
```

That should do the trick.

Body:
i am using twitter4s and play-framework-2.4.3

i am fetching tweets sending to the actor for performing some processing on it and the actor needs to send back the response back to the controller Action
here is my code

def totalTweetCount = Action.async {
    log.debug("in the action tofaltweets")
            def getTweet: PartialFunction[StreamingMessage, Unit] = {
      case tweet: Tweet =>
        future = ask(myActor, TotalNumberOfTweets(tweet)).mapTo[Int]
    }
    val streaming: Future[TwitterStream] = streamingClient.sampleStatuses(stall_warnings = true)(getTweet)
}

class MyActor extends Actor {
//sends back the response to the calling code
}

now the problem is below line runs continuously (its the twitter stream) and call's getTweet method continuously and send the tweet object to the actor

val streaming: Future[TwitterStream] = streamingClient.sampleStatuses(stall_warnings = true)(getTweet)

i want to fetch the actor response and display it in Ok block of my Action
when i do something like this i got NullPointerException

def totalTweetCount = Action.async {
    log.debug("in the action tofaltweets")

      def getTweet: PartialFunction[StreamingMessage, Unit] = {
          case tweet: Tweet =>
            var future: Future[Int] = null
            future = ask(myActor, TotalNumberOfTweets(tweet)).mapTo[Int]

        }
        val streaming: Future[TwitterStream] = streamingClient.sampleStatuses(stall_warnings = true)(getTweet)
    future.map {
              result =>
                Ok("Total number of tweets" + result)
            }
      }

if i do this
  def totalTweetCount = Action.async {
    log.debug("in the action tofaltweets")

def getTweet: PartialFunction[StreamingMessage, Unit] = {
  case tweet: Tweet =>
    var future: Future[Int] = null
    future = ask(actorManager, TotalNumberOfTweets(tweet)).mapTo[Int]
    future.map {
      result =>
        Ok("Total number of tweets" + result)
    }
}
val streaming: Future[TwitterStream] = streamingClient.sampleStatuses(stall_warnings = true)(getTweet)

}
its also wrong
so what should be the right approach

Body:
I'm not sure what you're trying to do here, but here it goes:

In all solutions, you're calling the streamingClient.sampleStatuses method inside your controller, which doesn't make a lot of sense, since that is a streaming method. Reading twitter4s docs, it seems they have an asynchronous approach for getting tweets.

Now, if what you're trying to do is to receive tweets, store them and them getting the total amount in a separate method, you should:

Call streamingClient.sampleStatuses inside your main method and send the incoming tweet to your actor

streamingClient.sampleStatuses(stall_warnings = true) {
  case t: Tweet => tweetsActor ! t
}

That will send all tweet data to your actor class. Supposing your actor's implementations will be something like

class Tweets extends Actor {
  var tweets = ListBuffer[Tweet]()

  def receive = {
    case t: Tweet => tweets += t
    case TotalTweetCount = sender() ! tweets.length
  }
}

Your controller method will look like this:

import akka.pattern.ask_

def totalTweetCount = Action.async {
  (tweetActor ? TotalTweetCount).mapTo[Int]
}

That should do the trick.


问:
check if argument is a valid date in bash shell
I am writing a bash shell script in Linux, this program will accept a date (mm-dd-yyyy) as a parameter. I am wondering if there is a simply way to check if the date is valid? is there an operator and I can just use test to check?</p>

答:
The date command will parse a date given with the -d argument.  If the date is invalid, an error message is printed to STDERR and date exits with an error status.   If the date is valid, it prints the date on STDOUT and exits with a success status.

Because of this, date -d "$date" can be used directly in a bash if statement.

The first wrinkle is that to prevent printing a message for valid dates, you need to redirect STDOUT to /dev/null using >/dev/null.

The second wrinkle is that date accepts an empty string as a valid date without complaint. In most cases, that should mean that your user didn't enter a date when they should have.  You will want to test for an empty date separately using the test [ "z$date" != "z" ]

date also accepts a variety of formats.  If you are using actual bash (as opposed to dash or some of ther sh variety, you could use regular expressions against your preferred format in place of a simple check for an empty string.  For example to check my preferred ISO format, I would use:  [[ "$date" =~ ^[0-9]{4}-[0-9]{2}-[0-9]{2}$ ]]

```<code>date=2001-01-01
if [ "z$date" != "z" ] && date -d "$date" >/dev/null
then
  echo "VALID DATE"
fi
</code>```

If you try this with an invalid date (such as 2001-01-53), it doesn't get into the if and it prints out:

date: invalid date ‘2001-01-53’

Alternately, you could check if the date is invalid and exit:

```<code>date=2001-01-01
if [ "z$date" == "z" ]
then
  echo "No date specified"
  exit 1
fi
if ! [[ "$date" =~ ^[0-9]{4}-[0-9]{2}-[0-9]{2}$ ]]
then
  echo "Expected date in YYYY-MM-DD format"
  exit 1
fi
if ! date -d "$date" >/dev/null
then
  exit 1
fi
echo "VALID DATE"
</code>```

Body:
The date command will parse a date given with the -d argument.  If the date is invalid, an error message is printed to STDERR and date exits with an error status.   If the date is valid, it prints the date on STDOUT and exits with a success status.

Because of this, date -d "$date" can be used directly in a bash if statement.

The first wrinkle is that to prevent printing a message for valid dates, you need to redirect STDOUT to /dev/null using >/dev/null.

The second wrinkle is that date accepts an empty string as a valid date without complaint. In most cases, that should mean that your user didn't enter a date when they should have.  You will want to test for an empty date separately using the test [ "z$date" != "z" ]

date also accepts a variety of formats.  If you are using actual bash (as opposed to dash or some of ther sh variety, you could use regular expressions against your preferred format in place of a simple check for an empty string.  For example to check my preferred ISO format, I would use:  [[ "$date" =~ ^[0-9]{4}-[0-9]{2}-[0-9]{2}$ ]]

date=2001-01-01
if [ "z$date" != "z" ] && date -d "$date" >/dev/null
then
  echo "VALID DATE"
fi

If you try this with an invalid date (such as 2001-01-53), it doesn't get into the if and it prints out:

date: invalid date ‘2001-01-53’

Alternately, you could check if the date is invalid and exit:

date=2001-01-01
if [ "z$date" == "z" ]
then
  echo "No date specified"
  exit 1
fi
if ! [[ "$date" =~ ^[0-9]{4}-[0-9]{2}-[0-9]{2}$ ]]
then
  echo "Expected date in YYYY-MM-DD format"
  exit 1
fi
if ! date -d "$date" >/dev/null
then
  exit 1
fi
echo "VALID DATE"


问:
Python - Array of Indexes of all appearances of a certain element in an array
This question is very similar to this question, Question, except for the fact that I need an answer for Python.

I'll explain the question anyway. If I have an array of characters, for example ["a", "b", "a", "c"], then it needs to return an array that includes the indexes of all the appearances of a certain character.

This means that if I input ['a', 'b', 'a', 'c', 'c', 'a'], and I need to find all appearances of 'a', then it would output [0, 2, 5].

I also need the program to be pretty fast, as I need to mass generate my final product, so the whole program needs to be quick. I will probably be running this piece of code millions of times in my code so the quicker it is the better, but I am accepting anything right now.

Right now my code does not work since it simply output [0, 0, 0] (I am running through a for loop so it isn't fast either)

Could someone please help? Thanks!

Body:
Just use the np.where function.

>>> l=np.array(['a','b','a','c','c','a'])
>>> np.where(l=='a')
(array([0, 2, 5]),)


问:
How do I get odd and even values in a Django for loop template?
I have this code

```<code>{% for o in some_list %}
</code>```

Now I want to do some stuff if I am on an even line. How can I do that?

答:
```<code><div class="row">
{% for post in posts %}
   {% if loop.index is divisibleby 2 %}
        <div class="col-md-6">Even posts</div>
      {% else %}
        <div class="col-md-6">Odd posts</div>
      {% endif %}
    {% endfor %}
</div>
</code>```

http://mitsuhiko.pocoo.org/jinja2docs/html/templates.html#id3

Body:
I have this code

{% for o in some_list %}

Now I want to do some stuff if I am on an even line. How can I do that?

Body:
<div class="row">
{% for post in posts %}
   {% if loop.index is divisibleby 2 %}
        <div class="col-md-6">Even posts</div>
      {% else %}
        <div class="col-md-6">Odd posts</div>
      {% endif %}
    {% endfor %}
</div>

http://mitsuhiko.pocoo.org/jinja2docs/html/templates.html#id3


问:
java exception handling in constructor
honestly I'm not very experienced with exception handling, because often for my laziness I tend to not handle exceptions. So here's a very basic question.

I would like to know what's the cleanest way to accomplish this situation, with an exception handling approach:

I have a class (ConfigManager) that  reads a file within its constructor, and need that file to exists to be constructed correctly, given as the constructor parameter.
If the file doesn't exist, I would like to catch the FileNotFoundException, create the file with some defaults values, and continue the creation of the ConfigManager object with the default config file now available.

Here's some code:

```<code>class ConfigManager{
    ConfigManager(String file){
         try{
             builder = builderFactory.newDocumentBuilder();
             document = builder.parse (new FileInputStream(file));
             ....
         }catch (FileNotFoundException e) {

        File configFile =  new File (file);

        try {

            configFile.createNewFile();
            BufferedWriter writer = new BufferedWriter(new FileWriter(configFile));
            writer.write(this.defaultConfig);
            writer.close();

            return new ConfigManager(string); //Here's the problem. I can't do that but I need to try build ConfigManager again. How do that?

        } catch (IOException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }
    }
}
</code>```

How to construct a new ConfigManager object, after the default config file has been created?
Is that the rigth way to handle such type of exception?

thanks in advance

答:
often for my laziness I tend to not
  handle exceptions

I suggest you fix the laziness first. In reality you are just creating more work for yourself further down the line.

Title: java exception handling in constructor

Body:
honestly I'm not very experienced with exception handling, because often for my laziness I tend to not handle exceptions. So here's a very basic question.

I would like to know what's the cleanest way to accomplish this situation, with an exception handling approach:

I have a class (ConfigManager) that  reads a file within its constructor, and need that file to exists to be constructed correctly, given as the constructor parameter.
If the file doesn't exist, I would like to catch the FileNotFoundException, create the file with some defaults values, and continue the creation of the ConfigManager object with the default config file now available.

Here's some code:

class ConfigManager{
    ConfigManager(String file){
         try{
             builder = builderFactory.newDocumentBuilder();
             document = builder.parse (new FileInputStream(file));
             ....
         }catch (FileNotFoundException e) {

        File configFile =  new File (file);

        try {

            configFile.createNewFile();
            BufferedWriter writer = new BufferedWriter(new FileWriter(configFile));
            writer.write(this.defaultConfig);
            writer.close();

            return new ConfigManager(string); //Here's the problem. I can't do that but I need to try build ConfigManager again. How do that?

        } catch (IOException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }
    }
}

How to construct a new ConfigManager object, after the default config file has been created?
Is that the rigth way to handle such type of exception?

thanks in advance


问:
Eclipse: Junit I am seeing this error in junit tab below
Below is my simple code

```<code>package M06;

    public class ExerciseE03 {

        public double calcTotal (double total, boolean existingMember, boolean validDiscount, boolean validCoupon) {

            double discount=0.0;

            if (existingMember && validDiscount || validCoupon) {
                if (total > 1_000.0)
                    discount = 0.15;
                else
                    if (total >= 750)
                        discount = 0.1;
                    else
                        if (total > 500)
                            discount = 0.05;
                        else
                            discount = 0.025;
            }
            return (total * (1-discount) * 1.0825);
        }
    }
</code>```

and this is the j unit file

```<code>package M06;

import static org.junit.Assert.*;
import static junitparams.JUnitParamsRunner.$;
import org.junit.Before;
import org.junit.Test;

import junitparams.FileParameters;

public class ExerciseE03Test {
    private ExerciseE03 object;

    @Before
    public void setUp() throws Exception {
        object = new ExerciseE03();
    }

    @Test
    @FileParameters("src/M06/E03TestCaseTable.csv")
    public void test(int testcaseNumber, boolean member, boolean disc, boolean coupon, double total, double discount, double output) {
        //ExerciseE03 object = new ExerciseE03();
        //assertEquals(1380.1875, object.calcTotal(1500, true, true, true),0.001);
        object.calcTotal( total, member, disc, coupon);
        assertEquals(output,object.calcTotal(total, member, disc, coupon),0.01);
    }

}
</code>```

I am also providing my junit screenshot below. since i am new to juint, i don't know what are steps to be taken for this type of error

Above is the error that i can see in my junit tab below.

答:
Use the @RunWith(JUnitParamsRunner.class) annotation on the top of your test class, ExerciseE03Test.

```<code>@RunWith(JUnitParamsRunner.class)
public class ExerciseE03Test {
</code>```

Check this post to learn more.

Body:
Below is my simple code

package M06;

    public class ExerciseE03 {

        public double calcTotal (double total, boolean existingMember, boolean validDiscount, boolean validCoupon) {

            double discount=0.0;

            if (existingMember && validDiscount || validCoupon) {
                if (total > 1_000.0)
                    discount = 0.15;
                else
                    if (total >= 750)
                        discount = 0.1;
                    else
                        if (total > 500)
                            discount = 0.05;
                        else
                            discount = 0.025;
            }
            return (total * (1-discount) * 1.0825);
        }
    }

and this is the j unit file

package M06;

import static org.junit.Assert.*;
import static junitparams.JUnitParamsRunner.$;
import org.junit.Before;
import org.junit.Test;

import junitparams.FileParameters;

public class ExerciseE03Test {
    private ExerciseE03 object;

    @Before
    public void setUp() throws Exception {
        object = new ExerciseE03();
    }

    @Test
    @FileParameters("src/M06/E03TestCaseTable.csv")
    public void test(int testcaseNumber, boolean member, boolean disc, boolean coupon, double total, double discount, double output) {
        //ExerciseE03 object = new ExerciseE03();
        //assertEquals(1380.1875, object.calcTotal(1500, true, true, true),0.001);
        object.calcTotal( total, member, disc, coupon);
        assertEquals(output,object.calcTotal(total, member, disc, coupon),0.01);
    }

}

I am also providing my junit screenshot below. since i am new to juint, i don't know what are steps to be taken for this type of error

Above is the error that i can see in my junit tab below.

Body:
Use the @RunWith(JUnitParamsRunner.class) annotation on the top of your test class, ExerciseE03Test.

@RunWith(JUnitParamsRunner.class)
public class ExerciseE03Test {

Check this post to learn more.


问:
django-allauth accounts/signup gets [WinError 10061] No connection could be made because the target machine actively refused it
I know that there are a lot of answers to this issue say that I should probably try running my server on another port like so: python manage.py runserver 0.0.0.0:8080  I have tried that didn't fix it.  I have turned off my windows Norton firewall:

I have started PyCharm as administrator.   The thing that make me think these solutions were not going to work for me was that other API endpoints work fine:  http://localhost:8000/accounts/login/ works and http://localhost:8000/accounts/logout/ works too.  But when I fill out the form and POST my data to http://localhost:8000/accounts/signup I get this error:

```<code>OSError at /accounts/signup/
[WinError 10013] An attempt was made to access a socket in a way forbidden by its access permissions
Request Method: POST
Request URL:    http://127.0.0.1:8000/accounts/signup/
Django Version: 2.2.7
Exception Type: OSError
Exception Value:
[WinError 10013] An attempt was made to access a socket in a way forbidden by its access permissions
</code>```

Can someone please tell me what I am missing here?

答:
Encountered the same issue with an identical setup.
Apparently has something to do with sending a confirmation email.
Turning off email verification fixed the problem for me:</p>

```<code># settings.py
ACCOUNT_EMAIL_VERIFICATION = "none"
</code>```

Body:
I know that there are a lot of answers to this issue say that I should probably try running my server on another port like so: python manage.py runserver 0.0.0.0:8080  I have tried that didn't fix it.  I have turned off my windows Norton firewall:

I have started PyCharm as administrator.   The thing that make me think these solutions were not going to work for me was that other API endpoints work fine:  http://localhost:8000/accounts/login/ works and http://localhost:8000/accounts/logout/ works too.  But when I fill out the form and POST my data to http://localhost:8000/accounts/signup I get this error:

OSError at /accounts/signup/
[WinError 10013] An attempt was made to access a socket in a way forbidden by its access permissions
Request Method: POST
Request URL:    http://127.0.0.1:8000/accounts/signup/
Django Version: 2.2.7
Exception Type: OSError
Exception Value:
[WinError 10013] An attempt was made to access a socket in a way forbidden by its access permissions

Can someone please tell me what I am missing here?

Body:
Encountered the same issue with an identical setup.
Apparently has something to do with sending a confirmation email.
Turning off email verification fixed the problem for me:

# settings.py
ACCOUNT_EMAIL_VERIFICATION = "none"


问:
how to automatically update ical events (Rails) daily
I am working on a website where users can subscribe via webcal to a calendar feed.
The events change daily. When events get updated/deleted/created this should be synced on the users local calendar accordingly.

If the user chooses to automatically update every day on the calendar app, I understand that the calendar app will periodically poll the calendar's URL to check for updates.

How does this exactly work on a technical level?

Code (Rails):

Controller:

```<code>respond_to do |format|
      format.html
      format.ics do
        cal = Icalendar::Calendar.new
        cal.x_wr_calname = 'My Calendar'
        events.each do |event|
        cal.event do |e|
            e.dtstart     = event.start_time
            e.dtend       = event.end_time
            e.summary     = "Calendar #{Area.where(area_code: events.first.area_code).first.name}"
            e.description = "placeholder"
         end
        end
        cal.publish
        render plain: cal.to_ical
      end
    end
</code>```

and in the html

```<code>    <button class="btn-subscribe">
        <%= link_to 'SUBSCRIBE TO ICAL', area_show_url(protocol: :webcal, format: :ics, id: Area.find(@selected_area.id)) %>
      </button>
</code>```

thanks for you help and time

答:
How it works:

Your website puts up a calendar feed (basically a .ics text/calendar file possibly produced in real time from latest data, no caching).  Hopefully this file contains valid RFC5545 data and thus shows any event updates as specified in https://www.rfc-editor.org/rfc/rfc5545 (Using UID and SEQUENCE and LAST-MODIFIED for each VEVENT modification)

Subscribing applications will check for any updates as and when suits them, as defined by their own algorithims.  They parse the .ics file and process the RFC5545 event definitions and update their systems accordingly.

Body:
I am working on a website where users can subscribe via webcal to a calendar feed.
The events change daily. When events get updated/deleted/created this should be synced on the users local calendar accordingly.

If the user chooses to automatically update every day on the calendar app, I understand that the calendar app will periodically poll the calendar's URL to check for updates.

How does this exactly work on a technical level?

Code (Rails):

Controller:

respond_to do |format|
      format.html
      format.ics do
        cal = Icalendar::Calendar.new
        cal.x_wr_calname = 'My Calendar'
        events.each do |event|
        cal.event do |e|
            e.dtstart     = event.start_time
            e.dtend       = event.end_time
            e.summary     = "Calendar #{Area.where(area_code: events.first.area_code).first.name}"
            e.description = "placeholder"
         end
        end
        cal.publish
        render plain: cal.to_ical
      end
    end

and in the html

    <button class="btn-subscribe">
        <%= link_to 'SUBSCRIBE TO ICAL', area_show_url(protocol: :webcal, format: :ics, id: Area.find(@selected_area.id)) %>
      </button>

thanks for you help and time


问:
How to base64 encode and decode a column in python pandas?
I read this post

encoding a dataframe

but I do not want to encrypt the dataframe, just convert it to base 64. I import a carriage return delimited list of words into a dataframe with:

```<code>words = pd.read_table("sampleText.txt",names=['word'], header=None)
words.head()
</code>```

that gives

```<code>    word
0   difference
1   where
2   mc
3   is
4   the
</code>```

then

```<code>words['words_encoded'] = map(lambda x: x.encode('base64','strict'), words['word'])
print (words)
</code>```

gave

```<code>                word                   words_encoded
0         difference  <map object at 0x7fad3e89e410>
1              where  <map object at 0x7fad3e89e410>
2                 mc  <map object at 0x7fad3e89e410>
3                 is  <map object at 0x7fad3e89e410>
4                the  <map object at 0x7fad3e89e410>
...              ...                             ...
999995  distribution  <map object at 0x7fad3e89e410>
999996            in  <map object at 0x7fad3e89e410>
999997      scenario  <map object at 0x7fad3e89e410>
999998          less  <map object at 0x7fad3e89e410>
999999          land  <map object at 0x7fad3e89e410>

[1000000 rows x 2 columns]
</code>```

I dont understand why my encoded column refers to a map object and not the actual data so I tried:

```<code>b64words = words.word.str.encode('base64')
print(b64words)
</code>```

gives

```<code>0        NaN
1        NaN
2        NaN
3        NaN
4        NaN
          ..
999995   NaN
999996   NaN
999997   NaN
999998   NaN
999999   NaN
Name: word, Length: 1000000, dtype: float64
</code>```

Well,

That threw me so I read the linked answer above and tried

```<code>import base64
def encode(text):
    return base64.b64encode(text)
words['Encoded_Column'] = [encode(x) for x in words]
</code>```

but got

```<code>---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-89-8cf5a6f1f3a9> in <module>
      2 def encode(text):
      3     return base64.b64encode(text)
----> 4 words['Encoded_Column'] = [encode(x) for x in words]

<ipython-input-89-8cf5a6f1f3a9> in <listcomp>(.0)
      2 def encode(text):
      3     return base64.b64encode(text)
----> 4 words['Encoded_Column'] = [encode(x) for x in words]

<ipython-input-89-8cf5a6f1f3a9> in encode(text)
      1 import base64
      2 def encode(text):
----> 3     return base64.b64encode(text)
      4 words['Encoded_Column'] = [encode(x) for x in words]

~/miniconda3/envs/p37cu10.2PyTo/lib/python3.7/base64.py in b64encode(s, altchars)
     56     application to e.g. generate url or filesystem safe Base64 strings.
     57     """
---> 58     encoded = binascii.b2a_base64(s, newline=False)
     59     if altchars is not None:
     60         assert len(altchars) == 2, repr(altchars)

TypeError: a bytes-like object is required, not 'str'
</code>```

so I tried converting to a bytes like object like so:

```<code>import base64
def encode(text):
    btext = text.str.encode('utf-8')
    return base64.b64encode(btext)
words['Encoded_Column'] = [encode(x) for x in words]
</code>```

but got

```<code>---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-90-46db6d3688ba> in <module>
      3     btext = text.str.encode('utf-8')
      4     return base64.b64encode(btext)
----> 5 words['Encoded_Column'] = [encode(x) for x in words]

<ipython-input-90-46db6d3688ba> in <listcomp>(.0)
      3     btext = text.str.encode('utf-8')
      4     return base64.b64encode(btext)
----> 5 words['Encoded_Column'] = [encode(x) for x in words]

<ipython-input-90-46db6d3688ba> in encode(text)
      1 import base64
      2 def encode(text):
----> 3     btext = text.str.encode('utf-8')
      4     return base64.b64encode(btext)
      5 words['Encoded_Column'] = [encode(x) for x in words]

AttributeError: 'str' object has no attribute 'str'
</code>```

in this C example they are also converting first to byte strings and then to base64 like but I cannot do this simple task in Python.I am falling down this rabbit hole and every attempt just gets me deeper. I really appreciate any help that a clear minded person can give.

答:
Simply delete .str from function body.
True code:

```<code>import base64

def encode(text):
    btext = text.encode('utf-8')
    return base64.b64encode(btext)

words = {'1': 1, '2': 2, '3': 3, 'asdasd': 4}
words['Encoded_Column'] = [encode(x) for x in words]
print(words)
</code>```

It's output is:

```<code>{'1': 1, '2': 2, '3': 3, 'asdasd': 4, 'Encoded_Column': [b'MQ==', b'Mg==', b'Mw==', b'YXNkYXNk']}
</code>```

Body:
I read this post

encoding a dataframe

but I do not want to encrypt the dataframe, just convert it to base 64. I import a carriage return delimited list of words into a dataframe with:

words = pd.read_table("sampleText.txt",names=['word'], header=None)
words.head()

that gives

    word
0   difference
1   where
2   mc
3   is
4   the

then

words['words_encoded'] = map(lambda x: x.encode('base64','strict'), words['word'])
print (words)

gave

                word                   words_encoded
0         difference  <map object at 0x7fad3e89e410>
1              where  <map object at 0x7fad3e89e410>
2                 mc  <map object at 0x7fad3e89e410>
3                 is  <map object at 0x7fad3e89e410>
4                the  <map object at 0x7fad3e89e410>
...              ...                             ...
999995  distribution  <map object at 0x7fad3e89e410>
999996            in  <map object at 0x7fad3e89e410>
999997      scenario  <map object at 0x7fad3e89e410>
999998          less  <map object at 0x7fad3e89e410>
999999          land  <map object at 0x7fad3e89e410>

[1000000 rows x 2 columns]

I dont understand why my encoded column refers to a map object and not the actual data so I tried:

b64words = words.word.str.encode('base64')
print(b64words)

gives

0        NaN
1        NaN
2        NaN
3        NaN
4        NaN
          ..
999995   NaN
999996   NaN
999997   NaN
999998   NaN
999999   NaN
Name: word, Length: 1000000, dtype: float64

Well,

That threw me so I read the linked answer above and tried

import base64
def encode(text):
    return base64.b64encode(text)
words['Encoded_Column'] = [encode(x) for x in words]

but got

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-89-8cf5a6f1f3a9> in <module>
      2 def encode(text):
      3     return base64.b64encode(text)
----> 4 words['Encoded_Column'] = [encode(x) for x in words]

<ipython-input-89-8cf5a6f1f3a9> in <listcomp>(.0)
      2 def encode(text):
      3     return base64.b64encode(text)
----> 4 words['Encoded_Column'] = [encode(x) for x in words]

<ipython-input-89-8cf5a6f1f3a9> in encode(text)
      1 import base64
      2 def encode(text):
----> 3     return base64.b64encode(text)
      4 words['Encoded_Column'] = [encode(x) for x in words]

~/miniconda3/envs/p37cu10.2PyTo/lib/python3.7/base64.py in b64encode(s, altchars)
     56     application to e.g. generate url or filesystem safe Base64 strings.
     57     """
---> 58     encoded = binascii.b2a_base64(s, newline=False)
     59     if altchars is not None:
     60         assert len(altchars) == 2, repr(altchars)

TypeError: a bytes-like object is required, not 'str'

so I tried converting to a bytes like object like so:

import base64
def encode(text):
    btext = text.str.encode('utf-8')
    return base64.b64encode(btext)
words['Encoded_Column'] = [encode(x) for x in words]

but got

---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-90-46db6d3688ba> in <module>
      3     btext = text.str.encode('utf-8')
      4     return base64.b64encode(btext)
----> 5 words['Encoded_Column'] = [encode(x) for x in words]

<ipython-input-90-46db6d3688ba> in <listcomp>(.0)
      3     btext = text.str.encode('utf-8')
      4     return base64.b64encode(btext)
----> 5 words['Encoded_Column'] = [encode(x) for x in words]

<ipython-input-90-46db6d3688ba> in encode(text)
      1 import base64
      2 def encode(text):
----> 3     btext = text.str.encode('utf-8')
      4     return base64.b64encode(btext)
      5 words['Encoded_Column'] = [encode(x) for x in words]

AttributeError: 'str' object has no attribute 'str'

in this C example they are also converting first to byte strings and then to base64 like but I cannot do this simple task in Python.I am falling down this rabbit hole and every attempt just gets me deeper. I really appreciate any help that a clear minded person can give.

Body:
Simply delete .str from function body.
True code:

import base64

def encode(text):
    btext = text.encode('utf-8')
    return base64.b64encode(btext)

words = {'1': 1, '2': 2, '3': 3, 'asdasd': 4}
words['Encoded_Column'] = [encode(x) for x in words]
print(words)

It's output is:

{'1': 1, '2': 2, '3': 3, 'asdasd': 4, 'Encoded_Column': [b'MQ==', b'Mg==', b'Mw==', b'YXNkYXNk']}