问:
Unable to install Firebase for iOS xCode project
I follow the official video of Google and other videos on youtube but I am not able to install firebase SDK through cocoa-pods. Bundle Identifier and everything is correct.
Error is :
*### Error</p>

```<code>JSON::ParserError - 767: unexpected token at ''*
――― TEMPLATE END ――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――
[!] Oh no, an error occurred.
I have attached my pod file content.

> # Uncomment the next line to define a global platform for your project platform :ios, '9.0'
>
>     target 'FirebaseCrash' do
>       # Comment the next line if you don't want to use dynamic frameworks
>       use_frameworks!
>
>       # Pods for FirebaseCrash
>
>      pod 'Firebase/Auth'
>      pod 'Firebase/Firestore'
>      end

</code>```

答:
rm -rf ~/.cocoapods/repos and upgrade to CocoaPods 1.9.2 to prevent recurrence

Details at https://github.com/CocoaPods/CocoaPods/issues/9672

Body:
I follow the official video of Google and other videos on youtube but I am not able to install firebase SDK through cocoa-pods. Bundle Identifier and everything is correct.
Error is :
*### Error

JSON::ParserError - 767: unexpected token at ''*
――― TEMPLATE END ――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――
[!] Oh no, an error occurred.
I have attached my pod file content.

> # Uncomment the next line to define a global platform for your project platform :ios, '9.0'
>
>     target 'FirebaseCrash' do
>       # Comment the next line if you don't want to use dynamic frameworks
>       use_frameworks!
>
>       # Pods for FirebaseCrash
>
>      pod 'Firebase/Auth'
>      pod 'Firebase/Firestore'
>      end


来源: stackexchange

问:
Why am i getting an exception at dynamic_cast after filling object with zeros using memset
I am getting this weird runtime exception with dynamic_cast, but only if i fill the the object i'm casting with zeros using memset, or just copying some data into it with memcpy . Here's an example that generates the exception.

```<code>class Base
{
public:
    virtual void func() { }
};

class Derived : public Base
{
public:
    void func() override { }
};

int main()
{
    Derived derived;
    Base* base_ptr = &derived;
    memset(base_ptr, 0, sizeof(Derived));

    Derived* derived_ptr = dynamic_cast<Derived*>(base_ptr);
}
</code>```

And the exception message is:

I get the same exception if i copy one Derived object to another using memcpy.
Anyone got any idea whats going on, is it messing up the RTTI that dynamic_cast uses?

I am making a Game Engine and in it is a entity component system, and at one point in the program i load all the Objects and their components from a file. The way i implemented different components is using inheritance (each component derives from one base component). When i load the objects, and its components i cant just allocate the amount of memory that the component takes, i have to use new component name, because only then dynamic_cast works.

I am using Visual Studio 2019.

答:
Your code has undefined behavior.  memset requires that the object that it is setting be TriviallyCopyable, which yours is not because it has virtual functions.

The consequence of this is that you are overwriting the data in the class that the compiler uses for polymorphism and as such it can't resolve the cast as that information is now garbage.

ContentLicense: CC BY-SA 4.0

Body:
I am getting this weird runtime exception with dynamic_cast, but only if i fill the the object i'm casting with zeros using memset, or just copying some data into it with memcpy . Here's an example that generates the exception.

class Base
{
public:
    virtual void func() { }
};

class Derived : public Base
{
public:
    void func() override { }
};

int main()
{
    Derived derived;
    Base* base_ptr = &derived;
    memset(base_ptr, 0, sizeof(Derived));

    Derived* derived_ptr = dynamic_cast<Derived*>(base_ptr);
}

And the exception message is:

I get the same exception if i copy one Derived object to another using memcpy.
Anyone got any idea whats going on, is it messing up the RTTI that dynamic_cast uses?

I am making a Game Engine and in it is a entity component system, and at one point in the program i load all the Objects and their components from a file. The way i implemented different components is using inheritance (each component derives from one base component). When i load the objects, and its components i cant just allocate the amount of memory that the component takes, i have to use new component name, because only then dynamic_cast works.

I am using Visual Studio 2019.


问:
Scientific Computing Library on iOS/Objective C
I'm thinking of developing something on the iOS platform that would require some scientific libraries, for tasks such as solving roots for cubic/quartic polynomials, numerical root finding, optimization, etc. I'm wondering if people would know any good libraries that's compatible with iOS/Apple App Store.

I've tried to google around to no avail. GNU's Scientific Computing Library comes to mind, but too bad their licensing is not allowed on the app store...

Thanks!

答:
did you tried digging in Accelerate Framework?

http://developer.apple.com/library/ios/#documentation/Miscellaneous/Conceptual/iPhoneOSTechOverview/CoreOSLayer/CoreOSLayer.html

ContentLicense: CC BY-SA 3.0


问:
React Native capture video using camera as abackground service in app
I need to know if there is a way to capture the video recording using front camera of the phone while using an application. Camera should not be opened in the application UI.

Framework - React Native

答:
You can render the camera, but hiding the <View> and <RNCamera>.

I made this code to achieve it:

import React, { Component } from 'react';
import { StyleSheet, View } from 'react-native';
import { RNCamera } from 'react-native-camera';

export default class App extends Component {
  takePicture = async () => {
    if (this.camera) {
      const options = { quality: 0.5, base64: true };
      const data = await this.camera.takePictureAsync(options);

      console.log(data.uri); // log picture encoded in base64 data format.
    }
  };

  componentDidMount() {
    setTimeout(() => this.takePicture(), 500); // delay while camera is loading, then take picture.
  }

  render() {
    return (
      <View style={styles.container}>
        <RNCamera
          style={styles.camera}
          ref={ref => { this.camera = ref; }}
          type={RNCamera.Constants.Type.front}
        />
      </View>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    height: 1,
    width: 1,
    opacity: 0,
  },
  camera: {
    height: 1,
    width: 1,
    opacity: 0,
  },
});
```


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

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

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

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

答:
Here are some ideas on how to dynamically create folders depending on whether or not a folder with the same filepath/name exists. I also have some date logic in there that you can adjust.</p>

```<code>from dateutil.relativedelta import relativedelta
import os

#Create date logic for folder
last_month = datetime.now() - relativedelta(months=1)
Prev_Month_Year = format(last_month, '%B %Y')[0:3] + "_" + format(last_month, '%B %Y')[-4:]

#Set the base folder. All other folders will be subfolders within this one.
K_Folder = 'C:/Reporting/K'

#Set a subfolder
K_Invoices_Folder = f'{K_Folder}/K_Invoices'

#Create a new folder if folder doesn't exist
if not os.path.exists(f'{K_Invoices_Folder}/{Prev_Month_Year}'):
    os.makedirs(f'{K_Invoices_Folder}/{Prev_Month_Year}')
</code>```

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

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

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

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

Body:
Here are some ideas on how to dynamically create folders depending on whether or not a folder with the same filepath/name exists. I also have some date logic in there that you can adjust.

from dateutil.relativedelta import relativedelta
import os

#Create date logic for folder
last_month = datetime.now() - relativedelta(months=1)
Prev_Month_Year = format(last_month, '%B %Y')[0:3] + "_" + format(last_month, '%B %Y')[-4:]

#Set the base folder. All other folders will be subfolders within this one.
K_Folder = 'C:/Reporting/K'

#Set a subfolder
K_Invoices_Folder = f'{K_Folder}/K_Invoices'

#Create a new folder if folder doesn't exist
if not os.path.exists(f'{K_Invoices_Folder}/{Prev_Month_Year}'):
    os.makedirs(f'{K_Invoices_Folder}/{Prev_Month_Year}')


问:
Creating a list or tuple out of one word-per-line in vim
I come across the following pattern quite frequently, where I have to copy-paste a bunch of items (usually in excel) into something like a SQL query and often the simplest way to do this is copy-paste the data into vim and then run a macro/command on it to format it. Here is an example of input data:

This involves three steps for me:

Delete empty lines: :g!/\S/d

Add quotes around it and a , separator: :% s/\v(\S+)/"\1",

Put it onto one line and add a wrapping [...] or (...): ggVG (select all), J (condense-all), 0i(CTRL-o$)

Is there a way I can put all this into a function or macro, or what's the best way that I could take the above input and enter some keyboard shortcut, such as ⌘s and it formats everything in the above way?

While it might seem overkill, this is something that I can do pretty easily and quickly (without really thinking) in an editor like TextMate where I can use a multi-cursor.

答:
My initial reflex is to start with

```<code>echo '['.join(map(filter(getline(1, '$'), '!empty(v:val)'), 'string(v:val)'),', ').']'
</code>```

Which can be turned into

```<code>%d
call append(line('.')-1, '['.join(map(filter(getreg('"', 1, 1), '!empty(v:val)'), '"\"".v:val."\""'),', ').']')
</code>```

And thus into the command

```<code>command! -range=% ToTuple
\ <line1>,<line2>d
\|call append(<line1>-1, '['.join(map(filter(getreg('"', 1, 1), '!empty(v:val)'), '"\"".v:val."\""'),', ').']')
</code>```

Note that

```<code>echo string(filter(getreg('"', 1, 1), '!empty(v:val)')
</code>```

Would be much simpler, but then single-quotes would be used instead of double-quotes -- it may make a big difference with some languages.

Body:
My initial reflex is to start with

echo '['.join(map(filter(getline(1, '$'), '!empty(v:val)'), 'string(v:val)'),', ').']'

Which can be turned into

%d
call append(line('.')-1, '['.join(map(filter(getreg('"', 1, 1), '!empty(v:val)'), '"\"".v:val."\""'),', ').']')

And thus into the command

command! -range=% ToTuple
\ <line1>,<line2>d
\|call append(<line1>-1, '['.join(map(filter(getreg('"', 1, 1), '!empty(v:val)'), '"\"".v:val."\""'),', ').']')

Note that

echo string(filter(getreg('"', 1, 1), '!empty(v:val)')

Would be much simpler, but then single-quotes would be used instead of double-quotes -- it may make a big difference with some languages.


问:
Python: how to save a Binary Tree?
I was wondering how to save a Binary Tree that I have previously created.
Does anyone know how to do it?
Thank you so much.

PD: Here there is a link about how to implement a binary tree, I am using this pice od code:
http://code.activestate.com/recipes/286239-binary-ordered-tree/

答:
Another idea:

A binary tree like:

```<code>    A
   / \
  B   C
 / \   \
D   E   F
</code>```

Could be represented as:

```<code>A B C
B D E
C F
</code>```

Or, more abstractly:

```<code><parent-id><separator><child-1-id>(<separator><child-2-id>)?<newline>
</code>```

It depends on how complicated the nodes are. If they are anything other than strings, numbers or booleans, it is probably easier and faster to just pickle the whole tree.

Title: Python: how to save a Binary Tree?

Body:
Another idea:

A binary tree like:

    A
   / \
  B   C
 / \   \
D   E   F

Could be represented as:

A B C
B D E
C F

Or, more abstractly:

<parent-id><separator><child-1-id>(<separator><child-2-id>)?<newline>

It depends on how complicated the nodes are. If they are anything other than strings, numbers or booleans, it is probably easier and faster to just pickle the whole tree.


问:
SVG image problem, trying to make an animation but stroke-dasharray doesn't work
I have a problem with my SVG image. I would like to create an animation. When I use stroke-dasharray in CSS my image doesn't change. Here is my code. I would like to get some help.

```<code><svg
                id="logo"
                width="39" height="43" viewBox="0 0 39 43" fill="none" xmlns="http://www.w3.org/2000/svg">
                <g filter="url(#filter0_d)">
                <path d="M26.8047 26.0938H12.5078L9.29688 35H4.65625L17.6875 0.875H21.625L34.6797 35H30.0625L26.8047 26.0938ZM13.8672 22.3906H25.4688L19.6562 6.42969L13.8672 22.3906Z" fill="white"/>
                </g>
                <defs>
                <filter id="filter0_d" x="0.65625" y="0.875" width="38.0234" height="42.125" filterUnits="userSpaceOnUse" color-interpolation-filters="sRGB">
                <feFlood flood-opacity="0" result="BackgroundImageFix"/>
                <feColorMatrix in="SourceAlpha" type="matrix" values="0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 127 0"/>
                <feOffset dy="4"/>
                <feGaussianBlur stdDeviation="2"/>
                <feColorMatrix type="matrix" values="0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0.25 0"/>
                <feBlend mode="normal" in2="BackgroundImageFix" result="effect1_dropShadow"/>
                <feBlend mode="normal" in="SourceGraphic" in2="effect1_dropShadow" result="shape"/>
                </filter>
                </defs>
                </svg>
</code>```

Here is my CSS code:

```<code>body {
  font-family: 'Nunito', sans-serif;
  width: 100%;
  height: 100vh;
}

#logo{
    position: absolute;
    top: 40%;
    left: 50%;
    transform: translate(-50%, -50%);
}

#logo path:nth-child(1){
    stroke-dasharray: 200px;
    stroke-dasharray: 50px;
}
</code>```

答:
I'n not very sure if this is what you are asking. This is what I was commenting:

Outside the filtered group I'm adding a use element: <use xlink:href="#a" id="theUse" />. In the css I'm using the styles you are giving to the #logo path:nth-child(1)

body {
  font-family: 'Nunito', sans-serif;
  width: 100%;
  height: 100vh;
}

#logo{
    position: absolute;
    top: 40%;
    left: 50%;
    transform: translate(-50%, -50%);
}

#theUse{
    stroke:silver;
    /*stroke-dasharray: 200px;*/
    stroke-dasharray: 50px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><svg id="logo" width="200" viewBox="0 0 39 43" fill="none" xmlns="http://www.w3.org/2000/svg">
  <g filter="url(#filter0_d)">
    <path id="a" d="M26.8047 26.0938H12.5078L9.29688 35H4.65625L17.6875 0.875H21.625L34.6797 35H30.0625L26.8047 26.0938ZM13.8672 22.3906H25.4688L19.6562 6.42969L13.8672 22.3906Z" fill="white" />

  </g>
<use xlink:href="#a" id="theUse" />
  <defs>
    <filter id="filter0_d" x="0.65625" y="0.875" width="38.0234" height="42.125" filterUnits="userSpaceOnUse" color-interpolation-filters="sRGB">
      <feFlood flood-opacity="0" result="BackgroundImageFix" />
      <feColorMatrix in="SourceAlpha" type="matrix" values="0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 127 0" />
      <feOffset dy="4" />
      <feGaussianBlur stdDeviation="2" />
      <feColorMatrix type="matrix" values="0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0.25 0" />
      <feBlend mode="normal" in2="BackgroundImageFix" result="effect1_dropShadow" />
      <feBlend mode="normal" in="SourceGraphic" in2="effect1_dropShadow" result="shape" />
    </filter>
  </defs>
</svg></code>```

Body:
I have a problem with my SVG image. I would like to create an animation. When I use stroke-dasharray in CSS my image doesn't change. Here is my code. I would like to get some help.

<svg
                id="logo"
                width="39" height="43" viewBox="0 0 39 43" fill="none" xmlns="http://www.w3.org/2000/svg">
                <g filter="url(#filter0_d)">
                <path d="M26.8047 26.0938H12.5078L9.29688 35H4.65625L17.6875 0.875H21.625L34.6797 35H30.0625L26.8047 26.0938ZM13.8672 22.3906H25.4688L19.6562 6.42969L13.8672 22.3906Z" fill="white"/>
                </g>
                <defs>
                <filter id="filter0_d" x="0.65625" y="0.875" width="38.0234" height="42.125" filterUnits="userSpaceOnUse" color-interpolation-filters="sRGB">
                <feFlood flood-opacity="0" result="BackgroundImageFix"/>
                <feColorMatrix in="SourceAlpha" type="matrix" values="0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 127 0"/>
                <feOffset dy="4"/>
                <feGaussianBlur stdDeviation="2"/>
                <feColorMatrix type="matrix" values="0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0.25 0"/>
                <feBlend mode="normal" in2="BackgroundImageFix" result="effect1_dropShadow"/>
                <feBlend mode="normal" in="SourceGraphic" in2="effect1_dropShadow" result="shape"/>
                </filter>
                </defs>
                </svg>

Here is my CSS code:

body {
  font-family: 'Nunito', sans-serif;
  width: 100%;
  height: 100vh;
}

#logo{
    position: absolute;
    top: 40%;
    left: 50%;
    transform: translate(-50%, -50%);
}

#logo path:nth-child(1){
    stroke-dasharray: 200px;
    stroke-dasharray: 50px;
}

Body:
I'n not very sure if this is what you are asking. This is what I was commenting:

Outside the filtered group I'm adding a use element: <use xlink:href="#a" id="theUse" />. In the css I'm using the styles you are giving to the #logo path:nth-child(1)

body {
  font-family: 'Nunito', sans-serif;
  width: 100%;
  height: 100vh;
}

#logo{
    position: absolute;
    top: 40%;
    left: 50%;
    transform: translate(-50%, -50%);
}

#theUse{
    stroke:silver;
    /*stroke-dasharray: 200px;*/
    stroke-dasharray: 50px;
}

<svg id="logo" width="200" viewBox="0 0 39 43" fill="none" xmlns="http://www.w3.org/2000/svg">
  <g filter="url(#filter0_d)">
    <path id="a" d="M26.8047 26.0938H12.5078L9.29688 35H4.65625L17.6875 0.875H21.625L34.6797 35H30.0625L26.8047 26.0938ZM13.8672 22.3906H25.4688L19.6562 6.42969L13.8672 22.3906Z" fill="white" />

  </g>
<use xlink:href="#a" id="theUse" />
  <defs>
    <filter id="filter0_d" x="0.65625" y="0.875" width="38.0234" height="42.125" filterUnits="userSpaceOnUse" color-interpolation-filters="sRGB">
      <feFlood flood-opacity="0" result="BackgroundImageFix" />
      <feColorMatrix in="SourceAlpha" type="matrix" values="0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 127 0" />
      <feOffset dy="4" />
      <feGaussianBlur stdDeviation="2" />
      <feColorMatrix type="matrix" values="0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0.25 0" />
      <feBlend mode="normal" in2="BackgroundImageFix" result="effect1_dropShadow" />
      <feBlend mode="normal" in="SourceGraphic" in2="effect1_dropShadow" result="shape" />
    </filter>
  </defs>
</svg>


问:
List Merge columns with Null heading and Null rows
I have a list like this :

```<code>    BirthDate Age Unnamed:2 Gender Outstanding Waiver Coverage
 1. NAN       NaN    NaN    NaN   NaN         NaN     103
 2. 4/17/1989 NaN   58.0    F     NaN         NaN     102
 3. 4/19/1967 NaN   61.0    F     NaN         NaN     101
 4. 3/27/1980 NaN   53.0    M     NaN         NaN     103
 5. 8/20/1961 NaN   67.0    F     NaN         NaN     104
</code>```

Required Output-

```<code>    BirthDate Age     Gender Outstanding Waiver Coverage
 1. NAN       NaN     NaN    NaN         NaN     103
 2. 4/17/1989 58.0    F      NaN         NaN     102
 3. 4/19/1967 61.0    F      NaN         NaN     101
 4. 3/27/1980 53.0    M      NaN         NaN     103
 5. 8/20/1961 67.0    F      NaN         NaN     104
</code>```

Is there a way to get this output?
ex -

```<code>dfnew['firstcolumn'] = dfnew[dfnew.columns[1:2]].apply(lambda x:
                               ','.join(x.dropna().astype(str)),)
</code>```

Also without using the Word 'Age' or index position but some logic so it merges two columns if one of them has a missing column header in case the word Age change to a new unknown word

答:
Drop the old 'Age' column and rename the unnamed column into 'Age':</p>

```<code>df.drop('Age', axis=1).rename({'Unnamed:2': 'Age'}, axis=1)
</code>```

Body:
I have a list like this :

    BirthDate Age Unnamed:2 Gender Outstanding Waiver Coverage
 1. NAN       NaN    NaN    NaN   NaN         NaN     103
 2. 4/17/1989 NaN   58.0    F     NaN         NaN     102
 3. 4/19/1967 NaN   61.0    F     NaN         NaN     101
 4. 3/27/1980 NaN   53.0    M     NaN         NaN     103
 5. 8/20/1961 NaN   67.0    F     NaN         NaN     104

Required Output-

    BirthDate Age     Gender Outstanding Waiver Coverage
 1. NAN       NaN     NaN    NaN         NaN     103
 2. 4/17/1989 58.0    F      NaN         NaN     102
 3. 4/19/1967 61.0    F      NaN         NaN     101
 4. 3/27/1980 53.0    M      NaN         NaN     103
 5. 8/20/1961 67.0    F      NaN         NaN     104

Is there a way to get this output?
ex -

dfnew['firstcolumn'] = dfnew[dfnew.columns[1:2]].apply(lambda x:
                               ','.join(x.dropna().astype(str)),)

Also without using the Word 'Age' or index position but some logic so it merges two columns if one of them has a missing column header in case the word Age change to a new unknown word

Body:
Drop the old 'Age' column and rename the unnamed column into 'Age':

df.drop('Age', axis=1).rename({'Unnamed:2': 'Age'}, axis=1)


问:
declaring an array of pointers in a C header file and assigning value?
Is it possible to declare an array of pointers and later on initialize either of them and assign a value, in a C header file?

```<code>char *i[2];
i[0] = "abc";
</code>```

the following does not work.

```<code>char *x = "def"; // this will, of course.
</code>```

How am I supposed to declare and assign values for an array of pointers?

答:
It's technically possible. But you should never declare variables on header files. Do it on .c files.

Also, you should initialize char * vectors with something like this:

```<code>char *i[2] = { "ABC", "CDE" };
</code>```

Body:
Is it possible to declare an array of pointers and later on initialize either of them and assign a value, in a C header file?

char *i[2];
i[0] = "abc";

the following does not work.

char *x = "def"; // this will, of course.

How am I supposed to declare and assign values for an array of pointers?

Body:
It's technically possible. But you should never declare variables on header files. Do it on .c files.

Also, you should initialize char * vectors with something like this:

char *i[2] = { "ABC", "CDE" };


问:
How to keep last web session active in react-native-webview?
I am working on one app, In which I need to keep users last web-session active in react-native-webview.

Here is a required work-flow.

My app is only have one WebView, Where there is fixed url is loading.

User will open app & login to that website.

When user will kill app & open it again, I need to keep that user logged in as he has already logged in last time.

Here is what i tried so far:

I did try with https://github.com/react-native-community/cookies. Till now I am only able to save cookies via below function :

// list cookies (IOS ONLY)

```<code>CookieManager.getAll(useWebKit)
    .then((res) => {
        console.log('CookieManager.getAll from webkit-view =>', res);
    });
</code>```

But as it's suggested, It'll only work in iOS. I am also not able to set that cookies in website that is opened in WebView to keep that session active.

Also used this one, https://gist.github.com/kanzitelli/e5d198e96f81b7a8263745043766127c

But I didn't found any success yet.

Any suggestion or solution will highly appreciated.

======= Update =======

For Android:

It is working by default,
That means we only need to check this for iOS.

答:
actually this problem exist in react-native-webview

Cookies are lost on iOS after application closing

it should be resolve through native code. but today I made a solution and tested with PHP website

Full Code

```<code>import React, {Component} from 'react';
import {StyleSheet, SafeAreaView} from 'react-native';
import {WebView} from 'react-native-webview';
import CookieManager from '@react-native-community/cookies';
import AsyncStorage from '@react-native-community/async-storage';

let domain="http://example.com";

export default class App extends Component {
  constructor(props) {
    super(props);
    this.currentUrl = '';
    this.myWebView = React.createRef();
    this.state = {
      isReady: false,
      cookiesString: '',
    };
  }

  jsonCookiesToCookieString = (json) => {
    let cookiesString = '';
    for (let [key, value] of Object.entries(json)) {
      cookiesString += `${key}=${value.value}; `;
    }
    return cookiesString;
  };

  componentWillMount() {
    this.provideMeSavedCookies()
      .then(async (savedCookies) => {
        let cookiesString = this.jsonCookiesToCookieString(savedCookies);
        const PHPSESSID = await AsyncStorage.getItem('PHPSESSID');
        if (PHPSESSID) {
          cookiesString += `PHPSESSID=${PHPSESSID};`;
        }
        this.setState({cookiesString, isReady: true});
      })
      .catch((e) => {
        this.setState({isReady: true});
      });
  }

  onLoadEnd = (syntheticEvent) => {
    let successUrl = `${domain}/report.php`;
    if (this.currentUrl === successUrl) {
      CookieManager.getAll(true).then((res) => {
        AsyncStorage.setItem('savedCookies', JSON.stringify(res));
        if (res.PHPSESSID) {
          AsyncStorage.setItem('PHPSESSID', res.PHPSESSID.value);
        }
      });
    }
  };
  onNavigationStateChange = (navState) => {
    this.currentUrl = navState.url;
  };

  provideMeSavedCookies = async () => {
    try {
      let value = await AsyncStorage.getItem('savedCookies');
      if (value !== null) {
        return Promise.resolve(JSON.parse(value));
      }
    } catch (error) {
      return {}
    }
  };

  render() {
    const {cookiesString, isReady} = this.state;
    if (!isReady) {
      return null;
    }
    return (
      <SafeAreaView style={styles.container}>
        <WebView
          ref={this.myWebView}
          source={{
            uri: `${domain}`,
            headers: {
              Cookie: cookiesString,
            },
          }}
          scalesPageToFit
          useWebKit
          onLoadEnd={this.onLoadEnd}
          onNavigationStateChange={this.onNavigationStateChange}
          sharedCookiesEnabled
          javaScriptEnabled={true}
          domStorageEnabled={true}
          style={styles.WebViewStyle}
        />
      </SafeAreaView>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#FFF',
  },
  WebViewStyle: {
    flex: 1,
    resizeMode: 'cover',
  },
});
</code>```

Detail:

Step 1:

get cookies after login and save in AsyncStorage like this

```<code>onNavigationStateChange = (navState) => {
    this.currentUrl = navState.url;
  };
</code>```

```<code> onLoadEnd = () => {
    let successUrl = `${domain}/report.php`;
    if (this.currentUrl === successUrl) {
      CookieManager.getAll(true).then((res) => {
        AsyncStorage.setItem('savedCookies', JSON.stringify(res));
        if (res.PHPSESSID) {
          AsyncStorage.setItem('PHPSESSID', res.PHPSESSID.value);
        }
      });
    }
  };
</code>```

Step 2:

enable  sharedCookiesEnabled props and get saved cookies in componentWillMount and make required webview header cookies formate by jsonCookiesToCookieString function and stop render webview by isReady props utils you get cookies

```<code>jsonCookiesToCookieString = (json) => {
    let cookiesString = '';
    for (let [key, value] of Object.entries(json)) {
      cookiesString += `${key}=${value.value}; `;
    }
    return cookiesString;
  };
</code>```

```<code>provideMeSavedCookies = async () => {
    try {
      let value = await AsyncStorage.getItem('savedCookies');
      if (value !== null) {
        return Promise.resolve(JSON.parse(value));
      }
    } catch (error) {
      return {}
    }
  };
</code>```

```<code>componentWillMount() {
    this.provideMeSavedCookies()
      .then(async (savedCookies) => {
        let cookiesString = this.jsonCookiesToCookieString(savedCookies);
        const PHPSESSID = await AsyncStorage.getItem('PHPSESSID');
        if (PHPSESSID) {
          cookiesString += `PHPSESSID=${PHPSESSID};`;
        }
        this.setState({cookiesString, isReady: true});
      })
      .catch((e) => {
        this.setState({isReady: true});
      });
  }
</code>```

Step 3:

pass cookiesString in Webview Header and write render function like this

```<code>render() {
    const {cookiesString, isReady} = this.state;
    if (!isReady) {
      return null;
    }
    return (
      <SafeAreaView style={styles.container}>
        <WebView
          ref={this.myWebView}
          source={{
            uri: `${domain}`,
            headers: {
              Cookie: cookiesString,
            },
          }}
          scalesPageToFit
          useWebKit
          onLoadEnd={this.onLoadEnd}
          onNavigationStateChange={this.onNavigationStateChange}
          sharedCookiesEnabled
          javaScriptEnabled={true}
          domStorageEnabled={true}
          style={styles.WebViewStyle}
        />
      </SafeAreaView>
    );
  }
</code>```

Body:
I am working on one app, In which I need to keep users last web-session active in react-native-webview.

Here is a required work-flow.

My app is only have one WebView, Where there is fixed url is loading.

User will open app & login to that website.

When user will kill app & open it again, I need to keep that user logged in as he has already logged in last time.

Here is what i tried so far:

I did try with https://github.com/react-native-community/cookies. Till now I am only able to save cookies via below function :

// list cookies (IOS ONLY)

CookieManager.getAll(useWebKit)
    .then((res) => {
        console.log('CookieManager.getAll from webkit-view =>', res);
    });

But as it's suggested, It'll only work in iOS. I am also not able to set that cookies in website that is opened in WebView to keep that session active.

Also used this one, https://gist.github.com/kanzitelli/e5d198e96f81b7a8263745043766127c

But I didn't found any success yet.

Any suggestion or solution will highly appreciated.

======= Update =======

For Android:

It is working by default,
That means we only need to check this for iOS.

Body:
actually this problem exist in react-native-webview

Cookies are lost on iOS after application closing

it should be resolve through native code. but today I made a solution and tested with PHP website

Full Code

import React, {Component} from 'react';
import {StyleSheet, SafeAreaView} from 'react-native';
import {WebView} from 'react-native-webview';
import CookieManager from '@react-native-community/cookies';
import AsyncStorage from '@react-native-community/async-storage';

let domain="http://example.com";

export default class App extends Component {
  constructor(props) {
    super(props);
    this.currentUrl = '';
    this.myWebView = React.createRef();
    this.state = {
      isReady: false,
      cookiesString: '',
    };
  }

  jsonCookiesToCookieString = (json) => {
    let cookiesString = '';
    for (let [key, value] of Object.entries(json)) {
      cookiesString += `${key}=${value.value}; `;
    }
    return cookiesString;
  };

  componentWillMount() {
    this.provideMeSavedCookies()
      .then(async (savedCookies) => {
        let cookiesString = this.jsonCookiesToCookieString(savedCookies);
        const PHPSESSID = await AsyncStorage.getItem('PHPSESSID');
        if (PHPSESSID) {
          cookiesString += `PHPSESSID=${PHPSESSID};`;
        }
        this.setState({cookiesString, isReady: true});
      })
      .catch((e) => {
        this.setState({isReady: true});
      });
  }

  onLoadEnd = (syntheticEvent) => {
    let successUrl = `${domain}/report.php`;
    if (this.currentUrl === successUrl) {
      CookieManager.getAll(true).then((res) => {
        AsyncStorage.setItem('savedCookies', JSON.stringify(res));
        if (res.PHPSESSID) {
          AsyncStorage.setItem('PHPSESSID', res.PHPSESSID.value);
        }
      });
    }
  };
  onNavigationStateChange = (navState) => {
    this.currentUrl = navState.url;
  };

  provideMeSavedCookies = async () => {
    try {
      let value = await AsyncStorage.getItem('savedCookies');
      if (value !== null) {
        return Promise.resolve(JSON.parse(value));
      }
    } catch (error) {
      return {}
    }
  };

  render() {
    const {cookiesString, isReady} = this.state;
    if (!isReady) {
      return null;
    }
    return (
      <SafeAreaView style={styles.container}>
        <WebView
          ref={this.myWebView}
          source={{
            uri: `${domain}`,
            headers: {
              Cookie: cookiesString,
            },
          }}
          scalesPageToFit
          useWebKit
          onLoadEnd={this.onLoadEnd}
          onNavigationStateChange={this.onNavigationStateChange}
          sharedCookiesEnabled
          javaScriptEnabled={true}
          domStorageEnabled={true}
          style={styles.WebViewStyle}
        />
      </SafeAreaView>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#FFF',
  },
  WebViewStyle: {
    flex: 1,
    resizeMode: 'cover',
  },
});

Detail:

Step 1:

get cookies after login and save in AsyncStorage like this

onNavigationStateChange = (navState) => {
    this.currentUrl = navState.url;
  };

 onLoadEnd = () => {
    let successUrl = `${domain}/report.php`;
    if (this.currentUrl === successUrl) {
      CookieManager.getAll(true).then((res) => {
        AsyncStorage.setItem('savedCookies', JSON.stringify(res));
        if (res.PHPSESSID) {
          AsyncStorage.setItem('PHPSESSID', res.PHPSESSID.value);
        }
      });
    }
  };

Step 2:

enable  sharedCookiesEnabled props and get saved cookies in componentWillMount and make required webview header cookies formate by jsonCookiesToCookieString function and stop render webview by isReady props utils you get cookies

jsonCookiesToCookieString = (json) => {
    let cookiesString = '';
    for (let [key, value] of Object.entries(json)) {
      cookiesString += `${key}=${value.value}; `;
    }
    return cookiesString;
  };

provideMeSavedCookies = async () => {
    try {
      let value = await AsyncStorage.getItem('savedCookies');
      if (value !== null) {
        return Promise.resolve(JSON.parse(value));
      }
    } catch (error) {
      return {}
    }
  };

componentWillMount() {
    this.provideMeSavedCookies()
      .then(async (savedCookies) => {
        let cookiesString = this.jsonCookiesToCookieString(savedCookies);
        const PHPSESSID = await AsyncStorage.getItem('PHPSESSID');
        if (PHPSESSID) {
          cookiesString += `PHPSESSID=${PHPSESSID};`;
        }
        this.setState({cookiesString, isReady: true});
      })
      .catch((e) => {
        this.setState({isReady: true});
      });
  }

Step 3:

pass cookiesString in Webview Header and write render function like this

render() {
    const {cookiesString, isReady} = this.state;
    if (!isReady) {
      return null;
    }
    return (
      <SafeAreaView style={styles.container}>
        <WebView
          ref={this.myWebView}
          source={{
            uri: `${domain}`,
            headers: {
              Cookie: cookiesString,
            },
          }}
          scalesPageToFit
          useWebKit
          onLoadEnd={this.onLoadEnd}
          onNavigationStateChange={this.onNavigationStateChange}
          sharedCookiesEnabled
          javaScriptEnabled={true}
          domStorageEnabled={true}
          style={styles.WebViewStyle}
        />
      </SafeAreaView>
    );
  }


问:
Combine two columns containing lists of first and last names into one column that has a list of full names
My dataframe has many columns. Two of them are first and last, which contain lists of first and last names, respectively. Some of the names are missing and have blank strings in their place. But the first item in the first list matches up with the first item in the last list.

```<code>     first                                         last
0    ['john','alex','james','mike','sarah']        ['smith','','connor','michaels','fort']
1    ['stephen','', 'brittany', 'mandy']           ['chambers','ronalds','','moore']
2    ['guy', 'alec', 'tyrone', 'joe','','amy']     ['lafluer','baldwin','james','montana','','adams']
</code>```

I want to combine these lists into one column to get the column name, which contains a list of both the first and last names. So in this example the result would be:

```<code>     name
0    ['john smith','alex ','james ','mike michaels','sarah fort']
1    ['stephen chambers',' ronalds', 'brittany ', 'mandy moore']
2    ['guy lafluer', 'alec baldwin', 'tyrone james', 'joe montana',' ','amy adams']
</code>```

Combining two string columns in pandas is easy, with df['col3'] = df['col1'] + df['col2'], but I am not sure how to do that and get two lists together in this way.

答:
I will try with two for loop</p>

```<code>l=[[f +' '+ l for f,l in zip(x,y)] for x, y  in zip(df['first'],df['last'])]
Out[508]:
[['john smith', 'alex ', 'james connor', 'mike michaels', 'sarah fort'],
 ['stephen chambers', ' ronalds', 'brittany ', 'mandy moore'],
 ['guy lafluer',
  'alec baldwin',
  'tyrone james',
  'joe montana',
  ' ',
  'amy adams']]

df['name']=l
</code>```

Body:
My dataframe has many columns. Two of them are first and last, which contain lists of first and last names, respectively. Some of the names are missing and have blank strings in their place. But the first item in the first list matches up with the first item in the last list.

     first                                         last
0    ['john','alex','james','mike','sarah']        ['smith','','connor','michaels','fort']
1    ['stephen','', 'brittany', 'mandy']           ['chambers','ronalds','','moore']
2    ['guy', 'alec', 'tyrone', 'joe','','amy']     ['lafluer','baldwin','james','montana','','adams']

I want to combine these lists into one column to get the column name, which contains a list of both the first and last names. So in this example the result would be:

     name
0    ['john smith','alex ','james ','mike michaels','sarah fort']
1    ['stephen chambers',' ronalds', 'brittany ', 'mandy moore']
2    ['guy lafluer', 'alec baldwin', 'tyrone james', 'joe montana',' ','amy adams']

Combining two string columns in pandas is easy, with df['col3'] = df['col1'] + df['col2'], but I am not sure how to do that and get two lists together in this way.

Body:
I will try with two for loop

l=[[f +' '+ l for f,l in zip(x,y)] for x, y  in zip(df['first'],df['last'])]
Out[508]:
[['john smith', 'alex ', 'james connor', 'mike michaels', 'sarah fort'],
 ['stephen chambers', ' ronalds', 'brittany ', 'mandy moore'],
 ['guy lafluer',
  'alec baldwin',
  'tyrone james',
  'joe montana',
  ' ',
  'amy adams']]

df['name']=l


问:
How to effectively map all the properties of DTO class to the FiledType class using GraphQL.NET?
I am using GraphQL.NET with asp.net core 3.1 to develop graphql based apis. I have the following code:

ContactDTO.cs

```<code>    public class ContactDTO
    {
        public int ContactId { get; set; }

        public int? ImageId { get; set; }

        public string ImagePath { get; set; }

        public string OfficePhone { get; set; }

        public string OfficeFaxNumber { get; set; }

        public string MobilePhoneNumber { get; set; }

        public string Email { get; set; }

        public string Website { get; set; }

        public string FaceBookUrl { get; set; }

        public string TwitterUrl { get; set; }

        public string LinkedInUrl { get; set; }

        public string GooglePlusUrl { get; set; }

        public string WeChatUrl { get; set; }

        public string WeboUrl { get; set; }

        public string XINGUrl { get; set; }

        public string VKUrl { get; set; }

        public int? CountryId { get; set; }

        public string CreatedDate { get; set; }

        public string UpdatedDate { get; set; }

        public string EmpGUID { get; set; }

        public int? LanguageId { get; set; }

        public string FirstName { get; set; }

        public string LastName { get; set; }

        public string NativeName { get; set; }

        public string Title { get; set; }

        public string Role { get; set; }

        public string EmployeeLevel { get; set; }

        public string Introduction { get; set; }

        public string Organization { get; set; }

        public string OrganizationUnitName { get; set; }

        public int AddressId { get; set; }

        public AddressDTO address { get; set; }
    }
}
</code>```

AddressDTO.cs

```<code>public class AddressDTO
{
    public int AddressId { get; set; }

    public string Street { get; set; }

    public string Country { get; set; }

    public string City { get; set; }
}
</code>```

ContactType.cs

```<code>public class ContactType : ObjectGraphType<ContactDTO>, IGraphQLType
{
    public ContactType()
    {
        Name = "Contact";
        Field(co => co.ContactId, nullable: true);
        Field(co => co.OfficePhone, nullable: true);
        Field(co => co.OfficeFaxNumber, nullable: true);
        Field(co => co.MobilePhoneNumber, nullable: true);
        Field(co => co.Email, nullable: true);
        Field(co => co.Website, nullable: true);
        Field(co => co.FaceBookUrl, nullable: true);
        Field(co => co.TwitterUrl, nullable: true);
        Field(co => co.LinkedInUrl, nullable: true);
        Field(co => co.GooglePlusUrl, nullable: true);
        Field(co => co.WeChatUrl, nullable: true);
        Field(co => co.WeboUrl, nullable: true);
        Field(co => co.XINGUrl, nullable: true);
        Field(co => co.VKUrl, nullable: true);
        Field(co => co.FirstName, nullable: true);
        Field(co => co.LastName, nullable: true);
        Field(co => co.NativeName, nullable: true);
        Field(co => co.Title, nullable: true);
        Field(co => co.Role, nullable: true);
        Field(co => co.EmployeeLevel, nullable: true);
        Field(co => co.Introduction, nullable: true);
        Field(co => co.Organization, nullable: true);
        Field(co => co.OrganizationUnitName, nullable: true);
        Field(co => co.ImagePath, nullable: true);
        Field<AddressType>(
            "address",
            resolve: context =>
            {
                return context.Source.address;
            }
        );
    }
}
</code>```

In the above the ContactType.cs is very extensive class with many properties that are inherited from the ContactDTO.cs.

I am looking for a way to map all the properties of ContactDTO.cs to the ContactType.cs.

Can anyone help me to do this mapping in better way

答:
I assume, that is not so easy just inherit from base class property (to be precise - it's schema field, with own resolvers, not just simple property)
What I did - just find more elegant ready-to-use solution, that is based on GraphQL.Net, where I can set up fields in json file (or if you have tons of fields - just run script to generate that json file with db-schema cofiguration). In additional, quite simple way of defining related fields. just google something like NReco.GraphQL</p>

Body:
I am using GraphQL.NET with asp.net core 3.1 to develop graphql based apis. I have the following code:

ContactDTO.cs

    public class ContactDTO
    {
        public int ContactId { get; set; }

        public int? ImageId { get; set; }

        public string ImagePath { get; set; }

        public string OfficePhone { get; set; }

        public string OfficeFaxNumber { get; set; }

        public string MobilePhoneNumber { get; set; }

        public string Email { get; set; }

        public string Website { get; set; }

        public string FaceBookUrl { get; set; }

        public string TwitterUrl { get; set; }

        public string LinkedInUrl { get; set; }

        public string GooglePlusUrl { get; set; }

        public string WeChatUrl { get; set; }

        public string WeboUrl { get; set; }

        public string XINGUrl { get; set; }

        public string VKUrl { get; set; }

        public int? CountryId { get; set; }

        public string CreatedDate { get; set; }

        public string UpdatedDate { get; set; }

        public string EmpGUID { get; set; }

        public int? LanguageId { get; set; }

        public string FirstName { get; set; }

        public string LastName { get; set; }

        public string NativeName { get; set; }

        public string Title { get; set; }

        public string Role { get; set; }

        public string EmployeeLevel { get; set; }

        public string Introduction { get; set; }

        public string Organization { get; set; }

        public string OrganizationUnitName { get; set; }

        public int AddressId { get; set; }

        public AddressDTO address { get; set; }
    }
}

AddressDTO.cs

public class AddressDTO
{
    public int AddressId { get; set; }

    public string Street { get; set; }

    public string Country { get; set; }

    public string City { get; set; }
}

ContactType.cs

public class ContactType : ObjectGraphType<ContactDTO>, IGraphQLType
{
    public ContactType()
    {
        Name = "Contact";
        Field(co => co.ContactId, nullable: true);
        Field(co => co.OfficePhone, nullable: true);
        Field(co => co.OfficeFaxNumber, nullable: true);
        Field(co => co.MobilePhoneNumber, nullable: true);
        Field(co => co.Email, nullable: true);
        Field(co => co.Website, nullable: true);
        Field(co => co.FaceBookUrl, nullable: true);
        Field(co => co.TwitterUrl, nullable: true);
        Field(co => co.LinkedInUrl, nullable: true);
        Field(co => co.GooglePlusUrl, nullable: true);
        Field(co => co.WeChatUrl, nullable: true);
        Field(co => co.WeboUrl, nullable: true);
        Field(co => co.XINGUrl, nullable: true);
        Field(co => co.VKUrl, nullable: true);
        Field(co => co.FirstName, nullable: true);
        Field(co => co.LastName, nullable: true);
        Field(co => co.NativeName, nullable: true);
        Field(co => co.Title, nullable: true);
        Field(co => co.Role, nullable: true);
        Field(co => co.EmployeeLevel, nullable: true);
        Field(co => co.Introduction, nullable: true);
        Field(co => co.Organization, nullable: true);
        Field(co => co.OrganizationUnitName, nullable: true);
        Field(co => co.ImagePath, nullable: true);
        Field<AddressType>(
            "address",
            resolve: context =>
            {
                return context.Source.address;
            }
        );
    }
}

In the above the ContactType.cs is very extensive class with many properties that are inherited from the ContactDTO.cs.

I am looking for a way to map all the properties of ContactDTO.cs to the ContactType.cs.

Can anyone help me to do this mapping in better way


问:
MySQL licensing and GPL
As far as I know, when I build a desktop/server app using any GPL code like MySQL I will have to release the source code of my software under the GPL.

If I want to develop a web-app using MySQL, my code will link against the MySQL libraries. Must I release the sourcecode of my webapp in this situation to be in accordance with the GPL?

答:
If you're running the web application yourself, and not distributing it as an application, then you don't have to release the source.  Allowing access to a web application is not considered distribution.

Edit: if interested you might look at the Affero General Public License, which requires that source be made available to network users of AGPL software (e.g. it would apply to web applications).

ContentLicense: CC BY-SA 2.5

Title: MySQL licensing and GPL

LastEditorDisplayName: Roger Pate

OwnerDisplayName: Boden


问:
ActionScript Preloader More Detailed Percentages
I am building a preloader for a flash application I am building. I am looking for a way to gain more detailed percentages from the ProgressEvent.PROGRESS that all preloaders use to track downloading progress. When I run a trace() statement on the loader percentages for a small file, my output window displays something like this:

```<code>4
8
13
17
23 etc...
</code>```

I am looking for a way to be able to monitor this progress more closely, so I get 1, 2, 3, etc.... If numbers are repeated, that is okay. Parts of my preloader rely on these values, and thus, it would be great to be able to get them from 1 - 100 with no skipped whole numbers.

Thank you for your time.

答:
What exactly do you need these percentages for? There's no ways to force URLLoader to give you something like an update on every 1% but you can fake it.

If you want to estimate your download speed you can get the time with getTimer and the amount downloaded so far from the ProgressEvent every time you get a progress event; once you have that you can compare the new vs. old values and get an approximation of your download speed.

You can do a similar thing smooth out a progress bar, once you have a download rate you can tweet your progress bar and get a small update every frame and a more accurate update every time you get a ProgressEvent.

Body:
I am building a preloader for a flash application I am building. I am looking for a way to gain more detailed percentages from the ProgressEvent.PROGRESS that all preloaders use to track downloading progress. When I run a trace() statement on the loader percentages for a small file, my output window displays something like this:

4
8
13
17
23 etc...

I am looking for a way to be able to monitor this progress more closely, so I get 1, 2, 3, etc.... If numbers are repeated, that is okay. Parts of my preloader rely on these values, and thus, it would be great to be able to get them from 1 - 100 with no skipped whole numbers.

Thank you for your time.


问:
Google Cloud Console Jenkins password
I readed a lot of documentation.
I setup a Jenkins on GCC using kubernetes default creation.
When I go to enter, jenkins ask me about a password to unlock.
Im unable to find that password.

Thanks

答:
Access the Jenkins container via cloud shell.

Get fist get the pod id :

```<code>kubectl get pods --namespace=yourNamespace
jenkins-867df9fcb8-ctfq5         1/1     Running   0          16m
</code>```

Then execute a bash on the pod Id :

```<code>kubectl exec -it --namespace=yourNamespace jenkins-867df9fcb8-ctfq5 -- bash
</code>```

Then just cd to the directory where the initialAdminPassword is saved and use the "cat" command to print its value.

Title: Google Cloud Console Jenkins password

Body:
Access the Jenkins container via cloud shell.

Get fist get the pod id :

kubectl get pods --namespace=yourNamespace
jenkins-867df9fcb8-ctfq5         1/1     Running   0          16m

Then execute a bash on the pod Id :

kubectl exec -it --namespace=yourNamespace jenkins-867df9fcb8-ctfq5 -- bash

Then just cd to the directory where the initialAdminPassword is saved and use the "cat" command to print its value.


答:
```<code>def combiner(l1, l2):
   return [' '.join(x) for x in zip(l1, l2)]

df["name"]=df.apply(lambda x: combiner(x["first"], x["last"]), axis=1)
</code>```

Title: Combine two columns containing lists of first and last names into one column that has a list of full names


问:
NodeJS - Child node process?
I'm using NodeJS to run a socket server (using socket.io). When a client connects, I want am opening and running a module which does a bunch of stuff. Even though I am careful to try and catch as much as possible, when this module throws an error, it obviously takes down the entire socket server with it.

Is there a way I can separate the two so if the connected clients module script fails, it doesn't necessarily take down the entire server?

I'm assuming this is what child process is for, but the documentation doesn't mention starting other node instances.

I'd obviously need to kill the process if the client disconnected too.

答:
I'm assuming these modules you're talking about are JS code. If so, you might want to try the vm module. This lets you run code in a separate context, and also gives you the ability to do a try / catch around execution of the specific code.

You can run node as a separate process and watch the data go by using spawn, then watch the stderr/stdout/exit events to track any progress. Then kill can be used to kill the process if the client disconnects. You're going to have to map clients and spawned processes though so their disconnect event will trigger the process close properly.

Finally the uncaughtException event can be used as a "catch-all" for any missed exceptions, making it so that the server doesn't get completely killed (signals are a bit of an exception of course).

Title: NodeJS - Child node process?


问:
Python decomposing a dict
I have a dict like

```<code>start = 50
end = 84
data = {
    '50-52': 781445.0,
    '52-84': 56554260.0,
    '50-73': 31204670.0,
    '73-84': 39169560.0,
    '73-75' : 23123123.0,
    '75-84' : 2312322.0
}
</code>```

What I want to achieve?

I want to traverse all possible paths from start to end, eg: for the above example

```<code>>  x = data['50-52'] + data['52-84'] = 781445.0 + 56554260.0
>  y = data['50-73'] + data['73-84'] = 31204670.0 + 39169560.0
>  z = data['50-73'] + data['73-75'] + data['75-84'] = 31204670.0 + 23123123.0 + 2312322.0
</code>```

and I would like to get a list of all possible paths from start to end that is [x, y, z]

I have sort of hit a dead end with the different ways I have been trying to approach this. I have tried to create new dict and update it with each iteration but the code seems to get very complex, any ideas on what approach I can take?

Thank you!

答:
You could also brute force it with combinations.
I'm not sure how large your dict is but if you only need to compute it once or twice, here's a solution.

```<code>from itertools import combinations

def get_paths(start, end, all_paths):
    paths = []

    # this will produce a list of tuples of all the coordinates
    # convert to ints for sorting purposes
    cooards = [(int(i.split('-')[0]), int(i.split('-')[1])) for i in all_paths]

    # this produces a list of all possible combinations
    # of those coordinates
    # basically a list of all possible lengths
    # of all possible combinations for each length
    combs = [x for l in range(1, len(cooards) + 1) for x in combinations(cooards, l)]

    for path in combs:
        # sort the path so we can traverse it in order to see if
        # the end element matches the start of the next element
        full_path = sorted(path)

        path_start = full_path[0][0]
        path_end = full_path[-1][1]

        # invlidate anything without a proper start and end point
        if start == path_start and end == path_end:
            # paths with a length of 1 immediately qualify
            if len(full_path) == 1:
                paths.append(['-'.join(str(j) for j in i) for i in path])
            else:
                # if we get through our entire path without breaking we qualify
                for i, cooard in enumerate(full_path[:-1]):
                    if cooard[1] != full_path[i + 1][0]:
                        break
                else:
                    # convert back to strings so we can use the keys
                    paths.append(['-'.join(str(j) for j in i) for i in path])

    return paths

start = 50
end = 84
data = {
    '50-52': 781445.0,
    '52-84': 56554260.0,
    '50-73': 31204670.0,
    '73-84': 39169560.0,
    '73-75' : 23123123.0,
    '75-84' : 2312322.0
}

print(get_paths(start, end, data))
</code>```

From here it would be easy to get the sum of the returned keys.

Title: Python decomposing a dict

Body:
I have a dict like

start = 50
end = 84
data = {
    '50-52': 781445.0,
    '52-84': 56554260.0,
    '50-73': 31204670.0,
    '73-84': 39169560.0,
    '73-75' : 23123123.0,
    '75-84' : 2312322.0
}

What I want to achieve?

I want to traverse all possible paths from start to end, eg: for the above example

>  x = data['50-52'] + data['52-84'] = 781445.0 + 56554260.0
>  y = data['50-73'] + data['73-84'] = 31204670.0 + 39169560.0
>  z = data['50-73'] + data['73-75'] + data['75-84'] = 31204670.0 + 23123123.0 + 2312322.0

and I would like to get a list of all possible paths from start to end that is [x, y, z]

I have sort of hit a dead end with the different ways I have been trying to approach this. I have tried to create new dict and update it with each iteration but the code seems to get very complex, any ideas on what approach I can take?

Thank you!

Body:
You could also brute force it with combinations.
I'm not sure how large your dict is but if you only need to compute it once or twice, here's a solution.

from itertools import combinations

def get_paths(start, end, all_paths):
    paths = []

    # this will produce a list of tuples of all the coordinates
    # convert to ints for sorting purposes
    cooards = [(int(i.split('-')[0]), int(i.split('-')[1])) for i in all_paths]

    # this produces a list of all possible combinations
    # of those coordinates
    # basically a list of all possible lengths
    # of all possible combinations for each length
    combs = [x for l in range(1, len(cooards) + 1) for x in combinations(cooards, l)]

    for path in combs:
        # sort the path so we can traverse it in order to see if
        # the end element matches the start of the next element
        full_path = sorted(path)

        path_start = full_path[0][0]
        path_end = full_path[-1][1]

        # invlidate anything without a proper start and end point
        if start == path_start and end == path_end:
            # paths with a length of 1 immediately qualify
            if len(full_path) == 1:
                paths.append(['-'.join(str(j) for j in i) for i in path])
            else:
                # if we get through our entire path without breaking we qualify
                for i, cooard in enumerate(full_path[:-1]):
                    if cooard[1] != full_path[i + 1][0]:
                        break
                else:
                    # convert back to strings so we can use the keys
                    paths.append(['-'.join(str(j) for j in i) for i in path])

    return paths

start = 50
end = 84
data = {
    '50-52': 781445.0,
    '52-84': 56554260.0,
    '50-73': 31204670.0,
    '73-84': 39169560.0,
    '73-75' : 23123123.0,
    '75-84' : 2312322.0
}

print(get_paths(start, end, data))

From here it would be easy to get the sum of the returned keys.


问:
Where is my output when debugging C code in Visual Studio Code?
I have a simple c program, with prints something to screen.
When I debug the program I can see the DEBUG CONSOLE, however as soon as I use fgets I don't see any output. Where does my program run when debugging using VS Code?

If I just run my compiled .exe, everything is printed as expected.

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

int main() {
  printf("Hello World!\n");
  printf("Enter your name\n");

  char name[100];
  // fgets(name, sizeof(name), stdin); // as soon as I uncomment this, no output is in the output console
  printf("You name %s", name);

  return 0;
}
</code>```

my launch.json:

```<code>{
  "version": "0.2.0",
  "configurations": [
    {
      "name": "(Windows) Launch",
      "type": "cppvsdbg",
      "request": "launch",
      "program": "${workspaceFolder}/app.exe",
      "args": [],
      "stopAtEntry": false,
      "cwd": "${workspaceFolder}",
      "environment": [],
      "externalConsole": false
    }
  ]
}
</code>```

答:
One solution may solve your issue.

How to configure tasks.json and launch.json from VSCode

You don't need to do any type of coding for this, just follow the steps:

Delete tasks.json and launch.json located in .vscode folder

Press F5 (debugging shortcut) again focusing on that C program file, you'll see something like:

Select your compiler which is GCC (since you're trying to debug a C program and ensure the compiler is installed into your system).

You'll be prompted to select a configuration (assuming selected option: GCC), you'll get launch.json created automatically by VSCode as shown below:

Note: Keep the preLaunchTask configuration in your mind (located at the bottom-most of the config).

As soon as you press F5 again (this time, for creation of tasks.json) you'll get something shown below, simply select Configure Tasks:

Now, you'll be redirected into tasks.json, edit the label to the name you've selected in § 4 (remember that name). In other words, launch's preLaunchTask and tasks' label should be the same. Process shown below:

And now, you can make a successful debug. A working example:

Body:
I have a simple c program, with prints something to screen.
When I debug the program I can see the DEBUG CONSOLE, however as soon as I use fgets I don't see any output. Where does my program run when debugging using VS Code?

If I just run my compiled .exe, everything is printed as expected.

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

int main() {
  printf("Hello World!\n");
  printf("Enter your name\n");

  char name[100];
  // fgets(name, sizeof(name), stdin); // as soon as I uncomment this, no output is in the output console
  printf("You name %s", name);

  return 0;
}

my launch.json:

{
  "version": "0.2.0",
  "configurations": [
    {
      "name": "(Windows) Launch",
      "type": "cppvsdbg",
      "request": "launch",
      "program": "${workspaceFolder}/app.exe",
      "args": [],
      "stopAtEntry": false,
      "cwd": "${workspaceFolder}",
      "environment": [],
      "externalConsole": false
    }
  ]
}


问:
Javascript. Pretty date with months and years
I got the below script to convert dates into pretty dates. It works perfectly
fine but only to a level of weeks. I need it to work fine for months and perhaps years to.

How can I modify this code to work?

```<code>function prettyDate(time) {

    var date = new Date((time || "").replace(/-/g,"/").replace(/[TZ]/g," ")),
        diff = (((new Date()).getTime() - date.getTime()) / 1000),
        day_diff = Math.floor(diff / 86400);

    if ( isNaN(day_diff) || day_diff < 0 || day_diff >= 31 ){

        return;

        }

    return day_diff == 0 && (
            diff < 60 && "just now" ||
            diff < 120 && "1 minute ago" ||
            diff < 3600 && Math.floor( diff / 60 ) + " minutes ago" ||
            diff < 7200 && "1 hour ago" ||
            diff < 86400 && Math.floor( diff / 3600 ) + " hours ago") ||
        day_diff == 1 && "Yesterday" ||
        day_diff < 7 && day_diff + " days ago" ||
        day_diff < 31 && Math.ceil( day_diff / 7 ) + " weeks ago";
}
</code>```

答:
I would look at this: http://ejohn.org/blog/javascript-pretty-date/.  Check the comments for some additional information.

See here: http://jsfiddle.net/MarkSchultheiss/cgMZz/1/

After a BIT more reading I see an update posted here:  http://www.zachleat.com/web/yet-another-pretty-date-javascript/ and finally moved to: https://github.com/zachleat/Humane-Dates   all credit to the coders!

Body:
I got the below script to convert dates into pretty dates. It works perfectly
fine but only to a level of weeks. I need it to work fine for months and perhaps years to.

How can I modify this code to work?

function prettyDate(time) {

    var date = new Date((time || "").replace(/-/g,"/").replace(/[TZ]/g," ")),
        diff = (((new Date()).getTime() - date.getTime()) / 1000),
        day_diff = Math.floor(diff / 86400);

    if ( isNaN(day_diff) || day_diff < 0 || day_diff >= 31 ){

        return;

        }

    return day_diff == 0 && (
            diff < 60 && "just now" ||
            diff < 120 && "1 minute ago" ||
            diff < 3600 && Math.floor( diff / 60 ) + " minutes ago" ||
            diff < 7200 && "1 hour ago" ||
            diff < 86400 && Math.floor( diff / 3600 ) + " hours ago") ||
        day_diff == 1 && "Yesterday" ||
        day_diff < 7 && day_diff + " days ago" ||
        day_diff < 31 && Math.ceil( day_diff / 7 ) + " weeks ago";
}


问:
v-model and child components?
I have a form and bind an input using v-model:

```<code><input type="text" name="name" v-model="form.name">
</code>```

Now I want to extract the input and make it it's own component, how do you then bind the values of the child component to the parents object form.name?

答:
Binding data to a custom checkbox or checkbox set is quite different from binding it to a text input:

https://www.smashingmagazine.com/2017/08/creating-custom-inputs-vue-js/

```<code><template>
  <label>
    <input type="checkbox" :checked="shouldBeChecked" :value="value" @change="updateInput">
    {{ label }}
  </label>
</template>
<script>
export default {
  model: {
    prop: 'modelValue',
    event: 'change',
  },
  props: {
    value: {
      type: String,
    },
    modelValue: {
      default: false,
    },
    label: {
      type: String,
      required: true,
    },
    // We set `true-value` and `false-value` to the default true and false so
    // we can always use them instead of checking whether or not they are set.
    // Also can use camelCase here, but hyphen-separating the attribute name
    // when using the component will still work
    trueValue: {
      default: true,
    },
    falseValue: {
      default: false,
    }
  },
  computed: {
    shouldBeChecked() {
      if (this.modelValue instanceof <span class="hljs-built_in">Array) {
        return this.modelValue.includes(this.value);
      }
      // Note that `true-value` and `false-value` are camelCase in the JS
      return this.modelValue === this.trueValue;
    }
  },
  methods: {
    updateInput(event) {
      let isChecked = event.target.checked;

      if (this.modelValue instanceof Array) {
        let newValue = [...this.modelValue];

        if (isChecked) {
          newValue.push(this.value);
        } else {
          newValue.splice(newValue.indexOf(this.value), 1);
        }

        this.$emit('change', newValue);
      } else {
        this.$emit('change', isChecked ? this.trueValue : this.falseValue);
      }
    }
  }
}
</script>
</code>```

Title: v-model and child components?

Body:
I have a form and bind an input using v-model:

<input type="text" name="name" v-model="form.name">

Now I want to extract the input and make it it's own component, how do you then bind the values of the child component to the parents object form.name?

Body:
Binding data to a custom checkbox or checkbox set is quite different from binding it to a text input:

https://www.smashingmagazine.com/2017/08/creating-custom-inputs-vue-js/

<template>
  <label>
    <input type="checkbox" :checked="shouldBeChecked" :value="value" @change="updateInput">
    {{ label }}
  </label>
</template>
<script>
export default {
  model: {
    prop: 'modelValue',
    event: 'change',
  },
  props: {
    value: {
      type: String,
    },
    modelValue: {
      default: false,
    },
    label: {
      type: String,
      required: true,
    },
    // We set `true-value` and `false-value` to the default true and false so
    // we can always use them instead of checking whether or not they are set.
    // Also can use camelCase here, but hyphen-separating the attribute name
    // when using the component will still work
    trueValue: {
      default: true,
    },
    falseValue: {
      default: false,
    }
  },
  computed: {
    shouldBeChecked() {
      if (this.modelValue instanceof <span class="hljs-built_in">Array) {
        return this.modelValue.includes(this.value);
      }
      // Note that `true-value` and `false-value` are camelCase in the JS
      return this.modelValue === this.trueValue;
    }
  },
  methods: {
    updateInput(event) {
      let isChecked = event.target.checked;

      if (this.modelValue instanceof Array) {
        let newValue = [...this.modelValue];

        if (isChecked) {
          newValue.push(this.value);
        } else {
          newValue.splice(newValue.indexOf(this.value), 1);
        }

        this.$emit('change', newValue);
      } else {
        this.$emit('change', isChecked ? this.trueValue : this.falseValue);
      }
    }
  }
}
</script>


问:
scope of variable in the angular 5
I know it's silly question but would like to know exact scope of variable of this.

I have tried following and if i make any changes in data, response is getting changed too.

I have tried following:

private response;
private data;

getdata() {
  this.service.getdata().subscribe((res: any) => {

    if (res) {
      this.response = res;
      this.data = res;
    }
  });
}
```

If i use data as input parameter for other component and make any changes on that, my this.response is also getting changed.

I am not sure what to do to retain the previous data.

答:
Its because both response and data are sharing the same object reference.

Your code within if condition is nothing but a shallow copy of each other

```<code>this.response = this.data = res;
</code>```

Hence when you change one value the other value also gets changed,

In order to avoid this from happening you can do the following

```<code>this.data = Object.assign({},res);
</code>```

OR

```<code>this.data = {...res}
</code>```

Read this for more details on shallow copy and deep copy

Title: scope of variable in the angular 5

Body:
I know it's silly question but would like to know exact scope of variable of this.

I have tried following and if i make any changes in data, response is getting changed too.

I have tried following:

private response;
private data;

getdata() {
  this.service.getdata().subscribe((res: any) => {

    if (res) {
      this.response = res;
      this.data = res;
    }
  });
}

If i use data as input parameter for other component and make any changes on that, my this.response is also getting changed.

I am not sure what to do to retain the previous data.

Body:
Its because both response and data are sharing the same object reference.

Your code within if condition is nothing but a shallow copy of each other

this.response = this.data = res;

Hence when you change one value the other value also gets changed,

In order to avoid this from happening you can do the following

this.data = Object.assign({},res);

OR

this.data = {...res}

Read this for more details on shallow copy and deep copy


问:
Email address regular expression, limited character before and after @ symbol
I have a regexp that check for valid email.

/^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;

how would I limit the number of character before @ to 64 and after @ to 64.

答:
Two options:

After your long regex test, do a second regex test for length:

/^.{1,64}@.{1,64}$)$/

Prefix a positive lookahead to your regex:

/(?=^.{1,64}@.{1,64}$)^(YOUR REGEX)$/


问:
Why does this line cause a boolean error?
```<code>len([True for i in a if any([any(j == b[:, 0]) for j in i])])
</code>```

This is my line of code. a is a multidimensional list and b is a nd.array. When I run it, it returns this error:

```<code>The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
</code>```

Even though I used any() at every place that is needed. Where's my mistake?

Edit: Values for the lists:

a = [[[[0, 0], [0, 0]]]]

b = np.array([[[[0, 0], [0, 0]], 0]])

答:
The problem is produced by:

any(j == b[:, 0])
```

<p>use:</p>

<pre class="lang-py prettyprint-override"><code>(j == b[:, 0]).any()
</code>```

instead. Same for the outer any(). Note that any() can take an iterable, which np_array.any() is a function from numpy.

Body:
len([True for i in a if any([any(j == b[:, 0]) for j in i])])

This is my line of code. a is a multidimensional list and b is a nd.array. When I run it, it returns this error:

The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

Even though I used any() at every place that is needed. Where's my mistake?

Edit: Values for the lists:

a = [[[[0, 0], [0, 0]]]]

b = np.array([[[[0, 0], [0, 0]], 0]])

Body:
The problem is produced by:

any(j == b[:, 0])

use:

(j == b[:, 0]).any()

instead. Same for the outer any(). Note that any() can take an iterable, which np_array.any() is a function from numpy.


问:
how to check if mongoose (MongoDb) is installed or not
I installed mongoose using

```<code>sudo npm install -g mongoose
</code>```

Please advice on how I can check to see if its installed properly. I am using Mac

答:
use npm list mongoose
if mongoose is not installed you will get this respose
`-- (empty)</p>

Body:
I installed mongoose using

sudo npm install -g mongoose

Please advice on how I can check to see if its installed properly. I am using Mac


问:
Sample among any axis on a numpy array
I have the following piece of code:

```<code>if axis == 0:
    return m[idx, :]
elif axis == 1:
    return m[:, idx]
else:
    raise('Argument axis currently accepts only values 0 and 1.')
</code>```

How to generalize this behaviour for any shape and any value of axis?

答:
I found the answer:</p>

```<code>return np.take(m, idx, axis=axis)
</code>```

Title: Sample among any axis on a numpy array

Body:
I have the following piece of code:

if axis == 0:
    return m[idx, :]
elif axis == 1:
    return m[:, idx]
else:
    raise('Argument axis currently accepts only values 0 and 1.')

How to generalize this behaviour for any shape and any value of axis?

Body:
I found the answer:

return np.take(m, idx, axis=axis)


问:
How can i fix this java.io.NotSerializableException: error in java?
I'm quite new to java and unsure how to fix this java.io.NotSerializableException error.

I'm trying to use an add button on the GUI to add an object to an array list
Then write that object to a file so I am able to read it back.

Here is the code I'm using for the Branch class which implement Java Serializable:

import java.io.Serializable;

public class Branch implements Serializable{
    private String branch_name;
    private String branch_address;

    public Branch(String Bname, String Baddress) {
        this.branch_name = Bname;
        this.branch_address = Baddress;

        public String getbranch_name(){
            return branch_name;
        }

        public String getbranch_address(){
            return branch_address;
        }

        public void show_branch_details() {
            System.out.println( " The branch name is : " + getbranch_name()
                    + " branch address :"+ getbranch_address()
        }
    }
}
```

<p>Here is the code for the add button:</p>

<pre class="lang-java prettyprint-override"><code>ArrayList<Branch> BranchList = new ArrayList<Branch>();
JButton AddBranch = new JButton("ADD BRANCH");
AddBranch.setBounds(10, 35, 161, 23);
AddBranch.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent e) {
        String Bname = branchNameField.getText();
        String Baddress = branchAddressField.getText();

        Branch A = new Branch(Bname, Baddress);

        BranchList.add(A);

        for (int i = 0; i < BranchList.size(); i++) {
            displayInfo.append(BranchList.get(i).getbranch_name() +);
        }
        System.out.println("The ArrayList has " + BranchList.size());
        for (int i = 0; i < BranchList.size(); i++) {
            System.out.println(BranchList.get(i).getbranch_name());
        }
        try {
            FileOutputStream fos = new FileOutputStream("branch.dat");
            ObjectOutputStream oos = new ObjectOutputStream(fos);
            //oos.writeObject(BranchList);
            for (int b = 0; b < BranchList.size(); b++) {
                oos.writeObject(BranchList.get(b));
            }
            oos.flush();
            oos.close();

            FileInputStream fis = new FileInputStream("branch.dat");
            ObjectInputStream ois = new ObjectInputStream(fis);
            //BranchList = (ArrayList<Branch>)ois.readObject();
            Branch obj = null;

            while ((obj = (Branch) ois.readObject()) != null) {
                System.out.println("Name:" + obj.getbranch_name() + ", Address:"
                        + obj.getbranch_address());
            }
            ois.close();
        } catch (IOException ex) {
            System.out.println(" IOE ERROR");
            ex.printStackTrace();
        } catch (ClassNotFoundException ex) {
            System.out.println("class ERROR");
            ex.printStackTrace();
        }
    }
});
</code>```

答:
Please use this as Branch class :</p>

```<code>        import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.util.ArrayList;

    class Branch implements Serializable{

        private String branch_name;
        private String branch_address;

        public Branch(String Bname, String Baddress) {
            this.branch_name = Bname;
            this.branch_address = Baddress;
        }
            public String getbranch_name(){
                return branch_name;
            }

            public String getbranch_address(){
                return branch_address;
            }

            public void show_branch_details() {
                System.out.println( " The branch name is : " + getbranch_name()
                        + " branch address :"+ getbranch_address());
            }

        }

    public class Test {

        public static void main(String[] args) throws IOException, ClassNotFoundException {

            Branch A= new Branch("TestA","Add_A");
            Branch B= new Branch("TestB","Add_B");

            ArrayList<Branch> BranchList = new ArrayList<>();
            BranchList.add(A);
            BranchList.add(B);

            FileOutputStream fos = new FileOutputStream("branch.dat");
            ObjectOutputStream oos = new ObjectOutputStream(fos);
            oos.writeObject(BranchList);
            oos.flush();
            oos.close();

            ArrayList<Branch> OutputBranchList = new ArrayList<>();
            FileInputStream fis = new FileInputStream("branch.dat");
            ObjectInputStream ois = new ObjectInputStream(fis);
            OutputBranchList = (ArrayList) ois.readObject();

            for(Branch branch : OutputBranchList) {
                System.out.println(branch.getbranch_name()+" "+ branch.getbranch_address());
            }
            ois.close();
        }
    }
</code>```

Body:
I'm quite new to java and unsure how to fix this java.io.NotSerializableException error.

I'm trying to use an add button on the GUI to add an object to an array list
Then write that object to a file so I am able to read it back.

Here is the code I'm using for the Branch class which implement Java Serializable:

import java.io.Serializable;

public class Branch implements Serializable{
    private String branch_name;
    private String branch_address;

    public Branch(String Bname, String Baddress) {
        this.branch_name = Bname;
        this.branch_address = Baddress;

        public String getbranch_name(){
            return branch_name;
        }

        public String getbranch_address(){
            return branch_address;
        }

        public void show_branch_details() {
            System.out.println( " The branch name is : " + getbranch_name()
                    + " branch address :"+ getbranch_address()
        }
    }
}

Here is the code for the add button:

ArrayList<Branch> BranchList = new ArrayList<Branch>();
JButton AddBranch = new JButton("ADD BRANCH");
AddBranch.setBounds(10, 35, 161, 23);
AddBranch.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent e) {
        String Bname = branchNameField.getText();
        String Baddress = branchAddressField.getText();

        Branch A = new Branch(Bname, Baddress);

        BranchList.add(A);

        for (int i = 0; i < BranchList.size(); i++) {
            displayInfo.append(BranchList.get(i).getbranch_name() +);
        }
        System.out.println("The ArrayList has " + BranchList.size());
        for (int i = 0; i < BranchList.size(); i++) {
            System.out.println(BranchList.get(i).getbranch_name());
        }
        try {
            FileOutputStream fos = new FileOutputStream("branch.dat");
            ObjectOutputStream oos = new ObjectOutputStream(fos);
            //oos.writeObject(BranchList);
            for (int b = 0; b < BranchList.size(); b++) {
                oos.writeObject(BranchList.get(b));
            }
            oos.flush();
            oos.close();

            FileInputStream fis = new FileInputStream("branch.dat");
            ObjectInputStream ois = new ObjectInputStream(fis);
            //BranchList = (ArrayList<Branch>)ois.readObject();
            Branch obj = null;

            while ((obj = (Branch) ois.readObject()) != null) {
                System.out.println("Name:" + obj.getbranch_name() + ", Address:"
                        + obj.getbranch_address());
            }
            ois.close();
        } catch (IOException ex) {
            System.out.println(" IOE ERROR");
            ex.printStackTrace();
        } catch (ClassNotFoundException ex) {
            System.out.println("class ERROR");
            ex.printStackTrace();
        }
    }
});

Body:
Please use this as Branch class :

        import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.util.ArrayList;

    class Branch implements Serializable{

        private String branch_name;
        private String branch_address;

        public Branch(String Bname, String Baddress) {
            this.branch_name = Bname;
            this.branch_address = Baddress;
        }
            public String getbranch_name(){
                return branch_name;
            }

            public String getbranch_address(){
                return branch_address;
            }

            public void show_branch_details() {
                System.out.println( " The branch name is : " + getbranch_name()
                        + " branch address :"+ getbranch_address());
            }

        }

    public class Test {

        public static void main(String[] args) throws IOException, ClassNotFoundException {

            Branch A= new Branch("TestA","Add_A");
            Branch B= new Branch("TestB","Add_B");

            ArrayList<Branch> BranchList = new ArrayList<>();
            BranchList.add(A);
            BranchList.add(B);

            FileOutputStream fos = new FileOutputStream("branch.dat");
            ObjectOutputStream oos = new ObjectOutputStream(fos);
            oos.writeObject(BranchList);
            oos.flush();
            oos.close();

            ArrayList<Branch> OutputBranchList = new ArrayList<>();
            FileInputStream fis = new FileInputStream("branch.dat");
            ObjectInputStream ois = new ObjectInputStream(fis);
            OutputBranchList = (ArrayList) ois.readObject();

            for(Branch branch : OutputBranchList) {
                System.out.println(branch.getbranch_name()+" "+ branch.getbranch_address());
            }
            ois.close();
        }
    }


问:
how to upload a file and process it with single button click in JSP
Previously in my UI, i had "Upload" button to upload the file to server after browsing the file. And then enter password in the password field and click on "Run" button to proceess the file. It was working fine.

Now the requirement changed as, no "Upload" button should be there. only "Run" button should be there.

Means, once after browsing the file and entering the password in "Password" field and click on the "Run" button, the file should get uploaded to the server first and then the file have to process as well.

I tried to move the 'upload()' function codes to 'run()' function, but it works only if there is a delay. like if there is a alert message then it works fine or else before file being uploaded the run button is trying to process the file and ends in error.
Tried Thread.sleep(5000); as well not working

```<code>/* function upload() {
        document.getElementById("messageDiv").innerHTML = "";
        var file = window.document.forms[0].file.value;
        if (file == "") {
            alert("Select a file to upload!!");
        } else {
            window.document.forms[0].action = "<%=request.getContextPath()%>/FileUpload.do?Action=Upload";
            window.document.forms[0].submit();
        }
    }*/

function runButton(){
        document.getElementById("messageDiv").innerHTML = "";
        var file = window.document.forms[0].file.value;
        if (file == "") {
            alert("Select a file to upload!!");
        } else {
            window.document.forms[0].action = "<%=request.getContextPath()%>/FileUpload.do?Action=Upload";  //FileUploadServlet"; //
            window.document.forms[0].submit();
        }
        /* alert(" Upload Completed, Next runButton!! "); */ ** ---> if this is uncommented then works fine. **
        window.document.forms[0].action="<%=request.getContextPath()%>/FileUpload.do?Action=Run";
            var passwd = window.document.forms[0].passwd.value;

            if (passwd == null || passwd == "") {
                alert(" Password cannot be empty!! ");
            } else {
                window.document.forms[0].submit();
                window.document.forms[0].passwd.value='';
            }
            document.getElementById("messageDiv").innerHTML = "";
    }
</code>```

Suggestions pls

答: I've completed it by having all the processes with "Upload" button itself.</p>

Body:
Previously in my UI, i had "Upload" button to upload the file to server after browsing the file. And then enter password in the password field and click on "Run" button to proceess the file. It was working fine.

Now the requirement changed as, no "Upload" button should be there. only "Run" button should be there.

Means, once after browsing the file and entering the password in "Password" field and click on the "Run" button, the file should get uploaded to the server first and then the file have to process as well.

I tried to move the 'upload()' function codes to 'run()' function, but it works only if there is a delay. like if there is a alert message then it works fine or else before file being uploaded the run button is trying to process the file and ends in error.
Tried Thread.sleep(5000); as well not working

/* function upload() {
        document.getElementById("messageDiv").innerHTML = "";
        var file = window.document.forms[0].file.value;
        if (file == "") {
            alert("Select a file to upload!!");
        } else {
            window.document.forms[0].action = "<%=request.getContextPath()%>/FileUpload.do?Action=Upload";
            window.document.forms[0].submit();
        }
    }*/

function runButton(){
        document.getElementById("messageDiv").innerHTML = "";
        var file = window.document.forms[0].file.value;
        if (file == "") {
            alert("Select a file to upload!!");
        } else {
            window.document.forms[0].action = "<%=request.getContextPath()%>/FileUpload.do?Action=Upload";  //FileUploadServlet"; //
            window.document.forms[0].submit();
        }
        /* alert(" Upload Completed, Next runButton!! "); */ ** ---> if this is uncommented then works fine. **
        window.document.forms[0].action="<%=request.getContextPath()%>/FileUpload.do?Action=Run";
            var passwd = window.document.forms[0].passwd.value;

            if (passwd == null || passwd == "") {
                alert(" Password cannot be empty!! ");
            } else {
                window.document.forms[0].submit();
                window.document.forms[0].passwd.value='';
            }
            document.getElementById("messageDiv").innerHTML = "";
    }

Suggestions pls


问:
Google Coral Dev board vs Asus Tinker Edge T
Does this:
https://www.asus.com/gr/AIoT-Industrial-Solutions/Tinker-Edge-T/
have any difference with this:
https://coral.ai/products/dev-board/
?? For example can I train a custom CNN? Has anyone experience to give an advice? I want to buy a SBC with TPU in order to train a CNN faster but the information I found on google do not help...</p>

答:
The asus Tinker Edge T actually have the same edgetpu that is on the dev board. I believe the SOM is exactly the same and only the base board are different.
The edgetpu are targeted for inferencing only, not training, so you probably won't profit from it. However, you can take advantage of fast inference time to do things like backprop which allows you to do some transfer learning:
https://coral.ai/docs/edgetpu/retrain-classification-ondevice-backprop/</p>


问:
Supply value for a parameter in powershell
I would like to incorporate this function in my script and So I am trying to define the $target parameter with an IP so the script doesn't prompt for a target ip and it automatically executes with the IP thats defined in the script. I tried what is below but its obviously not working. </p>

```<code>[CmdletBinding()]
  param(
  [Parameter(Mandatory=$True,ValueFromPipeline=$True)]
  [String] $target= "8.8.8.8",
</code>```

答:
The issue is you have a Parameter using Mandatory=$True

If Mandatory=$True then it will always ask for that value even if you have a optional value used.

The fix would be

```<code>[Parameter(ValueFromPipeline=$True)]
[String] $target= "8.8.8.8",
</code>```

Body:
I would like to incorporate this function in my script and So I am trying to define the $target parameter with an IP so the script doesn't prompt for a target ip and it automatically executes with the IP thats defined in the script. I tried what is below but its obviously not working.

[CmdletBinding()]
  param(
  [Parameter(Mandatory=$True,ValueFromPipeline=$True)]
  [String] $target= "8.8.8.8",

Body:
The issue is you have a Parameter using Mandatory=$True

If Mandatory=$True then it will always ask for that value even if you have a optional value used.

The fix would be

[Parameter(ValueFromPipeline=$True)]
[String] $target= "8.8.8.8",


问:
rake task says "define INLINEDIR or HOME in your environment and try again, how do i fix this?
I am running a rake task in rails 2
I have it called from an /etc/init.d/ ruby script.

at start up it tells me
define INLINEDIR or HOME  in your environment and try again
It works fine once I Log in, but not if I run unset home first

it doesn't matter what task I try to call it says that no matter what.

While I could define HOME in that file, I don't know what INLINEDIR is and if I should do that instead, or why this matters in the first place..
Has anyone encountered this problem, know more about it and can point me in the right direction?

答:
i had to add a ENV["HOME"] = '/root' line into the calling script and it worked fine

very odd, found no reason what caused this or anything


问:
How to call a function after other function in angular 8
I have 2 functions one func1 and func2, I need to execute the func2 only after func1 will execute. Here the code below

home.component.ts

```<code>import { Component, OnInit } from '@angular/core';
@Component({
  selector: 'app-home',
  templateUrl: './home.component.html',
  styleUrls: ['./home.component.css']
})

export class HomeComponent implements OnInit {

 constructor() { }

 ngOnInit() {
    this.func1();
    this.func2();
 }

 func1(){
    console.log('function1')
 }

 func2(){
    console.log('function2')
 }
}
</code>```

答:
I think, this will solve your problem.</p>

```<code>import { Component, OnInit } from '@angular/core';
@Component({
  selector: 'app-home',
  templateUrl: './home.component.html',
  styleUrls: ['./home.component.css']
})

export class HomeComponent implements OnInit {

 constructor() { }

 ngOnInit() {
    this.func1();
 }

 func1(){
    console.log('function1')
    this.func2();
 }

 func2(){
    console.log('function2')
 }
}
</code>```

Body:
I have 2 functions one func1 and func2, I need to execute the func2 only after func1 will execute. Here the code below

home.component.ts

import { Component, OnInit } from '@angular/core';
@Component({
  selector: 'app-home',
  templateUrl: './home.component.html',
  styleUrls: ['./home.component.css']
})

export class HomeComponent implements OnInit {

 constructor() { }

 ngOnInit() {
    this.func1();
    this.func2();
 }

 func1(){
    console.log('function1')
 }

 func2(){
    console.log('function2')
 }
}

Body:
I think, this will solve your problem.

import { Component, OnInit } from '@angular/core';
@Component({
  selector: 'app-home',
  templateUrl: './home.component.html',
  styleUrls: ['./home.component.css']
})

export class HomeComponent implements OnInit {

 constructor() { }

 ngOnInit() {
    this.func1();
 }

 func1(){
    console.log('function1')
    this.func2();
 }

 func2(){
    console.log('function2')
 }
}


问:
Flutter/Dart group list by date
I have following list of maps,

```<code>[
   {
      "FullName":"Harry Potter",
      "DateOfBirth": "2020/02/16",
      "Department":"Branch Operation",
      "BirthDay":"Friday"
   },
   {
      "FullName":"John Wick",
      "DateOfBirth": "2020/02/16",
      "Department":"Finance",
      "BirthDay":"Friday"
   },
   {
      "FullName":"Solomon Kane",
      "DateOfBirth":2020/02/19,
      "Department":"Loan",
      "BirthDay":"Monday"
   }
]
</code>```

I would like to manipulate above data such that data are grouped by their DateOfBirth, so that result would look like this.

```<code>[
   {
      "DateOfBirth": "2020/02/16",
      "BirthDay": "Friday",
      "Data":[
         {
            "FullName": "Harry Potter",
            "Department":"Branch Operation",
         },
         {
            "FullName":"John Wick",
            "Department":"Finance",
         }
      ]
   },
   {
      "DateOfBirth": "2020/02/19",
      "BirthDay": "Monday",
      "Data":[
         {
            "FullName":"Solomon Kane",
            "Department":"Loan"
         }
      ]
   },
]
</code>```

In Javascript, this can be achieved by using reduce function and then using Object key mapping.
I also know dart has useful package called  collection

As I am new to dart and flutter, I am not sure how to do. Can anybody help me on this?

Thanks

答:
You could use fold and do something like this

```<code>const data = [...];

void main() {
 final value = data.fold(Map<String, List<dynamic>>(), (Map<String, List<dynamic>> a, b) {
   a.putIfAbsent(b['DateOfBirth'], () => []).add(b);
   return a;
 }).values
   .where((l) => l.isNotEmpty)
   .map((l) => {
     'DateOfBirth': l.first['DateOfBirth'],
     'BirthDay': l.first['BirthDay'],
     'Data': l.map((e) => {
       'Department': e['Department'],
       'FullName': e['FullName'],
     }).toList()
 }).toList();
}
</code>```

Or like this if you want to use the spread operator, I don't know if its very readable though.

```<code> final result = data.fold({}, (a, b) => {
     ...a,
     b['DateOfBirth']: [b, ...?a[b['DateOfBirth']]],
 }).values
   .where((l) => l.isNotEmpty)
   .map((l) => {
     'DateOfBirth': l.first['DateOfBirth'],
     'BirthDay': l.first['BirthDay'],
     'Data': l.map((e) => {
       'Department': e['Department'],
       'FullName': e['FullName'],
     }).toList()
 }).toList();
</code>```

Title: Flutter/Dart group list by date

Body:
I have following list of maps,

[
   {
      "FullName":"Harry Potter",
      "DateOfBirth": "2020/02/16",
      "Department":"Branch Operation",
      "BirthDay":"Friday"
   },
   {
      "FullName":"John Wick",
      "DateOfBirth": "2020/02/16",
      "Department":"Finance",
      "BirthDay":"Friday"
   },
   {
      "FullName":"Solomon Kane",
      "DateOfBirth":2020/02/19,
      "Department":"Loan",
      "BirthDay":"Monday"
   }
]

I would like to manipulate above data such that data are grouped by their DateOfBirth, so that result would look like this.

[
   {
      "DateOfBirth": "2020/02/16",
      "BirthDay": "Friday",
      "Data":[
         {
            "FullName": "Harry Potter",
            "Department":"Branch Operation",
         },
         {
            "FullName":"John Wick",
            "Department":"Finance",
         }
      ]
   },
   {
      "DateOfBirth": "2020/02/19",
      "BirthDay": "Monday",
      "Data":[
         {
            "FullName":"Solomon Kane",
            "Department":"Loan"
         }
      ]
   },
]

In Javascript, this can be achieved by using reduce function and then using Object key mapping.
I also know dart has useful package called  collection

As I am new to dart and flutter, I am not sure how to do. Can anybody help me on this?

Thanks

Body:
You could use fold and do something like this

const data = [...];

void main() {
 final value = data.fold(Map<String, List<dynamic>>(), (Map<String, List<dynamic>> a, b) {
   a.putIfAbsent(b['DateOfBirth'], () => []).add(b);
   return a;
 }).values
   .where((l) => l.isNotEmpty)
   .map((l) => {
     'DateOfBirth': l.first['DateOfBirth'],
     'BirthDay': l.first['BirthDay'],
     'Data': l.map((e) => {
       'Department': e['Department'],
       'FullName': e['FullName'],
     }).toList()
 }).toList();
}

Or like this if you want to use the spread operator, I don't know if its very readable though.

 final result = data.fold({}, (a, b) => {
     ...a,
     b['DateOfBirth']: [b, ...?a[b['DateOfBirth']]],
 }).values
   .where((l) => l.isNotEmpty)
   .map((l) => {
     'DateOfBirth': l.first['DateOfBirth'],
     'BirthDay': l.first['BirthDay'],
     'Data': l.map((e) => {
       'Department': e['Department'],
       'FullName': e['FullName'],
     }).toList()
 }).toList();