问:
Cannot authenticate to Firebase API
I'm trying to configure firebase API to be used with my nativescript application.
In fact, i don't know how to configure it anymore.

I have my private keystore and another one (managed by google) in my Google Play Console.
Which one fingerprint should i use on Firebase Console?
Tried both separated and together too.

In app still receiving:
'Make sure you\'ve uploaded your SHA1 fingerprint(s) to the Firebase console. Status: Status{statusCode=DEVELOPER_ERROR, resolution=null}'
error message.

Any tips?

Edit:
Added two fingerprints, updated google-services.json and still not working.
Firebase Console Config

答:
Done!

I was wrong.

There are three types of keystores.

Upload keystore - this one we are using for building production app.

Signing keystore - (might be) maintained by google for in-store application signing.
and...

...drums.vaw...

Debug keystore - created during the installation of Google SDK, used for... yes, you know for what purpose. It is located in ~/.android/debug.keystore, password is android.

Clue was to retrieve SHA-1 fingerprint from debug keystore.

Title: Cannot authenticate to Firebase API


来源: stackexchange

问:
Trying selectively redraw background for an android game, but the moving image is duplicated across the screen
It's easiest if I just start by showing pictures of the problem. The pictures show a snapshot of a texture moving around.

The application on my HTC Hero:

The same application on the emulator where it works fine (Disregard the randomly placed leftovers, I know the cause of them, and it's not a problem):

Now, if you look at the first image, the top one is the "real one" and the others always follow beneath, and there are copies above aswell. I am currently only repainting the background squares that was visited, and they are for some reason drawn above the copies (you can see they are all partially painted over by a tile).

Do you have to always repaint the whole screen every frame on the android phones? Or is it possible to get rid of these weird copies?

Here is the code used to draw the textures (I'm new to opengl-es so it's a lot like replica island):

first

```<code>public static void beginDrawing(GL10 gl, float viewWidth, float viewHeight) {
    gl.glShadeModel(GL10.GL_FLAT);
    gl.glEnable(GL10.GL_BLEND);
    gl.glBlendFunc(GL10.GL_ONE, GL10.GL_ONE_MINUS_SRC_ALPHA);
    gl.glColor4x(0x10000, 0x10000, 0x10000, 0x10000);

    gl.glMatrixMode(GL10.GL_PROJECTION);
    gl.glPushMatrix();
    gl.glLoadIdentity();
    gl.glOrthof(0.0f, viewWidth, 0.0f, viewHeight, 0.0f, 1.0f);
    gl.glMatrixMode(GL10.GL_MODELVIEW);
    gl.glPushMatrix();
    gl.glLoadIdentity();

    gl.glEnable(GL10.GL_TEXTURE_2D);
}
</code>```

Then for every texture (I draw background first, then in this case only one hulk texture. I'm sure it's being drawn only once):

```<code>        gl.glBindTexture(GL10.GL_TEXTURE_2D, textureID);
        ((GL11Ext) gl).glDrawTexfOES(x, y, 0, (float) mWidth, (float) mHeight);
</code>```

and at the end:

```<code>public static void endDrawing(GL10 gl) {
    gl.glDisable(GL10.GL_BLEND);
    gl.glMatrixMode(GL10.GL_PROJECTION);
    gl.glPopMatrix();
    gl.glMatrixMode(GL10.GL_MODELVIEW);
    gl.glPopMatrix();
}
</code>```

The code I use to load textures:

```<code>private void loadGLTextures(GL10 gl) {
    int[] textures = new int[1];
    gl.glGenTextures(1, textures, 0);
    textureID = textures[0];

    gl.glBindTexture(GL10.GL_TEXTURE_2D, textureID);

    gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_MIN_FILTER,
            GL10.GL_LINEAR);
    gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_MAG_FILTER,
            GL10.GL_LINEAR);

    gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_WRAP_S,
            GL10.GL_CLAMP_TO_EDGE);
    gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_WRAP_T,
            GL10.GL_CLAMP_TO_EDGE);
    gl.glTexEnvf(GL10.GL_TEXTURE_ENV, GL10.GL_TEXTURE_ENV_MODE,
            GL10.GL_MODULATE);

    GLUtils.texImage2D(GL10.GL_TEXTURE_2D, 0, bitmap, 0);
    int[] mCropWorkspace = new int[4];
    mCropWorkspace[0] = 0;
    mCropWorkspace[1] = bitmap.getHeight();
    mCropWorkspace[2] = bitmap.getWidth();
    mCropWorkspace[3] = -bitmap.getHeight();
    ((GL11) gl).glTexParameteriv(GL10.GL_TEXTURE_2D,
            GL11Ext.GL_TEXTURE_CROP_RECT_OES,
            mCropWorkspace,
            0);
    mCrop = mCropWorkspace;
    bitmap.recycle();
}
</code>```

All help is very much appriciated, and please leave a comment if anything is unclear!

EDIT: I should add that if I every frame redraw all the squares, the "extra" images are hidden, and it works the way it should.

答: May I know where exactly you clear the previously visited square. It is definitely possible to update just the dirty potion. But assuming you are coding with android, it maintains two buffers where swapping happens internally. In that case, you must see to that you clear the area where the image was drawn 2 frames back. </p>

ContentLicense: CC BY-SA 3.0

Body:
It's easiest if I just start by showing pictures of the problem. The pictures show a snapshot of a texture moving around.

The application on my HTC Hero:

The same application on the emulator where it works fine (Disregard the randomly placed leftovers, I know the cause of them, and it's not a problem):

Now, if you look at the first image, the top one is the "real one" and the others always follow beneath, and there are copies above aswell. I am currently only repainting the background squares that was visited, and they are for some reason drawn above the copies (you can see they are all partially painted over by a tile).

Do you have to always repaint the whole screen every frame on the android phones? Or is it possible to get rid of these weird copies?

Here is the code used to draw the textures (I'm new to opengl-es so it's a lot like replica island):

first

public static void beginDrawing(GL10 gl, float viewWidth, float viewHeight) {
    gl.glShadeModel(GL10.GL_FLAT);
    gl.glEnable(GL10.GL_BLEND);
    gl.glBlendFunc(GL10.GL_ONE, GL10.GL_ONE_MINUS_SRC_ALPHA);
    gl.glColor4x(0x10000, 0x10000, 0x10000, 0x10000);

    gl.glMatrixMode(GL10.GL_PROJECTION);
    gl.glPushMatrix();
    gl.glLoadIdentity();
    gl.glOrthof(0.0f, viewWidth, 0.0f, viewHeight, 0.0f, 1.0f);
    gl.glMatrixMode(GL10.GL_MODELVIEW);
    gl.glPushMatrix();
    gl.glLoadIdentity();

    gl.glEnable(GL10.GL_TEXTURE_2D);
}

Then for every texture (I draw background first, then in this case only one hulk texture. I'm sure it's being drawn only once):

        gl.glBindTexture(GL10.GL_TEXTURE_2D, textureID);
        ((GL11Ext) gl).glDrawTexfOES(x, y, 0, (float) mWidth, (float) mHeight);

and at the end:

public static void endDrawing(GL10 gl) {
    gl.glDisable(GL10.GL_BLEND);
    gl.glMatrixMode(GL10.GL_PROJECTION);
    gl.glPopMatrix();
    gl.glMatrixMode(GL10.GL_MODELVIEW);
    gl.glPopMatrix();
}

The code I use to load textures:

private void loadGLTextures(GL10 gl) {
    int[] textures = new int[1];
    gl.glGenTextures(1, textures, 0);
    textureID = textures[0];

    gl.glBindTexture(GL10.GL_TEXTURE_2D, textureID);

    gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_MIN_FILTER,
            GL10.GL_LINEAR);
    gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_MAG_FILTER,
            GL10.GL_LINEAR);

    gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_WRAP_S,
            GL10.GL_CLAMP_TO_EDGE);
    gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_WRAP_T,
            GL10.GL_CLAMP_TO_EDGE);
    gl.glTexEnvf(GL10.GL_TEXTURE_ENV, GL10.GL_TEXTURE_ENV_MODE,
            GL10.GL_MODULATE);

    GLUtils.texImage2D(GL10.GL_TEXTURE_2D, 0, bitmap, 0);
    int[] mCropWorkspace = new int[4];
    mCropWorkspace[0] = 0;
    mCropWorkspace[1] = bitmap.getHeight();
    mCropWorkspace[2] = bitmap.getWidth();
    mCropWorkspace[3] = -bitmap.getHeight();
    ((GL11) gl).glTexParameteriv(GL10.GL_TEXTURE_2D,
            GL11Ext.GL_TEXTURE_CROP_RECT_OES,
            mCropWorkspace,
            0);
    mCrop = mCropWorkspace;
    bitmap.recycle();
}

All help is very much appriciated, and please leave a comment if anything is unclear!

EDIT: I should add that if I every frame redraw all the squares, the "extra" images are hidden, and it works the way it should.


ContentLicense: CC BY-SA 4.0

Title: How to get out of while loop at the end of String in c#

Body:
I have a String which is mentioned below i am extracting a 2D array from this string (which i am doing successfully) The problem is that I dont know how to exit the while loop.

00000000,00000000,10100111,10100101,11111101,11111111,00000111,00000000,
00000000,00000000,11100010,00100010,11111111,11111111,00000000,10000000,
00000000,00000000,00001001,00001000,00111111,00111111,00000000,00000000,
00100000,00100000,10101110,10100010,10111110,10111110,00000000,00001000,
00000000,00111000,00100011,01111110,01111111,01000011,01000000,01111000,
00000000,00000000,00000000,00000000,00000000,00000000,00000000,00000000,
00000000,00000000,00000000,00000000,00000000,00000000,00000000,00000000,

I tried to put "x" at the end of string  and ran my while loop like this and it works but Its not feasible for me beacuase I have to read this string from like hundreds of files.

while (Data_string[counter] !=  'x' )
{
    while (Data_string[counter] != ',')
    {
        if (Data_string[counter] != '\n')
            SubString += Data_string[counter];

        counter++;
    }
    // here I use Substring to covert to int and then set Substring to empty string
}

So I am looking for an efficient solution so i dont have to alter the string,

Thanks..

Body:
This is how I would approach:

class Program
{
    static void Main(string[] args)
    {
        string str = "00000000,00000000,10100111,10100101,11111101,11111111,00000111,00000000, 00000000,00000000,11100010,00100010,11111111,11111111,00000000,10000000, 00000000,00000000,00001001,00001000,00111111,00111111,00000000,00000000, 00100000,00100000,10101110,10100010,10111110,10111110,00000000,00001000, 00000000,00111000,00100011,01111110,01111111,01000011,01000000,01111000, 00000000,00000000,00000000,00000000,00000000,00000000,00000000,00000000, 00000000,00000000,00000000,00000000,00000000,00000000,00000000,00000000,";

        string[] codes = str.Split(',');
    }
}

You don't need a  while loop at all.

If you want to handle cases of blank data there are some approaches:

class Program
{
    static void Main(string[] args)
    {
        string str = "00000000,00000000,10100111,10100101,11111101,11111111,00000111,00000000, 00000000,00000000,11100010,00100010,11111111,11111111,00000000,10000000, 00000000,00000000,00001001,00001000,00111111,00111111,00000000,00000000, 00100000,00100000,10101110,10100010,10111110,10111110,00000000,00001000, 00000000,00111000,00100011,01111110,01111111,01000011,01000000,01111000, 00000000,00000000,00000000,00000000,00000000,00000000,00000000,00000000, 00000000,00000000,00000000,00000000,00000000,00000000,00000000,00000000,";

        string[] codes = str.Split(new string[] { "," }, StringSplitOptions.RemoveEmptyEntries);
    }
}

class Program
{
    static void Main(string[] args)
    {
        string str = "00000000,00000000,10100111,10100101,11111101,11111111,00000111,00000000, 00000000,00000000,11100010,00100010,11111111,11111111,00000000,10000000, 00000000,00000000,00001001,00001000,00111111,00111111,00000000,00000000, 00100000,00100000,10101110,10100010,10111110,10111110,00000000,00001000, 00000000,00111000,00100011,01111110,01111111,01000011,01000000,01111000, 00000000,00000000,00000000,00000000,00000000,00000000,00000000,00000000, 00000000,00000000,00000000,00000000,00000000,00000000,00000000,00000000,";

        string[] codes = str.Split(',').Where(x => string.IsNullOrEmpty(x) == false).ToArray();
    }
}

class Program
{
    static void Main(string[] args)
    {
        string str = "00000000,00000000,10100111,10100101,11111101,11111111,00000111,00000000, 00000000,00000000,11100010,00100010,11111111,11111111,00000000,10000000, 00000000,00000000,00001001,00001000,00111111,00111111,00000000,00000000, 00100000,00100000,10101110,10100010,10111110,10111110,00000000,00001000, 00000000,00111000,00100011,01111110,01111111,01000011,01000000,01111000, 00000000,00000000,00000000,00000000,00000000,00000000,00000000,00000000, 00000000,00000000,00000000,00000000,00000000,00000000,00000000,00000000,";

        List<string> codes = str.Split(',').ToList();

        codes.RemoveAll(x => string.IsNullOrEmpty(x));
    }
}


问:
Sort part of an array of array structs C#
I'd like to sort part of an array of array of structs in C#. I don't want to implement the IComparer interface as that seems to involve boxing and there doesn't seem to be a proper Array.Sort variant that would let me define a lambda expression to compare two elements.

My struct:

```<code>    private struct ActionChainBlock
    {
        public int optionIndex;
        public Vector2I target;
        public int fitness;
    }
</code>```

My array:

```<code>    private readonly ActionChainBlock[][] chains;
</code>```

My code thus far:

```<code>        System.Array.Sort(chains, (x, y) =>
        {
            var xFitness = CalculateFitnessSum(x);
            var yFitness = CalculateFitnessSum(y);

            return -xFitness.CompareTo(yFitness);
        });
</code>```

What I would like to do but can't:

```<code>        System.Array.Sort(chains, indexStart, indexEnd, (x, y) =>
        {
            var xFitness = CalculateFitnessSum(x);
            var yFitness = CalculateFitnessSum(y);

            return -xFitness.CompareTo(yFitness);
        });
</code>```

The CalculateFitnessSum() takes a ActionChainBlock[] as the argument.
What's the most performant way to do this?

EDIT:

Couldn't do it with a lambda expression so I implemented the Comparer class:

```<code>    private class ActionChainBlockComparer : IComparer<ActionChainBlock[]>
    {
        public int Compare(ActionChainBlock[] x, ActionChainBlock[] y)
        {
            var xFitness = CalculateFitnessSum(x);
            var yFitness = CalculateFitnessSum(y);

            return -xFitness.CompareTo(yFitness);
        }
    }
</code>```

答:
I think you need to use Linq.

```<code>using System.Linq;
</code>```

then you can just do this:

```<code>chains.OrderBy(x => x.Sum(y => y.fitness));
</code>```

or use where and any other Linq operation.

if you want to sort only part of the arrays use the where to pick the relevant arrays.

Body:
I'd like to sort part of an array of array of structs in C#. I don't want to implement the IComparer interface as that seems to involve boxing and there doesn't seem to be a proper Array.Sort variant that would let me define a lambda expression to compare two elements.

My struct:

    private struct ActionChainBlock
    {
        public int optionIndex;
        public Vector2I target;
        public int fitness;
    }

My array:

    private readonly ActionChainBlock[][] chains;

My code thus far:

        System.Array.Sort(chains, (x, y) =>
        {
            var xFitness = CalculateFitnessSum(x);
            var yFitness = CalculateFitnessSum(y);

            return -xFitness.CompareTo(yFitness);
        });

What I would like to do but can't:

        System.Array.Sort(chains, indexStart, indexEnd, (x, y) =>
        {
            var xFitness = CalculateFitnessSum(x);
            var yFitness = CalculateFitnessSum(y);

            return -xFitness.CompareTo(yFitness);
        });

The CalculateFitnessSum() takes a ActionChainBlock[] as the argument.
What's the most performant way to do this?

EDIT:

Couldn't do it with a lambda expression so I implemented the Comparer class:

    private class ActionChainBlockComparer : IComparer<ActionChainBlock[]>
    {
        public int Compare(ActionChainBlock[] x, ActionChainBlock[] y)
        {
            var xFitness = CalculateFitnessSum(x);
            var yFitness = CalculateFitnessSum(y);

            return -xFitness.CompareTo(yFitness);
        }
    }

Body:
I think you need to use Linq.

using System.Linq;

then you can just do this:

chains.OrderBy(x => x.Sum(y => y.fitness));

or use where and any other Linq operation.

if you want to sort only part of the arrays use the where to pick the relevant arrays.


问:
ReactNative How to pass Param in Custom Drawer Navigation
```<code>const ListNavigator = createStackNavigator({
  List: {
    screen: PostListContainer,
    path: 'list',
  },
});

const leftMenuWidth = Dimensions.get('screen').width / 2;

const DrawerNavigator = createDrawerNavigator({
  Home: AppNavigator,
  PostType1: ListNavigator,
  PostType2: ListNavigator,
}, {
  drawerWidth: leftMenuWidth,
  contentComponent: SlideMenuContainer,
  drawerOpenRoute: 'DrawerOpen',
  drawerCloseRoute: 'DrawerClose',
  drawerToggleRoute: 'DrawerToggle',
});
</code>```

SlideMenuContainer

```<code>class SideMenuContainer extends Component {
  navigateToScreen = route => () => {
    const { navigation } = this.props;
    const navigateAction = NavigationActions.navigate({
      routeName: route,
    });
    navigation.dispatch(navigateAction);
  }

  render() {
    const { props } = this;
    return (
      <Container>
        <SafeAreaView>
          <Header>
            <Body style={{ flex: 1 }}>
              <Icon named="a" />
            </Body>
            <Content style={{ flex: 1, height: 800 }}>
              <DrawerItems {...props} />
            </Content>
          </Header>
        </SafeAreaView>
      </Container>
    );
  }
}
</code>```

When touch PostType1 in Drawer Navigation
I want to pass {Type: 1} to ListNavigator.

```<code><ListNavigator {... props} Type = 1 />
</code>```

I have seen code like this, but I do not know where to use it.
How
Can I send param when I click the Drawer Navigation menu?

答:
you can add props when navigating to another screen in drawer navigation</p>

```<code> this.props.navigation.navigate("route", {
     type: 1
 });
</code>```

Body:
const ListNavigator = createStackNavigator({
  List: {
    screen: PostListContainer,
    path: 'list',
  },
});

const leftMenuWidth = Dimensions.get('screen').width / 2;

const DrawerNavigator = createDrawerNavigator({
  Home: AppNavigator,
  PostType1: ListNavigator,
  PostType2: ListNavigator,
}, {
  drawerWidth: leftMenuWidth,
  contentComponent: SlideMenuContainer,
  drawerOpenRoute: 'DrawerOpen',
  drawerCloseRoute: 'DrawerClose',
  drawerToggleRoute: 'DrawerToggle',
});

SlideMenuContainer

class SideMenuContainer extends Component {
  navigateToScreen = route => () => {
    const { navigation } = this.props;
    const navigateAction = NavigationActions.navigate({
      routeName: route,
    });
    navigation.dispatch(navigateAction);
  }

  render() {
    const { props } = this;
    return (
      <Container>
        <SafeAreaView>

              <Icon named="a" />

            <Content style={{ flex: 1, height: 800 }}>
              <DrawerItems {...props} />
            </Content>

        </SafeAreaView>
      </Container>
    );
  }
}

When touch PostType1 in Drawer Navigation
I want to pass {Type: 1} to ListNavigator.

<ListNavigator {... props} Type = 1 />

I have seen code like this, but I do not know where to use it.
How
Can I send param when I click the Drawer Navigation menu?

Body:
you can add props when navigating to another screen in drawer navigation

 this.props.navigation.navigate("route", {
     type: 1
 });


问:
React Router v4 and htaccess with wordpress
I made a simple React App with two components, which can route by links from one component to the other. If the page is standalone it works well. With the links inside the app the components can be switched and changing the url changes the components well, too. The parameters in the URL are working, too.
But now I want to integrate it in Wordpress as a plugin. The plugin works and the react app is schown on the wordpress page. The router works inside the app. But it`s not possible to switch between the components if I change the url.

I know this is a problem with the correct configuration of the .htaccess file.
The original .htacces of wordpress looks like this:

```<code># BEGIN WordPress
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>

# END WordPress
</code>```

The name of the page where the react app is shown is "shorttest". So I tried to add the RewriteRule:
RewriteRule ^shorttest/(.*)$ /shorttest [QSA,L]

or

RewriteRule ^shorttest/(.*)$ /index.php [QSA,L]

and I deleted the [L] in the rules above.

But this is not working.

here the important files from the the react app:

App.js

```<code><BrowserRouter basename="/shorttest">
       <App/>
</BrowserRouter>
</code>```

Blue.js

```<code>import React, { Component } from 'react';
import './Blue.css';
import { withRouter, Link } from 'react-router-dom';

const BlueComponent = withRouter(props => <Blue {...props} />);
class Blue extends Component {

    render() {
        console.log(this.props.match);
        return (
            <div className="Blue">
                <header className="blue__header">
                    <nav className="BluelicationHeader__nav">
                        <ul className="BluelicationHeader__ul">
                            <li className="BluelicationHeader__li">
                                <Link className="Blue__a" to='/green'>Green</Link>
                            </li>
                        </ul>
                    </nav>
                </header>
                <div className="bluebackground">
                    <img className="blue__image" src={require(`./image/difficulty_3.png`)} alt="image"/>
                </div>
                <p className="Blue-intro">
                    parameter was {this.props.match.params.param}
                </p>
            </div>
        );
    }
}

export default BlueComponent;
</code>```

Green.js

```<code>import React, { Component } from 'react';
import './Green.css';
import { withRouter, Link } from 'react-router-dom';

const GreenComponent = withRouter(props => <Green {...props} />);
class Green extends Component {
    render() {
        return (
            <div className="Green">
                <header className="Green__header">
                    <nav className="GreenlicationHeader__nav">
                        <ul className="GreenlicationHeader__ul">
                            <li className="GreenlicationHeader__li">
                                <Link className="Green__a" to='/'>Blue</Link>
                            </li>
                        </ul>
                    </nav>
                </header>
                <p className="Green-intro">
                    To get started, edit <code>src/App.js</code> and save to reload.
                </p>
            </div>
        );
    }
}

export default GreenComponent;
</code>```

package.json

```<code>"homepage": "http://wp_react_router.local/wp-content/plugins/shortcode-test/js/build",
</code>```

Does anybody know what I have to do in the htaccess or maybe in another htaccess?

Thanx for your help.

答:
Here is the solution for angular router:

In wordpress theme or plugin you need in functions.php (where you add the styles and js. it has the name of the plugin) a function, which overides the htaccess. So you don`t need any changes in the htaccess file itself.

Excample:

```<code>add_action('init', 'custom_rewrite_basic_angularApp');

function custom_rewrite_basic_angularApp() {
    require 'config.php';
    add_rewrite_rule(
        '^'. $wordpressShortcodePageName. '\/(.*)\/?',
        'index.php?pagename='. $wordpressShortcodePageName,
        'top'
    );
}
</code>```

$wordpressShortcodePageName must be the name of the page.
Now the angular router works perfectly. It is not tested with react router, but I think it is the same problem so it should work.

Please let us know, if it works.H

Body:
I made a simple React App with two components, which can route by links from one component to the other. If the page is standalone it works well. With the links inside the app the components can be switched and changing the url changes the components well, too. The parameters in the URL are working, too.
But now I want to integrate it in Wordpress as a plugin. The plugin works and the react app is schown on the wordpress page. The router works inside the app. But it`s not possible to switch between the components if I change the url.

I know this is a problem with the correct configuration of the .htaccess file.
The original .htacces of wordpress looks like this:

# BEGIN WordPress
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>

# END WordPress

The name of the page where the react app is shown is "shorttest". So I tried to add the RewriteRule:
RewriteRule ^shorttest/(.*)$ /shorttest [QSA,L]

or

RewriteRule ^shorttest/(.*)$ /index.php [QSA,L]

and I deleted the [L] in the rules above.

But this is not working.

here the important files from the the react app:

App.js

<BrowserRouter basename="/shorttest">
       <App/>
</BrowserRouter>

Blue.js

import React, { Component } from 'react';
import './Blue.css';
import { withRouter, Link } from 'react-router-dom';

const BlueComponent = withRouter(props => <Blue {...props} />);
class Blue extends Component {

    render() {
        console.log(this.props.match);
        return (

                                <Link className="Blue__a" to='/green'>Green</Link>

                    <img className="blue__image" src={require(`./image/difficulty_3.png`)} alt="image"/>

                    parameter was {this.props.match.params.param}

        );
    }
}

export default BlueComponent;

Green.js

import React, { Component } from 'react';
import './Green.css';
import { withRouter, Link } from 'react-router-dom';

const GreenComponent = withRouter(props => <Green {...props} />);
class Green extends Component {
    render() {
        return (

                                <Link className="Green__a" to='/'>Blue</Link>

                    To get started, edit src/App.js and save to reload.

        );
    }
}

export default GreenComponent;

package.json

"homepage": "http://wp_react_router.local/wp-content/plugins/shortcode-test/js/build",

Does anybody know what I have to do in the htaccess or maybe in another htaccess?

Thanx for your help.

Body:
Here is the solution for angular router:

In wordpress theme or plugin you need in functions.php (where you add the styles and js. it has the name of the plugin) a function, which overides the htaccess. So you don`t need any changes in the htaccess file itself.

Excample:

add_action('init', 'custom_rewrite_basic_angularApp');

function custom_rewrite_basic_angularApp() {
    require 'config.php';
    add_rewrite_rule(
        '^'. $wordpressShortcodePageName. '\/(.*)\/?',
        'index.php?pagename='. $wordpressShortcodePageName,
        'top'
    );
}

$wordpressShortcodePageName must be the name of the page.
Now the angular router works perfectly. It is not tested with react router, but I think it is the same problem so it should work.

Please let us know, if it works.H


问:
How to code An Azure function to receive data from a web portal?
How to code An Azure function to receive data from a web portal(Front end) like Patient name, Age, Sex etc and also send back the data when ever it is requested from the front end

Using Visual Studio i have created the Azure function, HTTP trigger

答:
Overall idea is to use HttpTrigger of Azure function , which intern can be triggered from Web app by posting http request and later can be de-crypt at function end.

The following example shows a C# function that looks for a name parameter either in the query string or the body of the HTTP request. Notice that the return value is used for the output binding, but a return value attribute isn't required.

```<code>[FunctionName("HttpTriggerCSharp")]
public static async Task<IActionResult> Run(
    [HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)]
    HttpRequest req, ILogger log)
{
    log.LogInformation("C# HTTP trigger function processed a request.");

    string name = req.Query["name"];

    string requestBody = await new StreamReader(req.Body).ReadToEndAsync();
    dynamic data = JsonConvert.DeserializeObject(requestBody);
    name = name ?? data?.name;

    return name != null
        ? (ActionResult)new OkObjectResult($"Hello, {name}")
        : new BadRequestObjectResult("Please pass a name on the query string or in the request body");
}
</code>```

Here is the binding for the same:

```<code>{
    "disabled": false,
    "bindings": [
        {
            "authLevel": "function",
            "name": "req",
            "type": "httpTrigger",
            "direction": "in",
            "methods": [
                "get",
                "post"
            ]
        },
        {
            "name": "$return",
            "type": "http",
            "direction": "out"
        }
    ]
}
</code>```

Also , Here's C# script code that binds to HttpRequest:

```<code>using System.Net;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Primitives;
using Newtonsoft.Json;

public static async Task<IActionResult> Run(HttpRequest req, ILogger log)
{
    log.LogInformation("C# HTTP trigger function processed a request.");

    string name = req.Query["name"];

    string requestBody = await new StreamReader(req.Body).ReadToEndAsync();
    dynamic data = JsonConvert.DeserializeObject(requestBody);
    name = name ?? data?.name;

    return name != null
        ? (ActionResult)new OkObjectResult($"Hello, {name}")
        : new BadRequestObjectResult("Please pass a name on the query string or in the request body");
}
</code>```

You can take a look at this link for further reference.

Hope it helps.

Body:
Overall idea is to use HttpTrigger of Azure function , which intern can be triggered from Web app by posting http request and later can be de-crypt at function end.

The following example shows a C# function that looks for a name parameter either in the query string or the body of the HTTP request. Notice that the return value is used for the output binding, but a return value attribute isn't required.

[FunctionName("HttpTriggerCSharp")]
public static async Task<IActionResult> Run(
    [HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)]
    HttpRequest req, ILogger log)
{
    log.LogInformation("C# HTTP trigger function processed a request.");

    string name = req.Query["name"];

    string requestBody = await new StreamReader(req.Body).ReadToEndAsync();
    dynamic data = JsonConvert.DeserializeObject(requestBody);
    name = name ?? data?.name;

    return name != null
        ? (ActionResult)new OkObjectResult($"Hello, {name}")
        : new BadRequestObjectResult("Please pass a name on the query string or in the request body");
}

Here is the binding for the same:

{
    "disabled": false,
    "bindings": [
        {
            "authLevel": "function",
            "name": "req",
            "type": "httpTrigger",
            "direction": "in",
            "methods": [
                "get",
                "post"
            ]
        },
        {
            "name": "$return",
            "type": "http",
            "direction": "out"
        }
    ]
}

Also , Here's C# script code that binds to HttpRequest:

using System.Net;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Primitives;
using Newtonsoft.Json;

public static async Task<IActionResult> Run(HttpRequest req, ILogger log)
{
    log.LogInformation("C# HTTP trigger function processed a request.");

    string name = req.Query["name"];

    string requestBody = await new StreamReader(req.Body).ReadToEndAsync();
    dynamic data = JsonConvert.DeserializeObject(requestBody);
    name = name ?? data?.name;

    return name != null
        ? (ActionResult)new OkObjectResult($"Hello, {name}")
        : new BadRequestObjectResult("Please pass a name on the query string or in the request body");
}

You can take a look at this link for further reference.

Hope it helps.


问:
Laravel roles and permissions
I am new with Laravel and i am trying to build an application based on roles, but in my case the user can have only one role (there is no a pivot table between users and roles) and we can create new role us we like(assign many permissions to one role). Any help? and thanks a lot</p>

答:
For setting up customized user roles and permissions, you may give a try to https://thewebtier.com/laravel/understanding-roles-permissions-laravel/.

It's a complete guide on how to setup roles and permissions in your Laravel project.

Title: Laravel roles and permissions


问:
How to set cell language for good number formatting in openpyxl?
I try to set polish currency format in xslx file using openpyxl.

I have:

xfile = openpyxl.load_workbook('myFile.xlsx')
    sheet = xfile.get_sheet_by_name('Sheet1')

locale.setlocale(locale.LC_ALL, 'pl_PL.utf8')
getcontext().prec = 3 #decimal precission

sheet[f'E1'].number_format = '# ##0,00 [$zł-415];-# ##0,00 [$zł-415]'
sheet[f'E1'] = Decimal(PRICENET) #PRICENET is 17.8
```

So, when I open this file in OpenOffice Calc and I check cell format I see that cell is Currency with good polish currency format but the language is "Default - English (USA)". The cell display "018 zł". When I change the cell language to "Polish" in the cell is "17,80 zł" so it's preferred. What's the clue?

答: In Excel, local settings are global for the application and not for workbooks or worksheets (you cannot set the language for cells) so that even if you set the currency as you have, the settings in the application will take precedence.</p>

Body:
I try to set polish currency format in xslx file using openpyxl.

I have:

xfile = openpyxl.load_workbook('myFile.xlsx')
    sheet = xfile.get_sheet_by_name('Sheet1')

locale.setlocale(locale.LC_ALL, 'pl_PL.utf8')
getcontext().prec = 3 #decimal precission

sheet[f'E1'].number_format = '# ##0,00 [$zł-415];-# ##0,00 [$zł-415]'
sheet[f'E1'] = Decimal(PRICENET) #PRICENET is 17.8

So, when I open this file in OpenOffice Calc and I check cell format I see that cell is Currency with good polish currency format but the language is "Default - English (USA)". The cell display "018 zł". When I change the cell language to "Polish" in the cell is "17,80 zł" so it's preferred. What's the clue?


问:
Is there an array function which produces more elements than it receives?
If we use map on array - we will get the same number of elements.

If we want less elements - we can use filter, find or reduce, depending on situation.

Is there a build in function which would work the other way?

For example, let's say I have an array like this:

```<code>myArray = [
  {nodes: Array(5)}, // some array with 5 elements
  {nodes: Array(3)},
  {nodes: Array(3)}
]
</code>```

I want to split every array with more than 3 elements into array which maximum 3 elements. So in the end I want to get:

```<code>splittedArray = [
  {nodes: Array(3)},
  {nodes: Array(2)},
  {nodes: Array(3)},
  {nodes: Array(3)}
]
</code>```

I know how to achive this with looping over myArray with forEach and pushing items to some new array, but is there some ready-to-go function for it?

答:
Using Array.flatMap() we iterate the original array, use the chunks method (based on Array.from()) to split the nodes array to multiple arrays, and then map them, and wrap each in an object. The flatMap converts the result back to a single array.

const myArray = [
  {nodes: Array(5)},
  {nodes: Array(3)},
  {nodes: Array(3)}
]

const chunks = chunkSize => arr => Array.from({ length: Math.ceil(arr.length / chunkSize) }, (_, i) =>
  arr.slice(i * chunkSize, (i + 1) * chunkSize)
)

const chunks3 = chunks(3)

const result = myArray.flatMap(o => chunks3(o.nodes).map(nodes => ({ nodes })))

console.log(result)```

Body:
If we use map on array - we will get the same number of elements.

If we want less elements - we can use filter, find or reduce, depending on situation.

Is there a build in function which would work the other way?

For example, let's say I have an array like this:

myArray = [
  {nodes: Array(5)}, // some array with 5 elements
  {nodes: Array(3)},
  {nodes: Array(3)}
]

I want to split every array with more than 3 elements into array which maximum 3 elements. So in the end I want to get:

splittedArray = [
  {nodes: Array(3)},
  {nodes: Array(2)},
  {nodes: Array(3)},
  {nodes: Array(3)}
]

I know how to achive this with looping over myArray with forEach and pushing items to some new array, but is there some ready-to-go function for it?


问:
PHP AJAX Delete Record - deletion only works 1 time
I am deleting records with ajax and php. When I click the button it erases the record but when I click to delete another record it does nothing. What am I doing wrong?

HTML

```<code><form id="prop_remove">
    <input type="hidden" name="id" id="last_id" value="<?php echo $id; ?>">
    <input type="hidden" name="user" id="last_user" value="<?php echo $user; ?>">
    <input type="button" name="submit" id="last_prop" class="button fullwidth margin-top-5" value="Delete">
</form>
</code>```

AJAX

```<code><script>
$(document).ready(function() {
    $('#last_prop').click(function() {
        var id = $('#last_id').val();
        var user = $('#last_user').val();
        $.ajax({
            url: "delete.php",
            method: "POST",
            data: {
                ilan_id: id,
                ilan_user: user
            },
            success: function(response) {
                if (response == 1) {
                    $('#last_prop').closest('tr').css('background', 'tomato');
                    $('#last_prop').closest('tr').fadeOut(800, function() {
                        $(this).remove();
                    });
                } else {
                    alert('Invalid id');
                }
            }
        });
    });
});
</script>
</code>```

PHP

```<code><?php
    require_once 'config.php';
    $id     =  $_POST['ilan_id'];
    $user   =  $_POST['ilan_user'];

    $checkRecord    = "SELECT * FROM last_tbl WHERE id = '$id' AND user = '$user'";
    $check_result   = mysqli_query($conn, $checkRecord);
    $totalrows      = mysqli_num_rows($check_result);

    if($totalrows > 0){
        $delete_sql     =   "DELETE FROM last_tbl WHERE id = '$id' AND user = '$user';";
        $delete_result  =   mysqli_query($conn, $delete_sql);
        echo 1;
        exit;
    }

?>
</code>```

答:
Your problem is that you're overwriting the HTML element IDs. You can remove your forms and use a single button instead, and pass data through the data attribute of the buttons.

Replace your form by a single button

<button class="button fullwidth margin-top-5 last_prop" data-last-id="<?= $id; ?>" data-last-user="<?= $user; ?>">Delete</button>
```

<p>Then adapt your jQuery to use the class <code>last_prop</code> instead of the ID, and fetch the values from the <code>data</code> attributes we set above.</p>

```
```

<p>Also, your query can be reduced to one (you don't need that <code>SELECT</code>), and should be with a prepared statement. </p>

<pre class="lang-php prettyprint-override"><code><?php
    require_once 'config.php';
    $id     =  $_POST['ilan_id'];
    $user   =  $_POST['ilan_user'];

    $sql = "DELETE FROM last_tbl WHERE id = ? AND user = ?;";
    $stmt = $conn->prepare($sql);
    $stmt->bind_param("ss", $id, $user);
    $stmt->execute();
    if ($stmt->affected_rows) {
        // rows were deleted
        echo 1;
    }
    $stmt->close();

</code>```

Body:
I am deleting records with ajax and php. When I click the button it erases the record but when I click to delete another record it does nothing. What am I doing wrong?

HTML

<form id="prop_remove">
    <input type="hidden" name="id" id="last_id" value="<?php echo $id; ?>">
    <input type="hidden" name="user" id="last_user" value="<?php echo $user; ?>">
    <input type="button" name="submit" id="last_prop" class="button fullwidth margin-top-5" value="Delete">
</form>

AJAX

PHP

<?php
    require_once 'config.php';
    $id     =  $_POST['ilan_id'];
    $user   =  $_POST['ilan_user'];

    $checkRecord    = "SELECT * FROM last_tbl WHERE id = '$id' AND user = '$user'";
    $check_result   = mysqli_query($conn, $checkRecord);
    $totalrows      = mysqli_num_rows($check_result);

    if($totalrows > 0){
        $delete_sql     =   "DELETE FROM last_tbl WHERE id = '$id' AND user = '$user';";
        $delete_result  =   mysqli_query($conn, $delete_sql);
        echo 1;
        exit;
    }

?>

Body:
Your problem is that you're overwriting the HTML element IDs. You can remove your forms and use a single button instead, and pass data through the data attribute of the buttons.

Replace your form by a single button

<button class="button fullwidth margin-top-5 last_prop" data-last-id="<?= $id; ?>" data-last-user="<?= $user; ?>">Delete</button>

Then adapt your jQuery to use the class last_prop instead of the ID, and fetch the values from the data attributes we set above.

<script>
$(document).ready(function () {
    $('.last_prop').click(function () {
        var id = $(this).data('last-id');
        var user = $(this).data('last-user');

        $.ajax({
            url:"delete.php",
            method: "POST",
            data: {ilan_id: id, ilan_user: user},
            success:function(response){
                if (response == 1 ){
                    $('#last_prop').closest('tr').css('background','tomato');
                    $('#last_prop').closest('tr').fadeOut(800,function(){
                        $(this).remove();
                    });
                } else {
                    alert('Invalid id');
                }
            }
        });
    });
});
</script>

Also, your query can be reduced to one (you don't need that SELECT), and should be with a prepared statement.

<?php
    require_once 'config.php';
    $id     =  $_POST['ilan_id'];
    $user   =  $_POST['ilan_user'];

    $sql = "DELETE FROM last_tbl WHERE id = ? AND user = ?;";
    $stmt = $conn->prepare($sql);
    $stmt->bind_param("ss", $id, $user);
    $stmt->execute();
    if ($stmt->affected_rows) {
        // rows were deleted
        echo 1;
    }
    $stmt->close();


问:
Yahoo Weather API by Lat and Lon
I'm writing a weather app in Xamarin.Form. I am using the Yahoo API. I have no problem getting the weather by the city name parameter. However, when I change the code to use longitude and latitude, the weather does not appear.

To download the weather I use the example from the page: https://developer.yahoo.com/weather/documentation.html#oauth-csharp

I processed it in the following way:

```<code>lSign = string.Format(
                "format={0}&" +
                "lat={1}&" +
                "lon={2}&" +
                "oauth_consumer_key={3}&" +
                "oauth_nonce={4}&" +
                "oauth_signature_method={5}&" +
                "oauth_timestamp={6}&" +
                "oauth_version={7}&" +
                "u={8}",
                cFormat,
                szerokosc,
                dlugosc,
                cConsumerKey,
                lNonce,
                cOAuthSignMethod,
                lTimes,
                cOAuthVersion,
                jednostka.ToString().ToLower()
</code>```

(...)

```<code>url = cURL + "?lat=" + szerokosc + "&lon=" + dlugosc + "&u=" + jednostka.ToString().ToLower() + "&format=" + cFormat;
</code>```

答:
According to the documentation, lSign is used for authentication. It should not be changed, remove these "lat={1}&" + "lon={2}&" from that strings.

It says Please don't simply change value of any parameter without
  re-sorting.

The location information should be involved in the request url and the authorization information is added in the header.

```<code>// Add Authorization
lClt.Headers.Add ( "Authorization", _get_auth () );
// The request URL
lURL = cURL + "?" + "lat=" + szerokosc + "&lon=" + dlugosc + "&format=" + cFormat;
</code>```

Title: Yahoo Weather API by Lat and Lon

Body:
I'm writing a weather app in Xamarin.Form. I am using the Yahoo API. I have no problem getting the weather by the city name parameter. However, when I change the code to use longitude and latitude, the weather does not appear.

To download the weather I use the example from the page: https://developer.yahoo.com/weather/documentation.html#oauth-csharp

I processed it in the following way:

lSign = string.Format(
                "format={0}&" +
                "lat={1}&" +
                "lon={2}&" +
                "oauth_consumer_key={3}&" +
                "oauth_nonce={4}&" +
                "oauth_signature_method={5}&" +
                "oauth_timestamp={6}&" +
                "oauth_version={7}&" +
                "u={8}",
                cFormat,
                szerokosc,
                dlugosc,
                cConsumerKey,
                lNonce,
                cOAuthSignMethod,
                lTimes,
                cOAuthVersion,
                jednostka.ToString().ToLower()

(...)

url = cURL + "?lat=" + szerokosc + "&lon=" + dlugosc + "&u=" + jednostka.ToString().ToLower() + "&format=" + cFormat;

Body:
According to the documentation, lSign is used for authentication. It should not be changed, remove these "lat={1}&" + "lon={2}&" from that strings.

It says Please don't simply change value of any parameter without
  re-sorting.

The location information should be involved in the request url and the authorization information is added in the header.

// Add Authorization
lClt.Headers.Add ( "Authorization", _get_auth () );
// The request URL
lURL = cURL + "?" + "lat=" + szerokosc + "&lon=" + dlugosc + "&format=" + cFormat;


问:
What is the difference between a service account and a context in Kubernetes?
What are the practical differences between the two? When should I choose one over the other?

For example if I'd like to give a developer in my project access to just view the logs of a pod. It seems both a service account or a context could be assigned these permissions via a RoleBinding.

答:
Service Account: A service account represents an identity for processes that run in a pod. When a process is authenticated through a service account, it can contact the API server and access cluster resources. If a pod doesn’t have an assigned service account, it gets the default service account.

When you create a pod, if you do not specify a service account, it is automatically assigned the default service account in the same namespace and you can access the API from inside a pod using automatically mounted service account credentials.

Context: A context is just a set of access parameters that contains a Kubernetes cluster, a user, and a namespace.

The current context is the cluster that is currently the default for kubectl and all kubectl commands run against that cluster.


问:
How can I avoid writing many very similar setter methods?
I am working on a piece of code where the following applies:

I need to instanciate a lot of similar objects within an instance of Class A

Each of these objects will then get their own setter in Class B, which corresponds 1:1 to the objects created in the instance of Class A
i.e.
In class A:

```<code>    B b = new B();

    final SomethingA somethingA1 = new SomethingA("input1");
    b.setSomethingA();

    ...
    final SomethingB somethingB15 = new SomethingB("input15");
    b.setSomethingB15();
    ...

    final SomethingA somethingA23 = new SomethingA("input23");
    b.setSomethingA23();
</code>```

Where all "somethings" inherit from the same class.

The setter does nothing but:

```<code>public void setSomethingX(somethingX){
this.somethingX = somethingX;
}
</code>```

I really do not want to write 23 setters that all do almost the same. Is there something like a multi-purpose setter?

The context of this is preparing an HTTP response in a very specific context and using some very specific frameworks. Apparently, this way of doing saves lot of work somewhere else (that I have no influence on).
Also, as you can probably tell I am a novice developer.

答:
I'd use Lombok setter/getter for this.

A single annotation that would trigger the creation of those methods. The source code in your IDE will not be polluted with those setters and a lot easier to read.

There is a proposal for data classes, but not yet implemented FYI.

Body:
I am working on a piece of code where the following applies:

I need to instanciate a lot of similar objects within an instance of Class A

Each of these objects will then get their own setter in Class B, which corresponds 1:1 to the objects created in the instance of Class A
i.e.
In class A:

    B b = new B();

    final SomethingA somethingA1 = new SomethingA("input1");
    b.setSomethingA();

    ...
    final SomethingB somethingB15 = new SomethingB("input15");
    b.setSomethingB15();
    ...

    final SomethingA somethingA23 = new SomethingA("input23");
    b.setSomethingA23();

Where all "somethings" inherit from the same class.

The setter does nothing but:

public void setSomethingX(somethingX){
this.somethingX = somethingX;
}

I really do not want to write 23 setters that all do almost the same. Is there something like a multi-purpose setter?

The context of this is preparing an HTTP response in a very specific context and using some very specific frameworks. Apparently, this way of doing saves lot of work somewhere else (that I have no influence on).
Also, as you can probably tell I am a novice developer.


问:
How to set all descendant nodes and links to same colour as level 2 ancestor?
I have a d3.js tree with descendant nodes receiving their level 2 ancestor's node colour.  This is working from level 2 to level 3, but stops working at level 4 and on.

Relevant code:

```<code>var colourScale = d3.scale.ordinal()
    .domain(["MD","Professional", "Leader", "Advocate", "Clinician", "Educator", "Scholar"])
    .range(["#6695c8", "#cd3838","#d48440", "#a8ba5f", "#63b7c0", "#c97eb2", "#ccc136"]);
</code>```

and

```<code> nodeUpdate.select("circle")
    .attr("r", 10)
    .attr("fill-opacity","0.7")
    .attr("stroke-opacity","1")
    .style("fill", function(d) {
      return d.depth === 2 ? colourScale(d.parent.name) : colourScale(d.name);
    })
    .style("stroke", function(d) {
      return d.depth === 2 ? colourScale(d.parent.name) : colourScale(d.name);
    });
</code>```

and

```<code>// Enter any new links at the parent's previous position.
  link.enter().insert("path", "g")
    .attr("class", "link")
    .attr("stroke-width", function(d) {
      return 1;
    })
    .attr("d", function(d) {
      var o = {
        x: source.x0,
        y: source.y0
      };
      return diagonal({
        source: o,
        target: o
      });
    })
    .attr("opacity","0.3")
    .style("stroke", function(d) {
      return d.target.depth === 2 ? colourScale(d.target.parent.name) : colourScale(d.target.name);
    });
</code>```

How can I set ALL descendants of a parent to the same colour (nodes and links)?

Fiddle

答:
Use a recursive function to go up the hierarchy until you find a node with the correct depth. For instance:

```<code>function findParent(datum) {
  if (datum.depth < 2) {
    return datum.name
  } else {
    return findParent(datum.parent)
  }
}
</code>```

Or even shorter with a ternary:

```<code>function findParent(datum) {
    return datum.depth < 2 ? datum.name : findParent(datum.parent);
};
</code>```

Then, you can pass it to the colour scale:

```<code>.style("fill", function(d) {
    return colourScale(findParent(d));
})
</code>```

Here is the updated code:

var treeData = [{
  "name": "MD",
  "children": [{
    "name": "Professional",
    "children": [{
      "name": "Third A",
      "children": [{
        "name": "Fourth A",
        "children": [{
          "name": "Fifth A"
        }, {
          "name": "Fifth B"
        }, {
          "name": "Fifth C"
        }, {
          "name": "Fifth D"
        }]
      }, {
        "name": "Fourth B"
      }, {
        "name": "Fourth C"
      }, {
        "name": "Fourth D"
      }]
    }, {
      "name": "Third B"
    }]
  }, {
    "name": "Leader",
    "children": [{
      "name": "Third C"
    }, {
      "name": "Third D"
    }]
  }, {
    "name": "Advocate",
    "children": [{
      "name": "Third E"
    }, {
      "name": "Third F"
    }]
  }, {
    "name": "Clinician",
    "children": [{
      "name": "Third G"
    }, {
      "name": "Third H"
    }, ]
  }, ]
}];

var colourScale = d3.scale.ordinal()
  .domain(["MD", "Professional", "Leader", "Advocate", "Clinician"])
  .range(["#6695c8", "#cd3838", "#d48440", "#a8ba5f", "#63b7c0"]);

// ************** Generate the tree diagram  *****************
var margin = {
    top: 20,
    right: 120,
    bottom: 20,
    left: 120
  },
  width = 1200 - margin.right - margin.left,
  height = 650 - margin.top - margin.bottom;

var i = 0,
  duration = 750,
  root;

var tree = d3.layout.tree()
  .size([height, width]);

var diagonal = d3.svg.diagonal()
  .projection(function(d) {
    return [d.y, d.x];
  });

var svg = d3.select("body").append("svg")
  .attr("width", width + margin.right + margin.left)
  .attr("height", height + margin.top + margin.bottom)
  .append("g")
  .attr("transform", "translate(" + margin.left + "," + margin.top + ")");

root = treeData[0];
root.x0 = height / 2;
root.y0 = 0;

update(root);

d3.select(self.frameElement).style("height", "500px");

// Collapse after the second level
root.children.forEach(collapse);

update(root);

// Collapse the node and all it's children
function collapse(d) {
  if (d.children) {
    d._children = d.children
    d._children.forEach(collapse)
    d.children = null
  }
}

function update(source) {

  // Compute the new tree layout.
  var nodes = tree.nodes(root).reverse(),
    links = tree.links(nodes);

  // Normalize for fixed-depth.
  nodes.forEach(function(d) {
    d.y = d.depth * 200;
  });

  // Update the nodes…
  var node = svg.selectAll("g.node")
    .data(nodes, function(d) {
      return d.id || (d.id = ++i);
    });

  // Enter any new nodes at the parent's previous position.
  var nodeEnter = node.enter().append("g")
    .attr("class", "node")
    .attr("transform", function(d) {
      return "translate(" + source.y0 + "," + source.x0 + ")";
    })
    .on("click", click);

  nodeEnter.append("circle")
    .attr("r", 1e-6)
    .style("fill", function(d) {
      return d._children ? "#C0C0C0" : "#fff";
    });

  nodeEnter.append("text")
    .attr("x", function(d) {
      return d.children || d._children ? -13 : 13;
    })
    .attr("dy", ".35em")
    .attr("text-anchor", function(d) {
      return d.children || d._children ? "end" : "start";
    })
    .text(function(d) {
      return d.name;
    })
    .style("fill-opacity", 1e-6);

  // Transition nodes to their new position.
  var nodeUpdate = node.transition()
    .duration(duration)
    .attr("transform", function(d) {
      return "translate(" + d.y + "," + d.x + ")";
    });

  nodeUpdate.select("circle")
    .attr("r", 10)
    .attr("fill-opacity", "0.7")
    .attr("stroke-opacity", "1")
    .style("fill", function(d) {
      return colourScale(findParent(d));
    })
    .style("stroke", function(d) {
      return colourScale(findParent(d));
    });

  nodeUpdate.select("text")
    .style("fill-opacity", 1);

  // Transition exiting nodes to the parent's new position.
  var nodeExit = node.exit().transition()
    .duration(duration)
    .attr("transform", function(d) {
      return "translate(" + source.y + "," + source.x + ")";
    })
    .remove();

  nodeExit.select("circle")
    .attr("r", 1e-6);

  nodeExit.select("text")
    .style("fill-opacity", 1e-6);

  // Update the links…
  var link = svg.selectAll("path.link")
    .data(links, function(d) {
      return d.target.id;
    });

  // Enter any new links at the parent's previous position.
  link.enter().insert("path", "g")
    .attr("class", "link")
    .attr("stroke-width", function(d) {
      return 1;
    })
    .attr("d", function(d) {
      var o = {
        x: source.x0,
        y: source.y0
      };
      return diagonal({
        source: o,
        target: o
      });
    })
    .attr("opacity", "0.3")
    .style("stroke", function(d) {
      return colourScale(findParentLinks(d));
    });

  // Transition links to their new position.
  link.transition()
    .duration(duration)
    .attr("d", diagonal);

  // Transition exiting nodes to the parent's new position.
  link.exit().transition()
    .duration(duration)
    .attr("d", function(d) {
      var o = {
        x: source.x,
        y: source.y
      };
      return diagonal({
        source: o,
        target: o
      });
    })
    .remove();

  // Stash the old positions for transition.
  nodes.forEach(function(d) {
    d.x0 = d.x;
    d.y0 = d.y;
  });
}

function findParent(datum) {
  if (datum.depth < 2) {
    return datum.name
  } else {
    return findParent(datum.parent)
  }
}

function findParentLinks(datum) {
  if (datum.target.depth < 2) {
    return datum.target.name
  } else {
    return findParent(datum.target.parent)
  }
}

// Toggle children on click.
function click(d) {
  if (d.children) {
    d._children = d.children;
    d.children = null;
  } else {
    d.children = d._children;
    d._children = null;
  }
  update(d);

}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.node {
  cursor: pointer;
}

.node circle {
  fill: #fff;
  stroke: #C0C0C0;
  stroke-width: 1.5px;
}

.node text {
  font: 10px sans-serif;
}

.link {
  fill: none;
  stroke: #C0C0C0;
  stroke-width: 1.5px;
}</code>```

```

Body:
I have a d3.js tree with descendant nodes receiving their level 2 ancestor's node colour.  This is working from level 2 to level 3, but stops working at level 4 and on.

Relevant code:

var colourScale = d3.scale.ordinal()
    .domain(["MD","Professional", "Leader", "Advocate", "Clinician", "Educator", "Scholar"])
    .range(["#6695c8", "#cd3838","#d48440", "#a8ba5f", "#63b7c0", "#c97eb2", "#ccc136"]);

and

 nodeUpdate.select("circle")
    .attr("r", 10)
    .attr("fill-opacity","0.7")
    .attr("stroke-opacity","1")
    .style("fill", function(d) {
      return d.depth === 2 ? colourScale(d.parent.name) : colourScale(d.name);
    })
    .style("stroke", function(d) {
      return d.depth === 2 ? colourScale(d.parent.name) : colourScale(d.name);
    });

and

// Enter any new links at the parent's previous position.
  link.enter().insert("path", "g")
    .attr("class", "link")
    .attr("stroke-width", function(d) {
      return 1;
    })
    .attr("d", function(d) {
      var o = {
        x: source.x0,
        y: source.y0
      };
      return diagonal({
        source: o,
        target: o
      });
    })
    .attr("opacity","0.3")
    .style("stroke", function(d) {
      return d.target.depth === 2 ? colourScale(d.target.parent.name) : colourScale(d.target.name);
    });

How can I set ALL descendants of a parent to the same colour (nodes and links)?

Fiddle

Body:
Use a recursive function to go up the hierarchy until you find a node with the correct depth. For instance:

function findParent(datum) {
  if (datum.depth < 2) {
    return datum.name
  } else {
    return findParent(datum.parent)
  }
}

Or even shorter with a ternary:

function findParent(datum) {
    return datum.depth < 2 ? datum.name : findParent(datum.parent);
};

Then, you can pass it to the colour scale:

.style("fill", function(d) {
    return colourScale(findParent(d));
})

Here is the updated code:

var treeData = [{
  "name": "MD",
  "children": [{
    "name": "Professional",
    "children": [{
      "name": "Third A",
      "children": [{
        "name": "Fourth A",
        "children": [{
          "name": "Fifth A"
        }, {
          "name": "Fifth B"
        }, {
          "name": "Fifth C"
        }, {
          "name": "Fifth D"
        }]
      }, {
        "name": "Fourth B"
      }, {
        "name": "Fourth C"
      }, {
        "name": "Fourth D"
      }]
    }, {
      "name": "Third B"
    }]
  }, {
    "name": "Leader",
    "children": [{
      "name": "Third C"
    }, {
      "name": "Third D"
    }]
  }, {
    "name": "Advocate",
    "children": [{
      "name": "Third E"
    }, {
      "name": "Third F"
    }]
  }, {
    "name": "Clinician",
    "children": [{
      "name": "Third G"
    }, {
      "name": "Third H"
    }, ]
  }, ]
}];

var colourScale = d3.scale.ordinal()
  .domain(["MD", "Professional", "Leader", "Advocate", "Clinician"])
  .range(["#6695c8", "#cd3838", "#d48440", "#a8ba5f", "#63b7c0"]);

// ************** Generate the tree diagram  *****************
var margin = {
    top: 20,
    right: 120,
    bottom: 20,
    left: 120
  },
  width = 1200 - margin.right - margin.left,
  height = 650 - margin.top - margin.bottom;

var i = 0,
  duration = 750,
  root;

var tree = d3.layout.tree()
  .size([height, width]);

var diagonal = d3.svg.diagonal()
  .projection(function(d) {
    return [d.y, d.x];
  });

var svg = d3.select("body").append("svg")
  .attr("width", width + margin.right + margin.left)
  .attr("height", height + margin.top + margin.bottom)
  .append("g")
  .attr("transform", "translate(" + margin.left + "," + margin.top + ")");

root = treeData[0];
root.x0 = height / 2;
root.y0 = 0;

update(root);

d3.select(self.frameElement).style("height", "500px");

// Collapse after the second level
root.children.forEach(collapse);

update(root);

// Collapse the node and all it's children
function collapse(d) {
  if (d.children) {
    d._children = d.children
    d._children.forEach(collapse)
    d.children = null
  }
}

function update(source) {

  // Compute the new tree layout.
  var nodes = tree.nodes(root).reverse(),
    links = tree.links(nodes);

  // Normalize for fixed-depth.
  nodes.forEach(function(d) {
    d.y = d.depth * 200;
  });

  // Update the nodes…
  var node = svg.selectAll("g.node")
    .data(nodes, function(d) {
      return d.id || (d.id = ++i);
    });

  // Enter any new nodes at the parent's previous position.
  var nodeEnter = node.enter().append("g")
    .attr("class", "node")
    .attr("transform", function(d) {
      return "translate(" + source.y0 + "," + source.x0 + ")";
    })
    .on("click", click);

  nodeEnter.append("circle")
    .attr("r", 1e-6)
    .style("fill", function(d) {
      return d._children ? "#C0C0C0" : "#fff";
    });

  nodeEnter.append("text")
    .attr("x", function(d) {
      return d.children || d._children ? -13 : 13;
    })
    .attr("dy", ".35em")
    .attr("text-anchor", function(d) {
      return d.children || d._children ? "end" : "start";
    })
    .text(function(d) {
      return d.name;
    })
    .style("fill-opacity", 1e-6);

  // Transition nodes to their new position.
  var nodeUpdate = node.transition()
    .duration(duration)
    .attr("transform", function(d) {
      return "translate(" + d.y + "," + d.x + ")";
    });

  nodeUpdate.select("circle")
    .attr("r", 10)
    .attr("fill-opacity", "0.7")
    .attr("stroke-opacity", "1")
    .style("fill", function(d) {
      return colourScale(findParent(d));
    })
    .style("stroke", function(d) {
      return colourScale(findParent(d));
    });

  nodeUpdate.select("text")
    .style("fill-opacity", 1);

  // Transition exiting nodes to the parent's new position.
  var nodeExit = node.exit().transition()
    .duration(duration)
    .attr("transform", function(d) {
      return "translate(" + source.y + "," + source.x + ")";
    })
    .remove();

  nodeExit.select("circle")
    .attr("r", 1e-6);

  nodeExit.select("text")
    .style("fill-opacity", 1e-6);

  // Update the links…
  var link = svg.selectAll("path.link")
    .data(links, function(d) {
      return d.target.id;
    });

  // Enter any new links at the parent's previous position.
  link.enter().insert("path", "g")
    .attr("class", "link")
    .attr("stroke-width", function(d) {
      return 1;
    })
    .attr("d", function(d) {
      var o = {
        x: source.x0,
        y: source.y0
      };
      return diagonal({
        source: o,
        target: o
      });
    })
    .attr("opacity", "0.3")
    .style("stroke", function(d) {
      return colourScale(findParentLinks(d));
    });

  // Transition links to their new position.
  link.transition()
    .duration(duration)
    .attr("d", diagonal);

  // Transition exiting nodes to the parent's new position.
  link.exit().transition()
    .duration(duration)
    .attr("d", function(d) {
      var o = {
        x: source.x,
        y: source.y
      };
      return diagonal({
        source: o,
        target: o
      });
    })
    .remove();

  // Stash the old positions for transition.
  nodes.forEach(function(d) {
    d.x0 = d.x;
    d.y0 = d.y;
  });
}

function findParent(datum) {
  if (datum.depth < 2) {
    return datum.name
  } else {
    return findParent(datum.parent)
  }
}

function findParentLinks(datum) {
  if (datum.target.depth < 2) {
    return datum.target.name
  } else {
    return findParent(datum.target.parent)
  }
}

// Toggle children on click.
function click(d) {
  if (d.children) {
    d._children = d.children;
    d.children = null;
  } else {
    d.children = d._children;
    d._children = null;
  }
  update(d);

}

.node {
  cursor: pointer;
}

.node circle {
  fill: #fff;
  stroke: #C0C0C0;
  stroke-width: 1.5px;
}

.node text {
  font: 10px sans-serif;
}

.link {
  fill: none;
  stroke: #C0C0C0;
  stroke-width: 1.5px;
}

<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.5.17/d3.min.js"></script>


问:
Indexing policy is not being created along with collection in Cosmos DB
I'm writing a database creation script using Java SDK and the indexing policy is not being created as expected (and documented).

JAVA SDK used: com.microsoft.azure:azure-documentdb:2.4.0

Azure Cosmos DB emulator 2.2.2 for windows

Current Cosmos DB installation in Azure Portal with SQL account

I construct the collection creation request with a JAVA library and the result (before the actual request) looks like this (DocumentCollection::toJson()):

```<code>{
    "uniqueKeyPolicy": {},
    "partitionKey":
    {
        "kind": "Hash",
        "paths": ["/playerId"]
    },
    "indexingPolicy":
    {
        "indexingMode": "Consistent",
        "automatic": true,
        "includedPaths": [
            {
                "path": "/gameId/?",
                "indexes": [
                    {
                        "kind": "Range",
                        "dataType": "String"
                    }
                ]
            },
            {
                "path": "/playerId/?",
                "indexes": [
                    {
                        "kind": "Range",
                        "dataType": "String"
                    }
                ]
            },
            {
                "path": "/date/*",
                "indexes": [
                    {
                        "kind": "Range",
                        "dataType": "String"
                    }
                ]
            }
        ],
        "excludedPaths": [
            {
                "path": "/*"
            }
        ]
    },
    "id": "Games"
}
</code>```

The request completes successful but if I check the actual indexing policy with data explorer or DocumentClient.readCollection it looks like this:

```<code>{
    "indexingMode": "consistent",
    "automatic": true,
    "includedPaths": [
        {
            "path": "/gameId/?",
            "indexes": []
        },
        {
            "path": "/playerId/?",
            "indexes": []
        },
        {
            "path": "/date/*",
            "indexes": []
        }
    ],
    "excludedPaths": [
        {
            "path": "/*"
        },
        {
            "path": "/\"_etag\"/?"
        }
    ]
}
</code>```

As you can see the arrays for index definitions are empty.
Then if I copy the indexing policy from SDK-generated output and manually paste it in Emulator or Portal 'Scale and settings' window for created collection the update outcome becomes the following:

```<code>{
    "indexingMode": "consistent",
    "automatic": true,
    "includedPaths": [
        {
            "path": "/gameId/?",
            "indexes": [
                {
                    "kind": "Range",
                    "dataType": "String",
                    "precision": -1
                },
                {
                    "kind": "Range",
                    "dataType": "Number",
                    "precision": -1
                }
            ]
        },
        {
            "path": "/playerId/?",
            "indexes": [
                {
                    "kind": "Range",
                    "dataType": "String",
                    "precision": -1
                },
                {
                    "kind": "Range",
                    "dataType": "Number",
                    "precision": -1
                }
            ]
        },
        {
            "path": "/date/*",
            "indexes": [
                {
                    "kind": "Range",
                    "dataType": "String",
                    "precision": -1
                },
                {
                    "kind": "Range",
                    "dataType": "Number",
                    "precision": -1
                }
            ]
        }
    ],
    "excludedPaths": [
        {
            "path": "/*"
        },
        {
            "path": "/\"_etag\"/?"
        }
    ]
}
</code>```

So the indexes are being created (although with extra Number entry as mentioned here).
Am I doing something wrong with a creation script?

答:
Please follow the github source code and refer to below code which works for me.</p>

```<code>import com.microsoft.azure.documentdb.*;

import java.util.Collection;
import java.util.List;

public class CreateCollectionTest {
    //
    static private String YOUR_COSMOS_DB_ENDPOINT = "https://***.documents.azure.com:443/";
    static private String YOUR_COSMOS_DB_MASTER_KEY = "***";

    public static void main(String[] args) throws DocumentClientException {

        DocumentClient client = new DocumentClient(
                YOUR_COSMOS_DB_ENDPOINT,
                YOUR_COSMOS_DB_MASTER_KEY,
                new ConnectionPolicy(),
                ConsistencyLevel.Session);

        DocumentCollection collection = new DocumentCollection();
        collection.set("id", "game");

        IndexingPolicy indexingPolicy = new IndexingPolicy();
        Collection<IncludedPath> includedPaths = new ArrayList<IncludedPath>();
        IncludedPath includedPath = new IncludedPath();
        includedPath.setPath("/gameId/?");
        Collection<Index> indexes = new ArrayList<Index>();

        Index stringIndex = Index.Range(DataType.String);
        stringIndex.set("precision", -1);
        indexes.add(stringIndex);

        Index numberIndex = Index.Range(DataType.Number);
        numberIndex.set("precision", -1);
        indexes.add(numberIndex);

        includedPath.setIndexes(indexes);
        includedPaths.add(includedPath);
        indexingPolicy.setIncludedPaths(includedPaths);

        collection.setIndexingPolicy(indexingPolicy);

        ResourceResponse<DocumentCollection> createColl = client.createCollection("dbs/db", collection, null);

    }
}
</code>```

Body:
I'm writing a database creation script using Java SDK and the indexing policy is not being created as expected (and documented).

JAVA SDK used: com.microsoft.azure:azure-documentdb:2.4.0

Azure Cosmos DB emulator 2.2.2 for windows

Current Cosmos DB installation in Azure Portal with SQL account

I construct the collection creation request with a JAVA library and the result (before the actual request) looks like this (DocumentCollection::toJson()):

{
    "uniqueKeyPolicy": {},
    "partitionKey":
    {
        "kind": "Hash",
        "paths": ["/playerId"]
    },
    "indexingPolicy":
    {
        "indexingMode": "Consistent",
        "automatic": true,
        "includedPaths": [
            {
                "path": "/gameId/?",
                "indexes": [
                    {
                        "kind": "Range",
                        "dataType": "String"
                    }
                ]
            },
            {
                "path": "/playerId/?",
                "indexes": [
                    {
                        "kind": "Range",
                        "dataType": "String"
                    }
                ]
            },
            {
                "path": "/date/*",
                "indexes": [
                    {
                        "kind": "Range",
                        "dataType": "String"
                    }
                ]
            }
        ],
        "excludedPaths": [
            {
                "path": "/*"
            }
        ]
    },
    "id": "Games"
}

The request completes successful but if I check the actual indexing policy with data explorer or DocumentClient.readCollection it looks like this:

{
    "indexingMode": "consistent",
    "automatic": true,
    "includedPaths": [
        {
            "path": "/gameId/?",
            "indexes": []
        },
        {
            "path": "/playerId/?",
            "indexes": []
        },
        {
            "path": "/date/*",
            "indexes": []
        }
    ],
    "excludedPaths": [
        {
            "path": "/*"
        },
        {
            "path": "/\"_etag\"/?"
        }
    ]
}

As you can see the arrays for index definitions are empty.
Then if I copy the indexing policy from SDK-generated output and manually paste it in Emulator or Portal 'Scale and settings' window for created collection the update outcome becomes the following:

{
    "indexingMode": "consistent",
    "automatic": true,
    "includedPaths": [
        {
            "path": "/gameId/?",
            "indexes": [
                {
                    "kind": "Range",
                    "dataType": "String",
                    "precision": -1
                },
                {
                    "kind": "Range",
                    "dataType": "Number",
                    "precision": -1
                }
            ]
        },
        {
            "path": "/playerId/?",
            "indexes": [
                {
                    "kind": "Range",
                    "dataType": "String",
                    "precision": -1
                },
                {
                    "kind": "Range",
                    "dataType": "Number",
                    "precision": -1
                }
            ]
        },
        {
            "path": "/date/*",
            "indexes": [
                {
                    "kind": "Range",
                    "dataType": "String",
                    "precision": -1
                },
                {
                    "kind": "Range",
                    "dataType": "Number",
                    "precision": -1
                }
            ]
        }
    ],
    "excludedPaths": [
        {
            "path": "/*"
        },
        {
            "path": "/\"_etag\"/?"
        }
    ]
}

So the indexes are being created (although with extra Number entry as mentioned here).
Am I doing something wrong with a creation script?

Body:
Please follow the github source code and refer to below code which works for me.

import com.microsoft.azure.documentdb.*;

import java.util.Collection;
import java.util.List;

public class CreateCollectionTest {
    //
    static private String YOUR_COSMOS_DB_ENDPOINT = "https://***.documents.azure.com:443/";
    static private String YOUR_COSMOS_DB_MASTER_KEY = "***";

    public static void main(String[] args) throws DocumentClientException {

        DocumentClient client = new DocumentClient(
                YOUR_COSMOS_DB_ENDPOINT,
                YOUR_COSMOS_DB_MASTER_KEY,
                new ConnectionPolicy(),
                ConsistencyLevel.Session);

        DocumentCollection collection = new DocumentCollection();
        collection.set("id", "game");

        IndexingPolicy indexingPolicy = new IndexingPolicy();
        Collection<IncludedPath> includedPaths = new ArrayList<IncludedPath>();
        IncludedPath includedPath = new IncludedPath();
        includedPath.setPath("/gameId/?");
        Collection<Index> indexes = new ArrayList<Index>();

        Index stringIndex = Index.Range(DataType.String);
        stringIndex.set("precision", -1);
        indexes.add(stringIndex);

        Index numberIndex = Index.Range(DataType.Number);
        numberIndex.set("precision", -1);
        indexes.add(numberIndex);

        includedPath.setIndexes(indexes);
        includedPaths.add(includedPath);
        indexingPolicy.setIncludedPaths(includedPaths);

        collection.setIndexingPolicy(indexingPolicy);

        ResourceResponse<DocumentCollection> createColl = client.createCollection("dbs/db", collection, null);

    }
}


问:
ERROR TypeError: Cannot set property 'username' of undefined
I need to request my api (https://myurl.com/login) for login (username + password) in angular 7.3. When i use POST without user.models.ts i received a bad request error. When I use this model I have this error : "ERROR TypeError: Cannot set property 'username' of undefined."

user.model.ts

```<code>export class User {
constructor(public username: string,
            public password: string) {
    }
}
</code>```

login.component.ts:

```<code>import {Component, OnInit} from '@angular/core';
import {NgForm} from '@angular/forms';
import {HttpClient} from '@angular/common/http';
import {LoginService} from '../services/login.service';
import {User} from '../models/user.model';

@Component({
selector: 'app-login',
templateUrl: './login.component.html',
styleUrls: ['./login.component.scss']
})
export class LoginComponent implements OnInit {
    user: User;
    constructor(private httpClient: HttpClient, private loginService:
LoginService) { }
    ngOnInit() {
    }
    onSubmit(form: NgForm) {
        this.user.username = form.value['login'];
        this.user.password = form.value['password'];
        this.loginService.LoginUser(this.user).subscribe(res => {
            console.log(res);
        });
    }
}
</code>```

login.service.ts:

```<code>import {User} from '../models/user.model';
import { HttpClient, HttpHeaders} from '@angular/common/http';
import { Observable, throwError } from 'rxjs';
import {Injectable} from '@angular/core';

@Injectable()
export class LoginService {
    constructor(private http: HttpClient) { }

    LoginUser(user: User): Observable<User> {
        return this.http.post<User>('https://captn-boat-api.herokuapp.com/login', user)
        ;
    }
}
</code>```

login.component.html

```<code><div class="login--already-registered">
      <span class="login--screen-title">J'ai déjà un compte</span>

      <form class="login" method="GET" action="login" (ngSubmit)="onSubmit(f)" #f="ngForm">

        <div class="input--field text dark">
          <label for="login" class="control-label"><svg class="icon icon-envelope"><use xlink:href="#icon-envelope"></use></svg> E-mail</label>
          <input id="login" name="login" type="text" placeholder="" value="" ngModel>

        </div>

        <div class="input--field password dark">
          <label for="password" class="control-label"><svg class="icon icon-lock"><use xlink:href="#icon-lock"></use></svg> Mot de passe</label>
          <input id="password" name="password" type="password" placeholder="" value="" ngModel>

        </div>

        <div class="input--field checkbox dark">
          <label for="session"><input id="session" name="" value="session" type="checkbox"> se souvenir de moi</label>
        </div>

        <div class="login--submit">

          <button class="button button btn-submit" type="submit">
</code>```

答:
You have to inilialize user.

Replace user: User; by user: User= new User or user: User = {};

Body:
I need to request my api (https://myurl.com/login) for login (username + password) in angular 7.3. When i use POST without user.models.ts i received a bad request error. When I use this model I have this error : "ERROR TypeError: Cannot set property 'username' of undefined."

user.model.ts

export class User {
constructor(public username: string,
            public password: string) {
    }
}

login.component.ts:

import {Component, OnInit} from '@angular/core';
import {NgForm} from '@angular/forms';
import {HttpClient} from '@angular/common/http';
import {LoginService} from '../services/login.service';
import {User} from '../models/user.model';

@Component({
selector: 'app-login',
templateUrl: './login.component.html',
styleUrls: ['./login.component.scss']
})
export class LoginComponent implements OnInit {
    user: User;
    constructor(private httpClient: HttpClient, private loginService:
LoginService) { }
    ngOnInit() {
    }
    onSubmit(form: NgForm) {
        this.user.username = form.value['login'];
        this.user.password = form.value['password'];
        this.loginService.LoginUser(this.user).subscribe(res => {
            console.log(res);
        });
    }
}

login.service.ts:

import {User} from '../models/user.model';
import { HttpClient, HttpHeaders} from '@angular/common/http';
import { Observable, throwError } from 'rxjs';
import {Injectable} from '@angular/core';

@Injectable()
export class LoginService {
    constructor(private http: HttpClient) { }

    LoginUser(user: User): Observable<User> {
        return this.http.post<User>('https://captn-boat-api.herokuapp.com/login', user)
        ;
    }
}

login.component.html

      J'ai déjà un compte

      <form class="login" method="GET" action="login" (ngSubmit)="onSubmit(f)" #f="ngForm">

          <svg class="icon icon-envelope"><use xlink:href="#icon-envelope"></use></svg> E-mail
          <input id="login" name="login" type="text" placeholder="" value="" ngModel>

          <svg class="icon icon-lock"><use xlink:href="#icon-lock"></use></svg> Mot de passe
          <input id="password" name="password" type="password" placeholder="" value="" ngModel>

          <input id="session" name="" value="session" type="checkbox"> se souvenir de moi

          <button class="button button btn-submit" type="submit">


问:
Enabling CSS modules in ReactJS by adding a .module to CSS file name
I am new to ReactJS , I was reading about how to enable CSS modules and what i came to is:

If you add .module it will add a base64 hash string to the name of classes used

Actually i created a function-based component Layout.js

```<code>import React from "react";
import classes from "./Layout.module.css";

const layout = props => <div className={classes.bg}>Here first div</div>

export default layout;

</code>```

and css file as Layout.module.css

```<code>.bg {
  display: inline;
  background-color: rgba(115, 251, 4, 0.685);
}
</code>```

When i inspected the div in browser:

```<code><div class="Layout_bg__1bzIA">Here first div</div>
</code>```

everything seems to work fine, But when i created another component second.js with a div in it and applied the same class

```<code>import React from "react";
import classes from "../Layout/Layout.module.css";

const second = props => <div className={classes.bg}>Here second div</div>

export default second;
</code>```

And when i inspected the second div it looks like:

```<code><div class="Layout_bg__1bzIA">Here seond div</div>
</code>```

They both took the same hash value, So my question is it right what i quoted above

.module enables CSS modules

And if it is , Why it gives the same hash values to different elements in different components

答:
In my understanding module allows you to create same classes name without mixing them together. I mean by it that when you create another module with the same class name (in your case bg) it will have assigned different hash value which means they will have different names and therefore those two classes will never mix together.
Hope that helps. </p>

Body:
I am new to ReactJS , I was reading about how to enable CSS modules and what i came to is:

If you add .module it will add a base64 hash string to the name of classes used

Actually i created a function-based component Layout.js

import React from "react";
import classes from "./Layout.module.css";

const layout = props =>
Here first div

export default layout;

and css file as Layout.module.css

.bg {
  display: inline;
  background-color: rgba(115, 251, 4, 0.685);
}

When i inspected the div in browser:

Here first div

everything seems to work fine, But when i created another component second.js with a div in it and applied the same class

import React from "react";
import classes from "../Layout/Layout.module.css";

const second = props =>
Here second div

export default second;

And when i inspected the second div it looks like:

Here seond div

They both took the same hash value, So my question is it right what i quoted above

.module enables CSS modules

And if it is , Why it gives the same hash values to different elements in different components


问:
How to convert/change date format from MM/DD/YYYY to Month Date, Year?
I'm trying to convert/change my blog date from MM/DD/YYYY to Month Date, Year. For example, this date 11/12/2018 convert to November 12, 2018. Is there a way to do this correctly?

I've tried a code that suppose to work. However, the code converted/changed every blog posts' date to recent published posts' (date).

I tried this code:

```<code>var months = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
var data = $('.date-text').text();
var arr = data.split('/');
$(".date-text").html(months[parseInt(arr[0]) - 1] + " " + arr[1] + ", " + arr[2]);
</code>```

and code converted all dates to recent published posts' date, which is now displayed as November 12, 2018 11.

Working editor: https://jsfiddle.net/s1b2fenk/

Website's image after date changed:

答:
Do you know about moment.js or date-fns ? This will do it for you.

Anyway your problem come certainly from the way "data" is computed. (and it's not explained in your code extract). You may console.log(data, arr) to check their value.

Body:
I'm trying to convert/change my blog date from MM/DD/YYYY to Month Date, Year. For example, this date 11/12/2018 convert to November 12, 2018. Is there a way to do this correctly?

I've tried a code that suppose to work. However, the code converted/changed every blog posts' date to recent published posts' (date).

I tried this code:

var months = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
var data = $('.date-text').text();
var arr = data.split('/');
$(".date-text").html(months[parseInt(arr[0]) - 1] + " " + arr[1] + ", " + arr[2]);

and code converted all dates to recent published posts' date, which is now displayed as November 12, 2018 11.

Working editor: https://jsfiddle.net/s1b2fenk/

Website's image after date changed:


问:
StreamBuilder is not rebuilding on new event in stream
My StreamBuilder in view:

```<code>Widget build(BuildContext context) {
    print("rebuilding..."); // as of now this gets called only on view initialization and never again - i.e. not on new events going through alarmController.stream

    return StreamBuilder(
        stream: widget.bloc.alarmController.stream,
        initialData: Alarm(''),
        builder: (BuildContext context, AsyncSnapshot<Alarm> snapshot) {
          if (!snapshot.hasData) {
            return Center(
              child: Text(StringLiterals.NO_ALARM_DATA_MSG))
            );
          }

          return Switch(
                  activeColor: Colors.red,
                  value: snapshot.data.status == 'Started',
                  onChanged: (bool _value) {
                    _newAlarmValue = _value;
                    _askAlarmConfirmation();
                  }));
        });
  }
</code>```

meat of my bloc:

```<code>AlarmBloc(this.Api) {
    getAlarm();
}
  getAlarm() async {
    Alarm response = await Api.getAlarmStatus();
    alarmController.sink.add(response); // here im adding new event, therefore streambuilder should rebuild, right?
}
</code>```

And lastly the code I call to initiate new event(in this case it's firebase message):

```<code>if(_message.notification.body.contains("Alarm") && IS_LOGGED_IN == true) {
   alarmBloc.getAlarm();
 }
</code>```

So the problem is StreamBuilder not rebuilding whenever new event passes through alarmController.stream. What could be the reason?

答: The issue was I was instantiaing my BLOC incorrectly(second one) and working on a second parallel stream and therefore not the one passed to StreamBuilder.</p>

Body:
My StreamBuilder in view:

Widget build(BuildContext context) {
    print("rebuilding..."); // as of now this gets called only on view initialization and never again - i.e. not on new events going through alarmController.stream

    return StreamBuilder(
        stream: widget.bloc.alarmController.stream,
        initialData: Alarm(''),
        builder: (BuildContext context, AsyncSnapshot<Alarm> snapshot) {
          if (!snapshot.hasData) {
            return Center(
              child: Text(StringLiterals.NO_ALARM_DATA_MSG))
            );
          }

          return Switch(
                  activeColor: Colors.red,
                  value: snapshot.data.status == 'Started',
                  onChanged: (bool _value) {
                    _newAlarmValue = _value;
                    _askAlarmConfirmation();
                  }));
        });
  }

meat of my bloc:

AlarmBloc(this.Api) {
    getAlarm();
}
  getAlarm() async {
    Alarm response = await Api.getAlarmStatus();
    alarmController.sink.add(response); // here im adding new event, therefore streambuilder should rebuild, right?
}

And lastly the code I call to initiate new event(in this case it's firebase message):

if(_message.notification.body.contains("Alarm") && IS_LOGGED_IN == true) {
   alarmBloc.getAlarm();
 }

So the problem is StreamBuilder not rebuilding whenever new event passes through alarmController.stream. What could be the reason?


问:
Problems replacing a substring
Let the string s be

```<code>structure(",SELECTCOLUMNS(FILTER(CG_PART,((CG_PART[0NIVEL4] = \"4.03.01.003\"))  && CG_PART[isEstorno] = 0 ) ,\"Data\",CG_PART[DATA], \"D/C\", CG_PART[D_C],\"Nivel1\", \"(-) Custo de serviços\", \"Nivel2\", \"Custo de Frete de Serviços PJ\",\"Nivel3\", [0NIVEL4],\"Valor\", IF(CG_PART[D_C] = \"D\",-CG_PART[VALORR],CG_PART[VALORR]), \"Ordem Apresentacao\", 7, \"isSub\", 0)")
</code>```

I would like to replace the content:

```<code>\"Nivel1\", \"(-) Custo de serviços\", \"Nivel2\", \"Custo de Frete de
Serviços PJ\",\"Nivel3\", [0NIVEL4],\"Valor\"
</code>```

to this one:

```<code>\"Nivel1\", \"(=) RECEITA OPERACIONAL LÍQUIDA\",\"Nivel2\", \"(=) RECEITA OPERACIONAL
LÍQUIDA\", \"Nivel3\",\"(=) RECEITA OPERACIONAL LÍQUIDA\",\"Valor\"
</code>```

so I've used this code

```<code>init.pos <- str_start(s, "\"Nivel1\"",ignore.case = F)
end.pos <- str_end(s, ",\"Valor\"",ignore.case = F)

substr(s, init.pos, end.pos) <- "\"Nivel1\",  \"(=) RECEITA OPERACIONAL LÍQUIDA\",\"Nivel2\", \"(=) RECEITA OPERACIONAL LÍQUIDA\", \"Nivel3\",\"(=) RECEITA OPERACIONAL LÍQUIDA\", \"Valor\""
</code>```

The problem arises when my sub-string is getting replaced wrongly. It appears that the string used to replace is getting cut in the middle.

Then added in my code this logic:

```<code>middle.pos <- (init.pos+end.pos)/2
substr(s, middle.pos, end.pos) <- "\"Nivel3\",\"(=) RECEITA OPERACIONAL LÍQUIDA\", \"Valor\""
substr(s, init.pos, middle.pos-1) <- "\"Nivel1\",  \"(=) RECEITA OPERACIONAL LÍQUIDA\",\"Nivel2\", \"(=) RECEITA OPERACIONAL LÍQUIDA\","
</code>```

And it got some weird output. I would your help to understand why is this happening.

OBS: The reason why I've used this logic is because I will run my code to replace the content between "Nivel1" and "Valor" with a new content, but the strings between them vary.

答:
You can use gsub to replace the content between "Nivel1" and "Valor" with a new content.</p>

```<code>tt <- "\"(=) RECEITA OPERACIONAL LÍQUIDA\",\"Nivel2\", \"(=) RECEITA OPERACIONAL LÍQUIDA\", \"Nivel3\",\"(=) RECEITA OPERACIONAL LÍQUIDA\","

gsub("(.*\"Nivel1\").*(\"Valor\".*)", paste("\\1", tt, "\\2"), s, ignore.case = FALSE)
</code>```

Title: Problems replacing a substring

Body:
Let the string s be

structure(",SELECTCOLUMNS(FILTER(CG_PART,((CG_PART[0NIVEL4] = \"4.03.01.003\"))  && CG_PART[isEstorno] = 0 ) ,\"Data\",CG_PART[DATA], \"D/C\", CG_PART[D_C],\"Nivel1\", \"(-) Custo de serviços\", \"Nivel2\", \"Custo de Frete de Serviços PJ\",\"Nivel3\", [0NIVEL4],\"Valor\", IF(CG_PART[D_C] = \"D\",-CG_PART[VALORR],CG_PART[VALORR]), \"Ordem Apresentacao\", 7, \"isSub\", 0)")

I would like to replace the content:

\"Nivel1\", \"(-) Custo de serviços\", \"Nivel2\", \"Custo de Frete de
Serviços PJ\",\"Nivel3\", [0NIVEL4],\"Valor\"

to this one:

\"Nivel1\", \"(=) RECEITA OPERACIONAL LÍQUIDA\",\"Nivel2\", \"(=) RECEITA OPERACIONAL
LÍQUIDA\", \"Nivel3\",\"(=) RECEITA OPERACIONAL LÍQUIDA\",\"Valor\"

so I've used this code

init.pos <- str_start(s, "\"Nivel1\"",ignore.case = F)
end.pos <- str_end(s, ",\"Valor\"",ignore.case = F)

substr(s, init.pos, end.pos) <- "\"Nivel1\",  \"(=) RECEITA OPERACIONAL LÍQUIDA\",\"Nivel2\", \"(=) RECEITA OPERACIONAL LÍQUIDA\", \"Nivel3\",\"(=) RECEITA OPERACIONAL LÍQUIDA\", \"Valor\""

The problem arises when my sub-string is getting replaced wrongly. It appears that the string used to replace is getting cut in the middle.

Then added in my code this logic:

middle.pos <- (init.pos+end.pos)/2
substr(s, middle.pos, end.pos) <- "\"Nivel3\",\"(=) RECEITA OPERACIONAL LÍQUIDA\", \"Valor\""
substr(s, init.pos, middle.pos-1) <- "\"Nivel1\",  \"(=) RECEITA OPERACIONAL LÍQUIDA\",\"Nivel2\", \"(=) RECEITA OPERACIONAL LÍQUIDA\","

And it got some weird output. I would your help to understand why is this happening.

OBS: The reason why I've used this logic is because I will run my code to replace the content between "Nivel1" and "Valor" with a new content, but the strings between them vary.

Body:
You can use gsub to replace the content between "Nivel1" and "Valor" with a new content.

tt <- "\"(=) RECEITA OPERACIONAL LÍQUIDA\",\"Nivel2\", \"(=) RECEITA OPERACIONAL LÍQUIDA\", \"Nivel3\",\"(=) RECEITA OPERACIONAL LÍQUIDA\","

gsub("(.*\"Nivel1\").*(\"Valor\".*)", paste("\\1", tt, "\\2"), s, ignore.case = FALSE)


问:
Auto Copy and Paste Cell Values not Formula to another Cell
I also need to get your help for the same issue. I need to copy the cell values and not the formulas automatically to the other Cell, "automatically" meaning, I don't need to click, use mouse, or any other means to do that, like once theres a value on that specific cell (which is derived from a formula), the value will automatically be copied and pasted in the other cell (without any intervention from my part) (Only the value is copied not the formula)

Note:
The cell should contain only the copied value and not the formula.

Scenario:

A1 Cell : has 250 value

B1 Cell : has a vlookup formula to search for the value of A1 cell (I need to use VLOOKUP as there's a lot of items in the list, and it is "Dynamic", the reason I cannot just use formula "=A1" to get the value directly)

C1 Cell : Needs to copy and paste only the plain value from B1 cell which is 250, not including the vlookup formula, it should be automatically copied without any intervention (Cannot use VBA code / Macro as it will be run in excel online)

Thanks!!

答: I managed to find a solution, sharing as might help someone in the future, just needed to use =value(A1), instead of just "=A1", when I did this, the chart can read the values as it is and not the formula behind it. Found another work around as well, by using the formula =A1+0, for some reason this works too. –</p>


问:
mysql Using INNER JOIN to select multiple tables?
I want to select all fields of several table and fetch result separate but mysql return all rows together:

```<code>SELECT prod_product.*
  ,pub_comment.*
FROM prod_product
INNER JOIN pub_comment ON (prod_product.id = pub_comment.itemId)
WHERE prod_product.id=7744
</code>```

Is there any way that i could fetch each table rows separately?

I try @prod:=prod_product.*, @comment:=pub_comment.* but mysql didn't allow me to store more than 1 row.

答:
Execute two queries:

```<code>select * from prod_product WHERE prod_product.id=7744
</code>```

and

```<code>select * from pub_comment WHERE pub_comment.itemId=7744
</code>```

A single query always return single rows containing two table fields.

Anyway: what is the problem of having columns together in a single row? If you have problems with their names you can use aliases.

Body:
I want to select all fields of several table and fetch result separate but mysql return all rows together:

SELECT prod_product.*
  ,pub_comment.*
FROM prod_product
INNER JOIN pub_comment ON (prod_product.id = pub_comment.itemId)
WHERE prod_product.id=7744

Is there any way that i could fetch each table rows separately?

I try @prod:=prod_product.*, @comment:=pub_comment.* but mysql didn't allow me to store more than 1 row.

Body:
Execute two queries:

select * from prod_product WHERE prod_product.id=7744

and

select * from pub_comment WHERE pub_comment.itemId=7744

A single query always return single rows containing two table fields.

Anyway: what is the problem of having columns together in a single row? If you have problems with their names you can use aliases.