问:
Begineer ReactJS
hello everyone I m newbie in ReactJS. I want to send data from child to parent and parent to child and vice versa. I done parent send to child but whenever I do child to send it gave me exception

```<code>index.js:1 Warning: Functions are not valid as a React child. This may happen if you return a Component instead of <Component /> from render. Or maybe you meant to call this function rather than return it.
    in div (at Child.js:17)
    in Child (at Parent.js:35)
    in div (at Parent.js:29).
</code>```

I am fadup this error I tried a lot different thigs from last four days can any one solve it? Here is my code:

This is Parent class:

```<code>import React from 'react';
import './App.css';
import Child from './Child';

class Parent extends React.Component {
    constructor(props) {
        super(props);
        console.log(props);
        this.state={
            counter:''
        };
    this.updateThisCounter = this.updateThisCounter.bind(this);

    this.myChangeHandler = this.myChangeHandler.bind(this);
    this.mySubmitHandler = this.mySubmitHandler.bind(this);
    }
    updateThisCounter(){
    this.setState({counter: this.state.counter + 1});
    }
    mySubmitHandler = (event) => {
        event.preventDefault();
        alert("child send parent " + this.state.counter);
    }
    myChangeHandler = (event) => {
        this.setState({counter: event.target.value});
    }
    render(){
        return(
            <div>
                <h1>Pass Data Child to Parent</h1>
                <input type="text" placeholder="Send Amount to Parent"
                  required value={this.state.counter}
                  onChange={this.myChangeHandler} />
                <span>{this.state.counter}</span>
                <Child triggerParentUpdate={ this.myChangeHandler } />
            </div>
        )
    }
}

export default Parent;
</code>```

This is child class:

```<code>import React from 'react';

class Child extends React.Component {
    constructor(props){
    super(props);
    this.state={
        parent1:''
    };
    this.myChangeHandler1 = this.myChangeHandler1.bind(this);
    }
    myChangeHandler1 = (event) => {
    this.setState({parent1: event.target.value});
    }

    render () {
        return(
            <div>
                <button onClick={this.props.triggerParentUpdate}>
                  Update Parent</button>
                console.log({this.props.triggerParentUpdate}
                <h3>12{this.props.counter}</h3>
                <input type="text" placeholder="After click"
                  required value={this.props.counter}
                  onChange={this.myChangeHandler1} />
                  {/*
                  <h3>{this.props.data.unit}</h3>
                  <button onClick={()=>this.props.data.changeUnit("Child unit")}>
                    Click</button>
                  */}
            </div>
        )
    }
}

export default Child;
</code>```

答:
enter image description here

This is my code
MyCSS.css

```<code>.boxStyleParent{
  border: '10px solid green';
  padding: 50px;
  background: #ccaa00;
  justify-content: center;
  align-items: center;
  width: 30%; height: 400px;
}

.boxStyleChild{
  border: '10px solid blue';
  padding: 80px;
  justify-content: center;
  background: #00aaaa;
  align-items: center;
</code>```

width: 50%; height: 200px;
}

Child.js

```<code>import React from 'react';
import './MyCSS.css';

class Child extends React.Component {
    constructor(props){
    super(props);
    this.state={
      parent:'',
        child:''
    };
    this.myParentChangeHandler = this.myParentChangeHandler.bind(this);
    this.mySubmitHandlerParent = this.mySubmitHandlerParent.bind(this);
    }
    myParentChangeHandler = (event) => {
    this.setState({child: event.target.value});
    }
    mySubmitHandlerParent = (event) => {
      alert("You are submitting " + this.props.triggerParentUpdate);
      event.preventDefault();
    }

    render () {
        return(
          <div className="boxStyleChild">
            <button onClick={this.mySubmitHandlerParent}>Update Parent</button>
            {console.log(this.props.triggerParentUpdate)}
            <br/><br/>
            <h2>Pass Data Parent to Child</h2>
            <input type="text"
                   placeholder="After click"
                   required
                   value={this.props.counter}
                   onChange={this.myParentChangeHandler} />

            <button onClick={this.props.triggerParentUpdate}>Update Child</button>
                {console.log(this.props.triggerParentUpdate)}
              {/*
              <h3>{this.props.data.unit}</h3>
              <button onClick={()=>this.props.data.changeUnit("Child unit")}>
                Click</button>
              */}
          </div>
        )
    }
}

export default Child;
</code>```

Parent class:

```<code>import React from 'react';
import './MyCSS.css';
import Child from './Child';

class Parent extends React.Component {
    constructor(props) {
        super(props);
        console.log(props);
        this.state={
            parent:''
        };
    this.myChangeHandler = this.myChangeHandler.bind(this);
    this.mySubmitHandler = this.mySubmitHandler.bind(this);
    }
    mySubmitHandler = (event) => {
        event.preventDefault();
        alert("child send parent " + this.props.parent);
    }

    myChangeHandler = (event) => {
        this.setState({parent: event.target.value});
    }
    render(){
        return(
            <div className="boxStyleParent">
                <h2>Pass Data Child to Parent</h2>
                <input type="text" placeholder="Send Amount to Parent"
                  required value={this.state.parent}
                  onChange={this.myChangeHandler} />

                <span>{this.props.parent}</span>

                <Child triggerParentUpdate={ this.myChangeHandler } />
            </div>
        )
    }
}

export default Parent;
</code>```

Title: Begineer ReactJS

Body:
hello everyone I m newbie in ReactJS. I want to send data from child to parent and parent to child and vice versa. I done parent send to child but whenever I do child to send it gave me exception

index.js:1 Warning: Functions are not valid as a React child. This may happen if you return a Component instead of <Component /> from render. Or maybe you meant to call this function rather than return it.
    in div (at Child.js:17)
    in Child (at Parent.js:35)
    in div (at Parent.js:29).

I am fadup this error I tried a lot different thigs from last four days can any one solve it? Here is my code:

This is Parent class:

import React from 'react';
import './App.css';
import Child from './Child';

class Parent extends React.Component {
    constructor(props) {
        super(props);
        console.log(props);
        this.state={
            counter:''
        };
    this.updateThisCounter = this.updateThisCounter.bind(this);

    this.myChangeHandler = this.myChangeHandler.bind(this);
    this.mySubmitHandler = this.mySubmitHandler.bind(this);
    }
    updateThisCounter(){
    this.setState({counter: this.state.counter + 1});
    }
    mySubmitHandler = (event) => {
        event.preventDefault();
        alert("child send parent " + this.state.counter);
    }
    myChangeHandler = (event) => {
        this.setState({counter: event.target.value});
    }
    render(){
        return(

Pass Data Child to Parent

                <input type="text" placeholder="Send Amount to Parent"
                  required value={this.state.counter}
                  onChange={this.myChangeHandler} />
                {this.state.counter}
                <Child triggerParentUpdate={ this.myChangeHandler } />

        )
    }
}

export default Parent;

This is child class:

import React from 'react';

class Child extends React.Component {
    constructor(props){
    super(props);
    this.state={
        parent1:''
    };
    this.myChangeHandler1 = this.myChangeHandler1.bind(this);
    }
    myChangeHandler1 = (event) => {
    this.setState({parent1: event.target.value});
    }

    render () {
        return(

                <button onClick={this.props.triggerParentUpdate}>
                  Update Parent</button>
                console.log({this.props.triggerParentUpdate}

12{this.props.counter}

                <input type="text" placeholder="After click"
                  required value={this.props.counter}
                  onChange={this.myChangeHandler1} />
                  {/*

{this.props.data.unit}

                  <button onClick={()=>this.props.data.changeUnit("Child unit")}>
                    Click</button>
                  */}

        )
    }
}

export default Child;

Body:
enter image description here

This is my code
MyCSS.css

.boxStyleParent{
  border: '10px solid green';
  padding: 50px;
  background: #ccaa00;
  justify-content: center;
  align-items: center;
  width: 30%; height: 400px;
}

.boxStyleChild{
  border: '10px solid blue';
  padding: 80px;
  justify-content: center;
  background: #00aaaa;
  align-items: center;

width: 50%; height: 200px;
}

Child.js

import React from 'react';
import './MyCSS.css';

class Child extends React.Component {
    constructor(props){
    super(props);
    this.state={
      parent:'',
        child:''
    };
    this.myParentChangeHandler = this.myParentChangeHandler.bind(this);
    this.mySubmitHandlerParent = this.mySubmitHandlerParent.bind(this);
    }
    myParentChangeHandler = (event) => {
    this.setState({child: event.target.value});
    }
    mySubmitHandlerParent = (event) => {
      alert("You are submitting " + this.props.triggerParentUpdate);
      event.preventDefault();
    }

    render () {
        return(
          <div className="boxStyleChild">
            <button onClick={this.mySubmitHandlerParent}>Update Parent</button>
            {console.log(this.props.triggerParentUpdate)}
            <br/><br/>
            <h2>Pass Data Parent to Child</h2>
            <input type="text"
                   placeholder="After click"
                   required
                   value={this.props.counter}
                   onChange={this.myParentChangeHandler} />

            <button onClick={this.props.triggerParentUpdate}>Update Child</button>
                {console.log(this.props.triggerParentUpdate)}
              {/*
              <h3>{this.props.data.unit}</h3>
              <button onClick={()=>this.props.data.changeUnit("Child unit")}>
                Click</button>
              */}
          </div>
        )
    }
}

export default Child;

Parent class:

import React from 'react';
import './MyCSS.css';
import Child from './Child';

class Parent extends React.Component {
    constructor(props) {
        super(props);
        console.log(props);
        this.state={
            parent:''
        };
    this.myChangeHandler = this.myChangeHandler.bind(this);
    this.mySubmitHandler = this.mySubmitHandler.bind(this);
    }
    mySubmitHandler = (event) => {
        event.preventDefault();
        alert("child send parent " + this.props.parent);
    }

    myChangeHandler = (event) => {
        this.setState({parent: event.target.value});
    }
    render(){
        return(
            <div className="boxStyleParent">
                <h2>Pass Data Child to Parent</h2>
                <input type="text" placeholder="Send Amount to Parent"
                  required value={this.state.parent}
                  onChange={this.myChangeHandler} />

                <span>{this.props.parent}</span>

                <Child triggerParentUpdate={ this.myChangeHandler } />
            </div>
        )
    }
}

export default Parent;


来源: stackexchange

问:
ImportError when use pycharm profile
The problem

I start a flask app, which works fine when I use "run" or "debug." However, I got the error when use "profile," here is the log message

```<code>In folder C:/Users/Myname/PycharmProjects/ProjectName
"C:\Users\Myname\Anaconda3\envs\ProjectName\python.exe" "C:\Program Files\JetBrains\PyCharm
Professional Edition with Anaconda plugin 2019.2.4\helpers\profiler\run_profiler.py" 127.0.0.1 12055 -m flask run
Starting cProfile profiler
Traceback (most recent call last):
Snapshot saved to C:\Users\Myname/.PyCharm2019.2/system\snapshots\ProjectName1.pstat
File "C:\Program Files\JetBrains\PyCharm Professional Edition with Anaconda plugin 2019.2.4\helpers\profiler\run_profiler.py", line 173, in <module>
profiler.run(file)
File "C:\Program Files\JetBrains\PyCharm Professional Edition with Anaconda plugin 2019.2.4\helpers\profiler\run_profiler.py", line 89, in run
execfile(file, globals, globals)  # execute the script
File "C:\Program Files\JetBrains\PyCharm Professional Edition with Anaconda plugin 2019.2.4\helpers\profiler\prof_util.py", line 30, in execfile
exec(compile(contents+"\n", file, 'exec'), glob, loc)
File "C:\Users\Myname\Anaconda3\envs\ProjectName\lib\site-packages\flask\__init__.py", line 19, in <module>
from . import json
ImportError: attempted relative import with no known parent package
</code>```

What I have tried

I google it and found that it is an old problem.

Can't profile module using relative imports

Pycharm profile is not working

How to reproduce it

If you would like to reproduce it, you can create a flask app using pycharm, and then click "profile."

The default code for flask app is as follows. But I don't think it matters.

```<code>from flask import Flask

app = Flask(__name__)

@app.route('/')
def hello_world():
    return 'Hello World!'

if __name__ == '__main__':
    app.run()

</code>```

The error message can be different due to the change of the flask version or Pycharm version, but the reason is the same: File "xxx\lib\site-packages\flask\__init__.py", line 19, in <module> use relative import and cause the ImportError

My question

My question is, is there a way to make it work? Any hacks or tricks are also appreciated. I just want to use the profile now. Thank you

答:
Apparently this is a long-standing issue with PyCharm's profiler, it does not run packages correctly resulting in sys.path being wonky and relative imports failing: https://youtrack.jetbrains.com/issue/PY-28509

I guess an option would be to make your own "launcher script" simply copying what flask.__main__ does.

Though things might also work out if you run -m flask.cli instead of just -m flask (I don't know, I didn't test it): it does the same thing but does not invoke a __main__ file so it could behave better.

ContentLicense: CC BY-SA 4.0

Title: ImportError when use pycharm profile

Body:
The problem

I start a flask app, which works fine when I use "run" or "debug." However, I got the error when use "profile," here is the log message

In folder C:/Users/Myname/PycharmProjects/ProjectName
"C:\Users\Myname\Anaconda3\envs\ProjectName\python.exe" "C:\Program Files\JetBrains\PyCharm
Professional Edition with Anaconda plugin 2019.2.4\helpers\profiler\run_profiler.py" 127.0.0.1 12055 -m flask run
Starting cProfile profiler
Traceback (most recent call last):
Snapshot saved to C:\Users\Myname/.PyCharm2019.2/system\snapshots\ProjectName1.pstat
File "C:\Program Files\JetBrains\PyCharm Professional Edition with Anaconda plugin 2019.2.4\helpers\profiler\run_profiler.py", line 173, in <module>
profiler.run(file)
File "C:\Program Files\JetBrains\PyCharm Professional Edition with Anaconda plugin 2019.2.4\helpers\profiler\run_profiler.py", line 89, in run
execfile(file, globals, globals)  # execute the script
File "C:\Program Files\JetBrains\PyCharm Professional Edition with Anaconda plugin 2019.2.4\helpers\profiler\prof_util.py", line 30, in execfile
exec(compile(contents+"\n", file, 'exec'), glob, loc)
File "C:\Users\Myname\Anaconda3\envs\ProjectName\lib\site-packages\flask\__init__.py", line 19, in <module>
from . import json
ImportError: attempted relative import with no known parent package

What I have tried

I google it and found that it is an old problem.

Can't profile module using relative imports

Pycharm profile is not working

How to reproduce it

If you would like to reproduce it, you can create a flask app using pycharm, and then click "profile."

The default code for flask app is as follows. But I don't think it matters.

from flask import Flask

app = Flask(__name__)

@app.route('/')
def hello_world():
    return 'Hello World!'

if __name__ == '__main__':
    app.run()

The error message can be different due to the change of the flask version or Pycharm version, but the reason is the same: File "xxx\lib\site-packages\flask\__init__.py", line 19, in <module> use relative import and cause the ImportError

My question

My question is, is there a way to make it work? Any hacks or tricks are also appreciated. I just want to use the profile now. Thank you


问:
Nuget Restore of Azure Devops Artifacts from within gulpfile
I'm trying to restore a NuGet package from an Azure Devops Artifact to my local installation as part of a gulpfile script.

However, I'm getting a

Response status code does not indicate success: 401 (Unauthorized).

with:

Unable to load the service index for source https://my-visualstudio-dot-com-npm-feed-here

I've tried creating a nugetauth.npmrc file with the following content:

```<code>registry=https://my-visualstudio-dot-com-npm-feed-here
always-auth=true
</code>```

I then run:

vsts-npm-auth -config nugetauth.npmrc

to generate my new .npmrc file, which I then place in the same directory as my package.json and gulpfile.js files.

When I subsequently run my 'Nuget-restore' task from task runner (with "gulp-nuget-restore": "^0.7.0"), it's failing to authenticate to my feed. What am I missing?

答:
If you want install NuGet package from azure devops artifacts, you should add a nuget.config file to your project, in the same folder as your .csproj or .sln file. Please check this document for more information. Then you can use nuget restore task

If it is a npm package, you should use npm install task.

If you are using the feed from azure devops pipeline. You also need to check if your project build service account have the reader permission to this feed. Please check below steps.

Click the Feed Setting(the gear icon)--> go to Permissions --> Check if group {projectName} build service(OrganizationName) has the permission(Click add groups to add your project build service account if not already existed).

Body:
I'm trying to restore a NuGet package from an Azure Devops Artifact to my local installation as part of a gulpfile script.

However, I'm getting a

Response status code does not indicate success: 401 (Unauthorized).

with:

Unable to load the service index for source https://my-visualstudio-dot-com-npm-feed-here

I've tried creating a nugetauth.npmrc file with the following content:

registry=https://my-visualstudio-dot-com-npm-feed-here
always-auth=true

I then run:

vsts-npm-auth -config nugetauth.npmrc

to generate my new .npmrc file, which I then place in the same directory as my package.json and gulpfile.js files.

When I subsequently run my 'Nuget-restore' task from task runner (with "gulp-nuget-restore": "^0.7.0"), it's failing to authenticate to my feed. What am I missing?


问:
How to clean csv file from non-word characters and remove words that contain them in python?
I am trying to clean a .csv file from all non-word characters for LDA model, however after I clean it using:

words = [re.sub(r'\W+','', st) for st in words]
```

<p>I get some 'junk' leftover that may affect the model. </p>

<p>I tried doing this:</p>

<pre class="lang-py prettyprint-override"><code>words = [re.sub(r'\W+',',', st) for st in words]
</code>```

but it doesn't seem to solve the issue. Is there a way to delete all the characters that are before or after these non-word characters as well?

If I run the code without re.sub line, what I get is:

```<code>>>>'set', 'editorial//a/aeaf-e', '-bd-frd/afac,,', 'photo', 'ab-ddf,', 'recording', 'record', 'belief', 'institution', 'change'
</code>```

After running it with re.sub line I get this:

```<code>>>>'set', 'editorialaaeafe', 'bdfrdafac', 'photo', 'abddf', 'recording', 'record', 'belief', 'institution', 'change'
</code>```

What I want to get is:

```<code> >>>'set', 'photo', 'recording', 'record', 'belief', 'institution', 'change'
</code>```

答:
You have to test each word of the list against the regex. As the expression will be used more than once, it is better to compile it first:

```<code>reject = re.compile(r'\W+')
[w for w in words if not reject.search(w)]
</code>```

You could also use a positive version:

```<code>clean = re.compile(r'\w+$')
[w for w in words if clean.match(w)]
</code>```

From your sample input, both snippets give as expected:

```<code>['set', 'photo', 'recording', 'record', 'belief', 'institution', 'change']
</code>```

Body:
I am trying to clean a .csv file from all non-word characters for LDA model, however after I clean it using:

words = [re.sub(r'\W+','', st) for st in words]

I get some 'junk' leftover that may affect the model.

I tried doing this:

words = [re.sub(r'\W+',',', st) for st in words]

but it doesn't seem to solve the issue. Is there a way to delete all the characters that are before or after these non-word characters as well?

If I run the code without re.sub line, what I get is:

>>>'set', 'editorial//a/aeaf-e', '-bd-frd/afac,,', 'photo', 'ab-ddf,', 'recording', 'record', 'belief', 'institution', 'change'

After running it with re.sub line I get this:

>>>'set', 'editorialaaeafe', 'bdfrdafac', 'photo', 'abddf', 'recording', 'record', 'belief', 'institution', 'change'

What I want to get is:

 >>>'set', 'photo', 'recording', 'record', 'belief', 'institution', 'change'

Body:
You have to test each word of the list against the regex. As the expression will be used more than once, it is better to compile it first:

reject = re.compile(r'\W+')
[w for w in words if not reject.search(w)]

You could also use a positive version:

clean = re.compile(r'\w+$')
[w for w in words if clean.match(w)]

From your sample input, both snippets give as expected:

['set', 'photo', 'recording', 'record', 'belief', 'institution', 'change']


问:
How to convert from android.graphics.Bitmap to javascript ImageData in NativeScript?
Is there any existing libraries that I can easily convert a android.graphics.Bitmap object to Javascript ImageData?  I am using NativeScript to build an app that takes Bitmap from camera and use tfjs for further processing.  The tfjs library requires to use ImageData as an input.

In the Android part, I have the android.graphics.Bitmap object ready, which is an output from my TextureView.

```<code>var bitmap = myTextureView.getBitmap();
</code>```

https://developer.android.com/reference/android/view/TextureView#getBitmap(int,%20int)

In the Tensorflow part, I need to first convert it into ImageData type.

```<code>const segmentation = await net.segmentPerson(img);
</code>```

https://github.com/tensorflow/tfjs-models/tree/master/body-pix

https://developer.mozilla.org/en-US/docs/Web/API/ImageData

答:
NativeScript !== Browser

{N} just gives you a JS runtime, it's not a Browser or WebView. It's just a way for you to reuse your web skills but you can't expect all browser dependent APIs to work here.

Thats being said, you have to take a closer look at the ImageSource module which is kind of alternate for ImageData here. But still it may not work with tfjs and I doubt tfjs works at all with {N} without significant efforts.

I see that tfjs is trying to support ReactNative, not sure how far they have got. But I presume they do it by exposing C++ APIs into native app, the same could be ported into {N} but that would require significant efforts.

So I would suggest you to find a plugin Or native equivalent on iOS / Android, which you may directly be able to use in your project.

Body:
Is there any existing libraries that I can easily convert a android.graphics.Bitmap object to Javascript ImageData?  I am using NativeScript to build an app that takes Bitmap from camera and use tfjs for further processing.  The tfjs library requires to use ImageData as an input.

In the Android part, I have the android.graphics.Bitmap object ready, which is an output from my TextureView.

var bitmap = myTextureView.getBitmap();

https://developer.android.com/reference/android/view/TextureView#getBitmap(int,%20int)

In the Tensorflow part, I need to first convert it into ImageData type.

const segmentation = await net.segmentPerson(img);

https://github.com/tensorflow/tfjs-models/tree/master/body-pix

https://developer.mozilla.org/en-US/docs/Web/API/ImageData


问:
Explicit line joining in Python
I am reading a file, line-by-line and doing some text processing in order to get output in a certain format
My string processing code goes as follows:

```<code>file1=open('/myfolder/testfile.txt')
scanlines=file1.readlines()
string = ''

 for line in scanlines:
    if line.startswith('>from'):
         continue
    if line.startswith('*'):
        continue
    string.join(line.rstrip('\n'))
</code>```

The output of this code is as follows:

abc

def

ghi

Is there a way to join these physical lines into one logical line, e.g:

abcdefghi

Basically, how can I concatenate multiple strings into one large string?

If I was reading from a file with very long strings is there the risk of an overflow by concatenating multiple physical lines into one logical line?

答:
Cleaning things up a bit, it would be easiest to append to array and then return the result

```<code>def joinfile(filename) :
   sarray = []
   with open(filename) as fd :
       for line in fd :
           if line.startswith('>from') or line.startswith('*'):
               continue
          sarray.append(line.rstrip('\n'))
   return ''.join(sarray)
</code>```

If you wanted to get really cute you could also do the following:

```<code>fd = open(filename)
str = ''.join([line.rstrip('\n') for line in fd if not (line.startswith('>from') or line.startswith('*'))])
</code>```

Yes of course you could read a file big enough to overflow memory.

ContentLicense: CC BY-SA 3.0

Title: Explicit line joining in Python

Body:
I am reading a file, line-by-line and doing some text processing in order to get output in a certain format
My string processing code goes as follows:

file1=open('/myfolder/testfile.txt')
scanlines=file1.readlines()
string = ''

 for line in scanlines:
    if line.startswith('>from'):
         continue
    if line.startswith('*'):
        continue
    string.join(line.rstrip('\n'))

The output of this code is as follows:

abc

def

ghi

Is there a way to join these physical lines into one logical line, e.g:

abcdefghi

Basically, how can I concatenate multiple strings into one large string?

If I was reading from a file with very long strings is there the risk of an overflow by concatenating multiple physical lines into one logical line?

Body:
Cleaning things up a bit, it would be easiest to append to array and then return the result

def joinfile(filename) :
   sarray = []
   with open(filename) as fd :
       for line in fd :
           if line.startswith('>from') or line.startswith('*'):
               continue
          sarray.append(line.rstrip('\n'))
   return ''.join(sarray)

If you wanted to get really cute you could also do the following:

fd = open(filename)
str = ''.join([line.rstrip('\n') for line in fd if not (line.startswith('>from') or line.startswith('*'))])

Yes of course you could read a file big enough to overflow memory.


问:
I am unable to run truffle commands (truffle compile, truffle init, or even truffle version) on terminal
-bash: truffle: command not found

Tried installing different versions of npm, node.js, truffle and nothing would work. Is there something wrong with the settings/permissions of my terminal?

答:
Try to install Truffle in admin mode and install as global.
like: npm install -g truffle
This should work fine now.</p>


问:
Setting entire register array to zero
I want to set all the registers in the array to zero. However, I've parametrized the sizing of the array:

```<code>logic [WIDTH-2:0] numelem [0:MAXBITS-1];
</code>```

Is there a way where I could essentially do numelem <= {0,0,0,0,...} but for a generic size? The method preferably needs to be non-blocking since I need to do the assignment within an always_ff block. Thanks.

答:
```<code>logic [WIDTH-2:0] numelem [0:MAXBITS-1] = '{default:'0};
</code>```

Title: Setting entire register array to zero

Body:
I want to set all the registers in the array to zero. However, I've parametrized the sizing of the array:

logic [WIDTH-2:0] numelem [0:MAXBITS-1];

Is there a way where I could essentially do numelem <= {0,0,0,0,...} but for a generic size? The method preferably needs to be non-blocking since I need to do the assignment within an always_ff block. Thanks.


问:
sending email with cakephp2
I'm having problems sending a mail with cakephp2, I know I can send emails because I have my postfix configured, and I can send e-mails with command line or php. So please, can you send me an example of cakephp2 sending emails.

This is the error message

Invalid email: "you@localhost"
Error: An Internal Error Has Occurred.

I've also tried with the ssl via gmail and it doesn't work either, and it's giving me a really hard time.

thanks guys

by the way, I'm trying the exact example of this url http://book.cakephp.org/2.0/en/core-utility-libraries/email.html

答:
```<code>In app/config/Email

public $smtp = array(
        'transport' => 'Smtp',
        'from' => array('no-reply@xyz.com' => 'no-reply@xyz.com'),
        'host' => 'ssl://smtp.abc.com',
        'port' => 465,
        'timeout' => 30,
        'username' => 'username',
        'password' => 'password',
        'client' => null,
        'log' => false,
    );

In Your Controller

App::uses('AppController', 'Controller');
App::uses('CakeEmail', 'Network/Email');

public function index()
    {
        $this->layout = 'layout';
        $this->set('title', "Title");
        if ($this->request->is('Post')) {
            if (!empty($this->request->data)) {
                if ($this->Modal->Save($this->request->data)) {
                    $to = 'test@anc.com';
                    $subject = 'Your_subject';
                    $message = $this->request->data;
                    if ($this->sendmail($to, $subject, $message)) {

                        echo"sent";die;
                    }
                } else {
                    echo"wrong";die;
                }
            }
        }
    }
    public function sendmail($to = null, $subject = '', $messages = null, $ccParam = null, $from = null, $reply = null, $path = null, $file_name = null)
    {
        $this->layout = false;
        $this->render(false);
        $name = $messages['Modalname']['name'];
        $email = $messages['Modalname']['email'];
        $Email = new CakeEmail();
        $Email->config('smtp');
        $Email->viewVars(array('name' => $name, 'email' => $email));
        $Email->template('comman_email_template', 'comman_email_template');
        return $Email->emailFormat('html')
            ->from(array('no-reply@xyz.com' => 'no-reply@xyz.com'))
            ->to($to)
            ->subject($subject)
            ->send();
    }
</code>```

Create a layout and view for email template.and add the data value that have been sent.

Title: sending email with cakephp2

Body:
In app/config/Email

public $smtp = array(
        'transport' => 'Smtp',
        'from' => array('no-reply@xyz.com' => 'no-reply@xyz.com'),
        'host' => 'ssl://smtp.abc.com',
        'port' => 465,
        'timeout' => 30,
        'username' => 'username',
        'password' => 'password',
        'client' => null,
        'log' => false,
    );

In Your Controller

App::uses('AppController', 'Controller');
App::uses('CakeEmail', 'Network/Email');

public function index()
    {
        $this->layout = 'layout';
        $this->set('title', "Title");
        if ($this->request->is('Post')) {
            if (!empty($this->request->data)) {
                if ($this->Modal->Save($this->request->data)) {
                    $to = 'test@anc.com';
                    $subject = 'Your_subject';
                    $message = $this->request->data;
                    if ($this->sendmail($to, $subject, $message)) {

                        echo"sent";die;
                    }
                } else {
                    echo"wrong";die;
                }
            }
        }
    }
    public function sendmail($to = null, $subject = '', $messages = null, $ccParam = null, $from = null, $reply = null, $path = null, $file_name = null)
    {
        $this->layout = false;
        $this->render(false);
        $name = $messages['Modalname']['name'];
        $email = $messages['Modalname']['email'];
        $Email = new CakeEmail();
        $Email->config('smtp');
        $Email->viewVars(array('name' => $name, 'email' => $email));
        $Email->template('comman_email_template', 'comman_email_template');
        return $Email->emailFormat('html')
            ->from(array('no-reply@xyz.com' => 'no-reply@xyz.com'))
            ->to($to)
            ->subject($subject)
            ->send();
    }

Create a layout and view for email template.and add the data value that have been sent.


问:
navLinks.forEach is not a function
I am making a Responsive Navigation bar and i don't know what is the problem in the function. it should work because the navLinks is defined. So can anyone tell me what is the problem here?

const navSlide = () => {
  const burger = document.querySelector('.burger');
  const nav = document.querySelector('.nav-links');
  const navLinks = document.querySelector('.nav-links li');
  //Toggle Nav
  burger.addEventListener('click', () => {
    nav.classList.toggle('nav-active');
  });
  //Animate Links
  navLinks.forEach((link, index) => {
    link.style.animation = `navLinkFade 0.5s ease forwards ${index / 7}s`;
  });
}

navSlide();
```

答:
ok, i think you need for loop for each li then you can do it by using $(selector).each. In $(this) get control and index get index of control

$(document).ready(function(){//Code for Each li
$('ul>li').each(function(index){console.log(this);console.log(index);});
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>jQuery.each demo</title>
  <style>

  </style>
  <script src="https://code.jquery.com/jquery-3.4.1.js"></script>
</head>
<body>

<ul>
<li>1</li>
<li>2</li>
<li>3</li>
<li>4</li>
<li>5</li>
</ul>

</body>
</html>
<script href="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/core.js"></script></code>```

Title: navLinks.forEach is not a function

Body:
ok, i think you need for loop for each li then you can do it by using $(selector).each. In $(this) get control and index get index of control

$(document).ready(function(){//Code for Each li
$('ul>li').each(function(index){console.log(this);console.log(index);});
});

<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>jQuery.each demo</title>
  <style>

  </style>
  <script src="https://code.jquery.com/jquery-3.4.1.js"></script>
</head>
<body>

<ul>
<li>1</li>
<li>2</li>
<li>3</li>
<li>4</li>
<li>5</li>
</ul>

</body>
</html>
<script href="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/core.js"></script>


问:
Parse json array string using jsoncpp
I have this JSON:

```<code>[{"header": "test" , "test2" : "test2"}]
</code>```

I'm trying to parse this using jsoncpp.

Here's my code snippet:

```<code> Json::CharReaderBuilder builder;
 Json::CharReader *reader = builder.newCharReader();
 Json::Value root;
 bool parseRet = reader->parse(serverResponse.c_str(),serverResponse.c_str() +serverResponse.size(), &root, &errors);
</code>```

parseRet returns true. But root does not include json data.

How do I parse this?

答:
parseRet returns true. But root does not include JSON data.

This sounds like an issue with the way you're accessing the parsed JSON elements.

Below is a complete working example with a raw string literal as JSON input.

A few points:

Use std::unique_ptr for reader to de-allocate memory appropriately at the end. In your code snippet, it's a memory leak.

Read the documentation carefully! Accessing an element using a method or operator might return a default value or an exception so handle accordingly. For example, the JSON in root is an array so it should be accessed by index and then each index contains an object i.e. root[0]["header"].

Example (C++11):

```<code>#include <iostream>
#include <string>
#include <memory>
#include <jsoncpp/json/json.h>

int main()
{
    const std::string raw_json = R"json([{"header": "test" , "test2" : "test2"}])json";

    Json::CharReaderBuilder builder {};

    // Don't leak memory! Use std::unique_ptr!
    auto reader = std::unique_ptr<Json::CharReader>( builder.newCharReader() );

    Json::Value root {};
    std::string errors {};
    const auto is_parsed = reader->parse( raw_json.c_str(),
                                          raw_json.c_str() + raw_json.length(),
                                          &root,
                                          &errors );
    if ( !is_parsed )
    {
        std::cerr << "ERROR: Could not parse! " << errors << '\n';
        return -1;
    }

    std::cout << "Parsed JSON:\n" << root << "\n\n";

    try
    {
        std::cout << "header: " << root[0]["header"] << '\n';
        std::cout << "test2 : " << root[0]["test2"] << '\n';
    }
    catch ( const Json::Exception& e )
    {
        std::cerr << e.what() << '\n';
    }

    return 0;
}
</code>```

Output:

```<code>Parsed JSON:
[
    {
        "header" : "test",
        "test2" : "test2"
    }
]

header: "test"
test2 : "test2"
</code>```

Title: Parse json array string using jsoncpp

Body:
I have this JSON:

[{"header": "test" , "test2" : "test2"}]

I'm trying to parse this using jsoncpp.

Here's my code snippet:

 Json::CharReaderBuilder builder;
 Json::CharReader *reader = builder.newCharReader();
 Json::Value root;
 bool parseRet = reader->parse(serverResponse.c_str(),serverResponse.c_str() +serverResponse.size(), &root, &errors);

parseRet returns true. But root does not include json data.

How do I parse this?

Body:
parseRet returns true. But root does not include JSON data.

This sounds like an issue with the way you're accessing the parsed JSON elements.

Below is a complete working example with a raw string literal as JSON input.

A few points:

Use std::unique_ptr for reader to de-allocate memory appropriately at the end. In your code snippet, it's a memory leak.

Read the documentation carefully! Accessing an element using a method or operator might return a default value or an exception so handle accordingly. For example, the JSON in root is an array so it should be accessed by index and then each index contains an object i.e. root[0]["header"].

Example (C++11):

#include <iostream>
#include <string>
#include <memory>
#include <jsoncpp/json/json.h>

int main()
{
    const std::string raw_json = R"json([{"header": "test" , "test2" : "test2"}])json";

    Json::CharReaderBuilder builder {};

    // Don't leak memory! Use std::unique_ptr!
    auto reader = std::unique_ptr<Json::CharReader>( builder.newCharReader() );

    Json::Value root {};
    std::string errors {};
    const auto is_parsed = reader->parse( raw_json.c_str(),
                                          raw_json.c_str() + raw_json.length(),
                                          &root,
                                          &errors );
    if ( !is_parsed )
    {
        std::cerr << "ERROR: Could not parse! " << errors << '\n';
        return -1;
    }

    std::cout << "Parsed JSON:\n" << root << "\n\n";

    try
    {
        std::cout << "header: " << root[0]["header"] << '\n';
        std::cout << "test2 : " << root[0]["test2"] << '\n';
    }
    catch ( const Json::Exception& e )
    {
        std::cerr << e.what() << '\n';
    }

    return 0;
}

Output:

Parsed JSON:
[
    {
        "header" : "test",
        "test2" : "test2"
    }
]

header: "test"
test2 : "test2"


问:
PHP form not writing to mySQL database
I'm just learning PHP and am trying the most basic thing: capturing info from a form and sticking it into a table in a mySQL database.  I'm embarrassed to ask such a stupid newbie question, but after reviewing two books, several Stack Overflow posts, and 7 different tutorials, I still can't get my pathetic code to write a few lousy metrics to my database.

Here's the latest version of the code.  Could someone please tell me what I am doing wrong?

* Basic HTML Form *

```<code><form method="post" action="post_metrics_stack.php" >
<p>Date<br />
<input name="date" type="text" /></p>

<p>Metric1<br />
<input name="metric1" type="text" /></p>

<p>Metric2<br />
<input name="metric2" type="text" /></p>

<input type="submit" name="submit" value="Submit" />
</form>
</code>```

* Processor File *

```<code><?php

$date=$_POST['date'];
$metric1=$_POST['metric1'];
$metric2=$_POST['metric2'];

$con = mysql_connect("localhost", "root", "mypassword");
if (!$con)
  {die('Could not connect to mysql: ' . mysql_error());}

$mydb = mysql_select_db("mydatabasename");
if (!$mydb)
  {die('Could not connect to database: ' . mysql_error());}

mysql_query("INSERT INTO my_metrics VALUES ('$date', '$metric1', '$metric2')");
 Print "Your metrics have been successfully added to the database.";

mysql_close($con);
?>
</code>```

答:
Here you go love :) try W3c it a good place for new pepps</p>

```<code> <?php
    $con = mysql_connect("localhost","peter","abc123");
    if (!$con)
      {
      die('Could not connect: ' . mysql_error());
      }

    mysql_select_db("my_db", $con);

    $sql="INSERT INTO my_metrics (date, metric1, metric2)
    VALUES
    ('$_POST[date]','$_POST[mertric1]','$_POST[metric2]')";

    if (!mysql_query($sql,$con))
      {
      die('Error: ' . mysql_error());
      }
    echo "Your metrics have been successfully added to the database.";

    mysql_close($con)
    ?>
</code>```

Title: PHP form not writing to mySQL database

Body:
I'm just learning PHP and am trying the most basic thing: capturing info from a form and sticking it into a table in a mySQL database.  I'm embarrassed to ask such a stupid newbie question, but after reviewing two books, several Stack Overflow posts, and 7 different tutorials, I still can't get my pathetic code to write a few lousy metrics to my database.

Here's the latest version of the code.  Could someone please tell me what I am doing wrong?

* Basic HTML Form *

<form method="post" action="post_metrics_stack.php" >

Date

<input name="date" type="text" />

Metric1

<input name="metric1" type="text" />

Metric2

<input name="metric2" type="text" />

<input type="submit" name="submit" value="Submit" />
</form>

* Processor File *

<?php

$date=$_POST['date'];
$metric1=$_POST['metric1'];
$metric2=$_POST['metric2'];

$con = mysql_connect("localhost", "root", "mypassword");
if (!$con)
  {die('Could not connect to mysql: ' . mysql_error());}

$mydb = mysql_select_db("mydatabasename");
if (!$mydb)
  {die('Could not connect to database: ' . mysql_error());}

mysql_query("INSERT INTO my_metrics VALUES ('$date', '$metric1', '$metric2')");
 Print "Your metrics have been successfully added to the database.";

mysql_close($con);
?>

Body:
Here you go love :) try W3c it a good place for new pepps

 <?php
    $con = mysql_connect("localhost","peter","abc123");
    if (!$con)
      {
      die('Could not connect: ' . mysql_error());
      }

    mysql_select_db("my_db", $con);

    $sql="INSERT INTO my_metrics (date, metric1, metric2)
    VALUES
    ('$_POST[date]','$_POST[mertric1]','$_POST[metric2]')";

    if (!mysql_query($sql,$con))
      {
      die('Error: ' . mysql_error());
      }
    echo "Your metrics have been successfully added to the database.";

    mysql_close($con)
    ?>


问:
Cache static files by content type in Spring Boot
I'm trying to set up caching headers on specific static file type in Spring Boot.
In directory src/main/resources/static there are few subdirectories with different file types:

```<code>src/main/resources/static/font   --> *.otf
src/main/resources/static/lib    --> *.js
src/main/resources/static/images --> *.png, *.jpg
</code>```

Is there a way to put cache headers by file type inside Spring configuration?

```<code>*.otf 365 days
*.png 30 days
*.jpg 7 days
</code>```

Spring version is 5.2.3 and Spring Boot 2.2.4 - is there a chance that Spring Boot deals with it and makes it not work?

Tried with

```<code>@Override
public void addResourceHandlers(final ResourceHandlerRegistry registry) {
    final CacheControl oneYearPublic =
        CacheControl.maxAge(365, TimeUnit.DAYS).cachePublic();
    // it does not "work" with "/static/fonts/"
    registry
        .addResourceHandler("/fonts/{filename:\\w+\\.otf}")
        .setCacheControl(oneYearPublic);
}
</code>```

but I get weird results. When checking with Network tab of DevTools I get these headers:

```<code>    Cache-Control: no-cache, no-store, max-age=0, must-revalidate
    Pragma: no-cache
    Expires: 0
</code>```

But when I go to the URL directly, I get 404

```<code>http://localhost/fonts/1952RHEINMETALL.otf
</code>```

Without any configuration I get "no-store" Cache-Control header.

答:
I've managed to have a working solution for this problem. Check the GitHub repo https://github.com/alexsomai/cache-static-assets.

This is an example of config that should work:

```<code>@Configuration
public class WebConfig implements WebMvcConfigurer {

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        Objects.requireNonNull(registry);

        // could use either '/**/images/{filename:\w+\.png}' or '/**/images/*.png'
        registry.addResourceHandler("/**/images/{filename:\\w+\\.png}")
                .addResourceLocations("classpath:/static/")
                .setCacheControl(CacheControl.maxAge(1, TimeUnit.DAYS));

        registry.addResourceHandler("/**/images/*.jpg")
                .addResourceLocations("classpath:/static/")
                .setCacheControl(CacheControl.maxAge(2, TimeUnit.DAYS));

        registry.addResourceHandler("/**/lib/*.js")
                .addResourceLocations("classpath:/static/")
                .setCacheControl(CacheControl.maxAge(3, TimeUnit.DAYS));
    }
}
</code>```

You could easily adjust it for your needs, based on file type and cache duration.

As key takeaways, make sure to add the addResourceLocations function (without this one, you get 404). Plus, if you are using Spring Boot, you don't need the @EnableWebMvc, as it was initially posted in this example https://stackoverflow.com/a/33216168/6908551.

Body:
I'm trying to set up caching headers on specific static file type in Spring Boot.
In directory src/main/resources/static there are few subdirectories with different file types:

src/main/resources/static/font   --> *.otf
src/main/resources/static/lib    --> *.js
src/main/resources/static/images --> *.png, *.jpg

Is there a way to put cache headers by file type inside Spring configuration?

*.otf 365 days
*.png 30 days
*.jpg 7 days

Spring version is 5.2.3 and Spring Boot 2.2.4 - is there a chance that Spring Boot deals with it and makes it not work?

Tried with

@Override
public void addResourceHandlers(final ResourceHandlerRegistry registry) {
    final CacheControl oneYearPublic =
        CacheControl.maxAge(365, TimeUnit.DAYS).cachePublic();
    // it does not "work" with "/static/fonts/"
    registry
        .addResourceHandler("/fonts/{filename:\\w+\\.otf}")
        .setCacheControl(oneYearPublic);
}

but I get weird results. When checking with Network tab of DevTools I get these headers:

    Cache-Control: no-cache, no-store, max-age=0, must-revalidate
    Pragma: no-cache
    Expires: 0

But when I go to the URL directly, I get 404

http://localhost/fonts/1952RHEINMETALL.otf

Without any configuration I get "no-store" Cache-Control header.

Body:
I've managed to have a working solution for this problem. Check the GitHub repo https://github.com/alexsomai/cache-static-assets.

This is an example of config that should work:

@Configuration
public class WebConfig implements WebMvcConfigurer {

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        Objects.requireNonNull(registry);

        // could use either '/**/images/{filename:\w+\.png}' or '/**/images/*.png'
        registry.addResourceHandler("/**/images/{filename:\\w+\\.png}")
                .addResourceLocations("classpath:/static/")
                .setCacheControl(CacheControl.maxAge(1, TimeUnit.DAYS));

        registry.addResourceHandler("/**/images/*.jpg")
                .addResourceLocations("classpath:/static/")
                .setCacheControl(CacheControl.maxAge(2, TimeUnit.DAYS));

        registry.addResourceHandler("/**/lib/*.js")
                .addResourceLocations("classpath:/static/")
                .setCacheControl(CacheControl.maxAge(3, TimeUnit.DAYS));
    }
}

You could easily adjust it for your needs, based on file type and cache duration.

As key takeaways, make sure to add the addResourceLocations function (without this one, you get 404). Plus, if you are using Spring Boot, you don't need the @EnableWebMvc, as it was initially posted in this example https://stackoverflow.com/a/33216168/6908551.


问:
Spark Dataframe: Group and rank rows on a certain column value
I am trying to rank a column when the "ID" column numbering starts from 1 to max and then resets from 1.

So, the first three rows have a continuous numbering on "ID"; hence these should be grouped with group rank =1. Rows four and five are in another group, group rank = 2.

The rows are sorted by "rownum" column. I am aware of the row_number window function but I don't think I can apply for this use case as there is no constant window. I can only think of looping through each row in the dataframe but not sure how I can update a column when number resets to 1.

val df = Seq(
    (1, 1 ),
    (2, 2 ),
    (3, 3 ),
    (4, 1),
    (5, 2),
    (6, 1),
    (7, 1),
    (8, 2)
  ).toDF("rownum", "ID")
  df.show()

Expected result is below:

答:
As @Prithvi noted, we can use lead here.

The tricky part is in order to use window function such as lead, we need to at least provide the order.

Consider

val nextID = lag('ID, 1, -1) over Window.orderBy('rownum)
val isNewGroup = 'ID <= nextID cast "integer"
val group_rank_of_ID = sum(isNewGroup) over Window.orderBy('rownum)

/* you can try
df.withColumn("intermediate", nextID).show
//                           ^^^^^^^-- can be `isNewGroup`, or other vals
*/

df.withColumn("group_rank_of_ID", group_rank_of_ID).show

/* returns
+------+---+----------------+
|rownum| ID|group_rank_of_ID|
+------+---+----------------+
|     1|  1|               0|
|     2|  2|               0|
|     3|  3|               0|
|     4|  1|               1|
|     5|  2|               1|
|     6|  1|               2|
|     7|  1|               3|
|     8|  2|               3|
+------+---+----------------+
*/

df.withColumn("group_rank_of_ID", group_rank_of_ID + 1).show

/* returns
+------+---+----------------+
|rownum| ID|group_rank_of_ID|
+------+---+----------------+
|     1|  1|               1|
|     2|  2|               1|
|     3|  3|               1|
|     4|  1|               2|
|     5|  2|               2|
|     6|  1|               3|
|     7|  1|               4|
|     8|  2|               4|
+------+---+----------------+
*/
```


问:
Unity 3d Invokerepeating for blinking Images
I am working on a car game project. I have made a UI Panel in which there are two UI Images (Left_Image and Right_Image). When I press "left" button then Left_Image starts blinking and when i press "right" button the Right_Image starts blinking. but what i want is that if Right_Image is already blinking and I press "left" button then Left_Image starts blink but Right_Images should be stopped. I have tried every trick but no luck. Please help.</p>

```<code>using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Indicators_UI : MonoBehaviour {

    public GameObject flash_right;
    public GameObject flash_left;

    public float interval;

    void Start()
    {
        InvokeRepeating("RightFlash", 0, interval);
        InvokeRepeating("LeftFlash", 0, interval);
    }

    void Update ()
    {
        if (ControlFreak2.CF2Input.GetAxis ("right") != 0) {

            if (!IsInvoking("RightFlash"))
                InvokeRepeating("RightFlash", 0.35f, 0.35f);
        }
        else
        {
            CancelInvoke("RightFlash");
        }
        if (ControlFreak2.CF2Input.GetAxis ("left") != 0) {
            if (!IsInvoking("LeftFlash"))
                InvokeRepeating("LeftFlash", 0.35f, 0.35f);
        }
        else
        {
            CancelInvoke("LeftFlash");
        }
    }

    void RightFlash()
    {
        if(flash_right.activeSelf)
            flash_right.SetActive(false);
        else
            flash_right.SetActive(true);
    }

    void LeftFlash()
    {
        if(flash_left.activeSelf)
            flash_left.SetActive(false);
        else
            flash_left.SetActive(true);
    }
}
</code>```

答:
In general don't use InvokeRepeating etc with string! It is not very maintainable to call methods via their names. If you want to use them at least rather use nameof to be sure the name is not misspelled.

Then can't you just do

```<code>void Update ()
{
    if (ControlFreak2.CF2Input.GetAxis ("right") != 0)
    {
        if (!IsInvoking(nameof(RightFlash)))
        {
            if(IsInvoking(nameof(LeftFlash)) CancelInvoke(nameof(LeftFlash));

            InvokeRepeating(nameof(RightFlash), 0.35f, 0.35f);
        }
    }
    else
    {
        CancelInvoke(nameof(RightFlash));
    }

    if (ControlFreak2.CF2Input.GetAxis ("left") != 0)
    {
        if (!IsInvoking(nameof(LeftFlash)))
        {
            if(IsInvoking(nameof(RightFlash)) CancelInvoke(nameof(RightFlash));

            InvokeRepeating(nameof(LeftFlash), 0.35f, 0.35f);
        }
    }
    else
    {
        CancelInvoke(nameof(LeftFlash));
    }
}

// Btw: These you can implement way shorter this way ;)
void RightFlash()
{
    flash_right.SetActive(!flash_right.activeSelf);
}

void LeftFlash()
{
    flash_left.SetActive(!flash_left.activeSelf);
}
</code>```

In your case I would actually rather use simple timers since you need the Update method anyway for getting the user input so why overcomplicating:

```<code>private float timerLeft;
private float timerRight;

void Update ()
{
    if (ControlFreak2.CF2Input.GetAxis ("right") != 0)
    {
        timerRight -= Time.deltaTime;
        if (timerRight <= 0)
        {
            timerRight = interval;

            RightFlash();
        }
    }
    // simply make them exclusive so only one button is handled at a time
    // if you press both at the same time right overrules
    else if (ControlFreak2.CF2Input.GetAxis ("left") != 0)
    {
        timerLeft -= Time.deltaTime;
        if (timerLeft <= 0)
        {
            timerLeft = interval;

            LeftFlash();
        }
    }
}

void RightFlash()
{
    flash_right.SetActive(!flash_right.activeSelf);
}

void LeftFlash()
{
    flash_left.SetActive(!flash_left.activeSelf);
}
</code>```

Body:
I am working on a car game project. I have made a UI Panel in which there are two UI Images (Left_Image and Right_Image). When I press "left" button then Left_Image starts blinking and when i press "right" button the Right_Image starts blinking. but what i want is that if Right_Image is already blinking and I press "left" button then Left_Image starts blink but Right_Images should be stopped. I have tried every trick but no luck. Please help.

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Indicators_UI : MonoBehaviour {

    public GameObject flash_right;
    public GameObject flash_left;

    public float interval;

    void Start()
    {
        InvokeRepeating("RightFlash", 0, interval);
        InvokeRepeating("LeftFlash", 0, interval);
    }

    void Update ()
    {
        if (ControlFreak2.CF2Input.GetAxis ("right") != 0) {

            if (!IsInvoking("RightFlash"))
                InvokeRepeating("RightFlash", 0.35f, 0.35f);
        }
        else
        {
            CancelInvoke("RightFlash");
        }
        if (ControlFreak2.CF2Input.GetAxis ("left") != 0) {
            if (!IsInvoking("LeftFlash"))
                InvokeRepeating("LeftFlash", 0.35f, 0.35f);
        }
        else
        {
            CancelInvoke("LeftFlash");
        }
    }

    void RightFlash()
    {
        if(flash_right.activeSelf)
            flash_right.SetActive(false);
        else
            flash_right.SetActive(true);
    }

    void LeftFlash()
    {
        if(flash_left.activeSelf)
            flash_left.SetActive(false);
        else
            flash_left.SetActive(true);
    }
}

Body:
In general don't use InvokeRepeating etc with string! It is not very maintainable to call methods via their names. If you want to use them at least rather use nameof to be sure the name is not misspelled.

Then can't you just do

void Update ()
{
    if (ControlFreak2.CF2Input.GetAxis ("right") != 0)
    {
        if (!IsInvoking(nameof(RightFlash)))
        {
            if(IsInvoking(nameof(LeftFlash)) CancelInvoke(nameof(LeftFlash));

            InvokeRepeating(nameof(RightFlash), 0.35f, 0.35f);
        }
    }
    else
    {
        CancelInvoke(nameof(RightFlash));
    }

    if (ControlFreak2.CF2Input.GetAxis ("left") != 0)
    {
        if (!IsInvoking(nameof(LeftFlash)))
        {
            if(IsInvoking(nameof(RightFlash)) CancelInvoke(nameof(RightFlash));

            InvokeRepeating(nameof(LeftFlash), 0.35f, 0.35f);
        }
    }
    else
    {
        CancelInvoke(nameof(LeftFlash));
    }
}

// Btw: These you can implement way shorter this way ;)
void RightFlash()
{
    flash_right.SetActive(!flash_right.activeSelf);
}

void LeftFlash()
{
    flash_left.SetActive(!flash_left.activeSelf);
}

In your case I would actually rather use simple timers since you need the Update method anyway for getting the user input so why overcomplicating:

private float timerLeft;
private float timerRight;

void Update ()
{
    if (ControlFreak2.CF2Input.GetAxis ("right") != 0)
    {
        timerRight -= Time.deltaTime;
        if (timerRight <= 0)
        {
            timerRight = interval;

            RightFlash();
        }
    }
    // simply make them exclusive so only one button is handled at a time
    // if you press both at the same time right overrules
    else if (ControlFreak2.CF2Input.GetAxis ("left") != 0)
    {
        timerLeft -= Time.deltaTime;
        if (timerLeft <= 0)
        {
            timerLeft = interval;

            LeftFlash();
        }
    }
}

void RightFlash()
{
    flash_right.SetActive(!flash_right.activeSelf);
}

void LeftFlash()
{
    flash_left.SetActive(!flash_left.activeSelf);
}


问:
Error "void is an invalid type for the variable passwordMethod1"

Discription: This program check password between 7 to 16

characters which contain only characters, numeric digits and underscore

and first character*/

import java.util.*;

```<code>public class PasswordValidationOne {
 /**my hints on how to solve this problem
 * the length of the string must not less 7 and must not more than 16 character
 **/
public static void main (String[] args) {
      Scanner scan = new Scanner(System.in);
      System.out.println("Enter a password");
      String password = scan.nextLine();

      public  void  passwordMethod1( password) {
            int lengthPassword = password.length(); // getting the length of the string password
            boolean containsDigit = password.matches("*.\\d*.");
            boolean containsUnderscore = password.contains("_");
            char firstCharacter = password.charAt(0);
            if((lengthPassword >= 7&& lengthPassword<=16)&& (containsDigit == true) && (containsUnderscore == true)&& (firstCharacter >= 'A' && firstCharacter <= 'z') )
                System.out.println("Password Accepted! You can proceed");
            else
                System.out.println("Password not accepted! Retry");
      } //end of method passwordMethod1()

}// end of main method
</code>```

}//end of the class

答:
You declare the passwordMethod1 inside the main method, that's not valid. The compiler expects a variable there, hence the error message.

Move it outside.

```<code>public static void main (String[] args) {
      Scanner scan = new Scanner(System.in);
      System.out.println("Enter a password");
      String password = scan.nextLine();

      passwordMethod1( password);

}// end of main method

public  void  passwordMethod1(String password) {
    int lengthPassword = password.length(); // getting the length of the string password
    boolean containsDigit = password.matches("*.\\d*.");
                boolean containsUnderscore = password.contains("_");
    char firstCharacter = password.charAt(0);
    if((lengthPassword >= 7&& lengthPassword<=16)&& (containsDigit == true) && (containsUnderscore == true)&& (firstCharacter >= 'A' && firstCharacter <= 'z') )
        System.out.println("Password Accepted! You can proceed");
    else
        System.out.println("Password not accepted! Retry");
} //end of method passwordMethod1()
</code>```

Body:
Discription: This program check password between 7 to 16

characters which contain only characters, numeric digits and underscore

and first character*/

import java.util.*;

public class PasswordValidationOne {
 /**my hints on how to solve this problem
 * the length of the string must not less 7 and must not more than 16 character
 **/
public static void main (String[] args) {
      Scanner scan = new Scanner(System.in);
      System.out.println("Enter a password");
      String password = scan.nextLine();

      public  void  passwordMethod1( password) {
            int lengthPassword = password.length(); // getting the length of the string password
            boolean containsDigit = password.matches("*.\\d*.");
            boolean containsUnderscore = password.contains("_");
            char firstCharacter = password.charAt(0);
            if((lengthPassword >= 7&& lengthPassword<=16)&& (containsDigit == true) && (containsUnderscore == true)&& (firstCharacter >= 'A' && firstCharacter <= 'z') )
                System.out.println("Password Accepted! You can proceed");
            else
                System.out.println("Password not accepted! Retry");
      } //end of method passwordMethod1()

}// end of main method

}//end of the class

Body:
You declare the passwordMethod1 inside the main method, that's not valid. The compiler expects a variable there, hence the error message.

Move it outside.

public static void main (String[] args) {
      Scanner scan = new Scanner(System.in);
      System.out.println("Enter a password");
      String password = scan.nextLine();

      passwordMethod1( password);

}// end of main method

public  void  passwordMethod1(String password) {
    int lengthPassword = password.length(); // getting the length of the string password
    boolean containsDigit = password.matches("*.\\d*.");
                boolean containsUnderscore = password.contains("_");
    char firstCharacter = password.charAt(0);
    if((lengthPassword >= 7&& lengthPassword<=16)&& (containsDigit == true) && (containsUnderscore == true)&& (firstCharacter >= 'A' && firstCharacter <= 'z') )
        System.out.println("Password Accepted! You can proceed");
    else
        System.out.println("Password not accepted! Retry");
} //end of method passwordMethod1()


问:
panic: unable to bootstrap orderer. Error reading genesis block file: open /etc/hyperledger/fabric/genesisblock: no such file or directory
I am working on hyperledger blockchain. I am running 4 organizations network, I have developed docker-compose.yml file. When is start docker-compose all containers are starting but orderer.example.com container is not starting i.e., the container is exiting with code 2.

Below is the orderer.example.com docker-compose configuration details and logs of the orderer.example.com container.

docker-compose configuration details

```<code>###########################################
# Orderer Docker Container Config
###########################################
  orderer.example.com:
  container_name: orderer.example.com
  image: hyperledger/fabric-orderer
  environment:
    - ORDERER_GENERAL_LOGLEVEL=debug
    - FABRIC_LOGGING_SPEC=info
    - ORDERER_GENERAL_LISTENADDRESS=0.0.0.0
    - ORDERER_GENERAL_GENESISMETHOD=file
    - OERDERER_GENERAL_GENESISFILE=/etc/hyperledger/configtx/genesis.block
    - ORDERER_GENERAL_LOCALMSPID=OrdererMSP
    - ORDERER_GENERAL_LOCALMSPDIR=/etc/hyperledger/msp/orderer/msp

  working_dir: /opt/gopath/src/github.com/hyperledger/fabric/orderer

  command: orderer

  ports:
  - 7050:7050

  volumes:
    - ./channel-artifacts/:/etc/hyperledger/configtx
    - ./crypto-config/ordererOrganizations/example.com/orderers/OrdererPeer.example.com/:/etc/hyperledger/msp/orderer
    - ./crypto-config/peerOrganizations/org1.example.com/peers/peer0.org1.example.com/:/etc/hyperledger/msp/peerOrg1/peer0
    - ./crypto-config/peerOrganizations/org2.example.com/peers/peer0.org2.example.com/:/etc/hyperledger/msp/peerOrg2/peer0
    - ./crypto-config/peerOrganizations/org3.example.com/peers/peer0.org3.example.com/:/etc/hyperledger/msp/peerOrg3/peer0
    - ./crypto-config/peerOrganizations/org4.example.com/peers/peer0.org4.example.com/:/etc/hyperledger/msp/peerOrg4/peer0

  networks:
    - basic
</code>```

Error logs of orderer.example.com container

```<code>2019-10-18 08:08:51.429 UTC [localconfig] completeInitialization -> INFO 001 Kafka.Version unset, setting to 0.10.2.0
2019-10-18 08:08:51.556 UTC [orderer.common.server] prettyPrintStruct -> INFO 002 Orderer config values:
    General.LedgerType = "file"
    General.ListenAddress = "0.0.0.0"
    General.ListenPort = 7050
    General.TLS.Enabled = false
    General.TLS.PrivateKey = "/etc/hyperledger/fabric/tls/server.key"
    General.TLS.Certificate = "/etc/hyperledger/fabric/tls/server.crt"
    General.TLS.RootCAs = [/etc/hyperledger/fabric/tls/ca.crt]
    General.TLS.ClientAuthRequired = false
    General.TLS.ClientRootCAs = []
    General.Cluster.ListenAddress = ""
    General.Cluster.ListenPort = 0
    General.Cluster.ServerCertificate = ""
    General.Cluster.ServerPrivateKey = ""
    General.Cluster.ClientCertificate = ""
    General.Cluster.ClientPrivateKey = ""
    General.Cluster.RootCAs = []
    General.Cluster.DialTimeout = 5s
    General.Cluster.RPCTimeout = 7s
    General.Cluster.ReplicationBufferSize = 20971520
    General.Cluster.ReplicationPullTimeout = 5s
    General.Cluster.ReplicationRetryTimeout = 5s
    General.Cluster.ReplicationBackgroundRefreshInterval = 5m0s
    General.Cluster.ReplicationMaxRetries = 12
    General.Cluster.SendBufferSize = 10
    General.Cluster.CertExpirationWarningThreshold = 168h0m0s
    General.Cluster.TLSHandshakeTimeShift = 0s
    General.Keepalive.ServerMinInterval = 1m0s
    General.Keepalive.ServerInterval = 2h0m0s
    General.Keepalive.ServerTimeout = 20s
    General.ConnectionTimeout = 0s
    General.GenesisMethod = "file"
    General.GenesisProfile = "SampleInsecureSolo"
    General.SystemChannel = "test-system-channel-name"
    General.GenesisFile = "/etc/hyperledger/fabric/genesisblock"
    General.Profile.Enabled = false
    General.Profile.Address = "0.0.0.0:6060"
    General.LocalMSPDir = "/etc/hyperledger/msp/orderer/msp"
    General.LocalMSPID = "OrdererMSP"
    General.BCCSP.ProviderName = "SW"
    General.BCCSP.SwOpts.SecLevel = 256
    General.BCCSP.SwOpts.HashFamily = "SHA2"
    General.BCCSP.SwOpts.Ephemeral = false
    General.BCCSP.SwOpts.FileKeystore.KeyStorePath = "/etc/hyperledger/msp/orderer/msp/keystore"
    General.BCCSP.SwOpts.DummyKeystore =
    General.BCCSP.SwOpts.InmemKeystore =
    General.BCCSP.PluginOpts =
    General.Authentication.TimeWindow = 15m0s
    General.Authentication.NoExpirationChecks = false
    FileLedger.Location = "/var/hyperledger/production/orderer"
    FileLedger.Prefix = "hyperledger-fabric-ordererledger"
    RAMLedger.HistorySize = 1000
    Kafka.Retry.ShortInterval = 5s
    Kafka.Retry.ShortTotal = 10m0s
    Kafka.Retry.LongInterval = 5m0s
    Kafka.Retry.LongTotal = 12h0m0s
    Kafka.Retry.NetworkTimeouts.DialTimeout = 10s
    Kafka.Retry.NetworkTimeouts.ReadTimeout = 10s
    Kafka.Retry.NetworkTimeouts.WriteTimeout = 10s
    Kafka.Retry.Metadata.RetryMax = 3
    Kafka.Retry.Metadata.RetryBackoff = 250ms
    Kafka.Retry.Producer.RetryMax = 3
    Kafka.Retry.Producer.RetryBackoff = 100ms
    Kafka.Retry.Consumer.RetryBackoff = 2s
    Kafka.Verbose = false
    Kafka.Version = 0.10.2.0
    Kafka.TLS.Enabled = false
    Kafka.TLS.PrivateKey = ""
    Kafka.TLS.Certificate = ""
    Kafka.TLS.RootCAs = []
    Kafka.TLS.ClientAuthRequired = false
    Kafka.TLS.ClientRootCAs = []
    Kafka.SASLPlain.Enabled = false
    Kafka.SASLPlain.User = ""
    Kafka.SASLPlain.Password = ""
    Kafka.Topic.ReplicationFactor = 3
    Debug.BroadcastTraceDir = ""
    Debug.DeliverTraceDir = ""
    Consensus = map[WALDir:/var/hyperledger/production/orderer/etcdraft/wal SnapDir:/var/hyperledger/production/orderer/etcdraft/snapshot]
    Operations.ListenAddress = "127.0.0.1:8443"
    Operations.TLS.Enabled = false
    Operations.TLS.PrivateKey = ""
    Operations.TLS.Certificate = ""
    Operations.TLS.RootCAs = []
    Operations.TLS.ClientAuthRequired = false
    Operations.TLS.ClientRootCAs = []
    Metrics.Provider = "disabled"
    Metrics.Statsd.Network = "udp"
    Metrics.Statsd.Address = "127.0.0.1:8125"
    Metrics.Statsd.WriteInterval = 30s
    Metrics.Statsd.Prefix = ""
panic: unable to bootstrap orderer. Error reading genesis block file: open /etc/hyperledger/fabric/genesisblock: no such file or directory

goroutine 1 [running]:
github.com/hyperledger/fabric/orderer/common/bootstrap/file.(*fileBootstrapper).GenesisBlock(0xc0002bb2b0, 0xc0002bb2b0)
    /opt/gopath/src/github.com/hyperledger/fabric/orderer/common/bootstrap/file/bootstrap.go:39 +0x1d0
github.com/hyperledger/fabric/orderer/common/server.extractBootstrapBlock(0xc000444900, 0x0)
    /opt/gopath/src/github.com/hyperledger/fabric/orderer/common/server/main.go:532 +0x1bd
github.com/hyperledger/fabric/orderer/common/server.Start(0x1018e03, 0x5, 0xc000444900)
    /opt/gopath/src/github.com/hyperledger/fabric/orderer/common/server/main.go:96 +0x43
github.com/hyperledger/fabric/orderer/common/server.Main()
    /opt/gopath/src/github.com/hyperledger/fabric/orderer/common/server/main.go:91 +0x1ce
main.main()
    /opt/gopath/src/github.com/hyperledger/fabric/orderer/main.go:15 +0x20
</code>```

When I got this error I made changes to the code follows as below:

```<code>environment:
  - OERDERER_GENERAL_GENESISFILE=/etc/hyperledger/fabric/genesis.block
volumes:
  - ./channel-artifacts/:/etc/hyperledger/fabric
</code>```

But the I got the same error below is the error logs:

```<code>2019-10-18 07:49:44.841 UTC [orderer.common.server] Main -> ERRO 001 failed to parse config:  Error reading configuration: Unsupported Config Type ""
</code>```

Please help me with this issue. please ignore is there are any indentation error

答: Please check the genesis block path. Docker is not able to locate the file</p>

Body:
I am working on hyperledger blockchain. I am running 4 organizations network, I have developed docker-compose.yml file. When is start docker-compose all containers are starting but orderer.example.com container is not starting i.e., the container is exiting with code 2.

Below is the orderer.example.com docker-compose configuration details and logs of the orderer.example.com container.

docker-compose configuration details

###########################################
# Orderer Docker Container Config
###########################################
  orderer.example.com:
  container_name: orderer.example.com
  image: hyperledger/fabric-orderer
  environment:
    - ORDERER_GENERAL_LOGLEVEL=debug
    - FABRIC_LOGGING_SPEC=info
    - ORDERER_GENERAL_LISTENADDRESS=0.0.0.0
    - ORDERER_GENERAL_GENESISMETHOD=file
    - OERDERER_GENERAL_GENESISFILE=/etc/hyperledger/configtx/genesis.block
    - ORDERER_GENERAL_LOCALMSPID=OrdererMSP
    - ORDERER_GENERAL_LOCALMSPDIR=/etc/hyperledger/msp/orderer/msp

  working_dir: /opt/gopath/src/github.com/hyperledger/fabric/orderer

  command: orderer

  ports:
  - 7050:7050

  volumes:
    - ./channel-artifacts/:/etc/hyperledger/configtx
    - ./crypto-config/ordererOrganizations/example.com/orderers/OrdererPeer.example.com/:/etc/hyperledger/msp/orderer
    - ./crypto-config/peerOrganizations/org1.example.com/peers/peer0.org1.example.com/:/etc/hyperledger/msp/peerOrg1/peer0
    - ./crypto-config/peerOrganizations/org2.example.com/peers/peer0.org2.example.com/:/etc/hyperledger/msp/peerOrg2/peer0
    - ./crypto-config/peerOrganizations/org3.example.com/peers/peer0.org3.example.com/:/etc/hyperledger/msp/peerOrg3/peer0
    - ./crypto-config/peerOrganizations/org4.example.com/peers/peer0.org4.example.com/:/etc/hyperledger/msp/peerOrg4/peer0

  networks:
    - basic

Error logs of orderer.example.com container

2019-10-18 08:08:51.429 UTC [localconfig] completeInitialization -> INFO 001 Kafka.Version unset, setting to 0.10.2.0
2019-10-18 08:08:51.556 UTC [orderer.common.server] prettyPrintStruct -> INFO 002 Orderer config values:
    General.LedgerType = "file"
    General.ListenAddress = "0.0.0.0"
    General.ListenPort = 7050
    General.TLS.Enabled = false
    General.TLS.PrivateKey = "/etc/hyperledger/fabric/tls/server.key"
    General.TLS.Certificate = "/etc/hyperledger/fabric/tls/server.crt"
    General.TLS.RootCAs = [/etc/hyperledger/fabric/tls/ca.crt]
    General.TLS.ClientAuthRequired = false
    General.TLS.ClientRootCAs = []
    General.Cluster.ListenAddress = ""
    General.Cluster.ListenPort = 0
    General.Cluster.ServerCertificate = ""
    General.Cluster.ServerPrivateKey = ""
    General.Cluster.ClientCertificate = ""
    General.Cluster.ClientPrivateKey = ""
    General.Cluster.RootCAs = []
    General.Cluster.DialTimeout = 5s
    General.Cluster.RPCTimeout = 7s
    General.Cluster.ReplicationBufferSize = 20971520
    General.Cluster.ReplicationPullTimeout = 5s
    General.Cluster.ReplicationRetryTimeout = 5s
    General.Cluster.ReplicationBackgroundRefreshInterval = 5m0s
    General.Cluster.ReplicationMaxRetries = 12
    General.Cluster.SendBufferSize = 10
    General.Cluster.CertExpirationWarningThreshold = 168h0m0s
    General.Cluster.TLSHandshakeTimeShift = 0s
    General.Keepalive.ServerMinInterval = 1m0s
    General.Keepalive.ServerInterval = 2h0m0s
    General.Keepalive.ServerTimeout = 20s
    General.ConnectionTimeout = 0s
    General.GenesisMethod = "file"
    General.GenesisProfile = "SampleInsecureSolo"
    General.SystemChannel = "test-system-channel-name"
    General.GenesisFile = "/etc/hyperledger/fabric/genesisblock"
    General.Profile.Enabled = false
    General.Profile.Address = "0.0.0.0:6060"
    General.LocalMSPDir = "/etc/hyperledger/msp/orderer/msp"
    General.LocalMSPID = "OrdererMSP"
    General.BCCSP.ProviderName = "SW"
    General.BCCSP.SwOpts.SecLevel = 256
    General.BCCSP.SwOpts.HashFamily = "SHA2"
    General.BCCSP.SwOpts.Ephemeral = false
    General.BCCSP.SwOpts.FileKeystore.KeyStorePath = "/etc/hyperledger/msp/orderer/msp/keystore"
    General.BCCSP.SwOpts.DummyKeystore =
    General.BCCSP.SwOpts.InmemKeystore =
    General.BCCSP.PluginOpts =
    General.Authentication.TimeWindow = 15m0s
    General.Authentication.NoExpirationChecks = false
    FileLedger.Location = "/var/hyperledger/production/orderer"
    FileLedger.Prefix = "hyperledger-fabric-ordererledger"
    RAMLedger.HistorySize = 1000
    Kafka.Retry.ShortInterval = 5s
    Kafka.Retry.ShortTotal = 10m0s
    Kafka.Retry.LongInterval = 5m0s
    Kafka.Retry.LongTotal = 12h0m0s
    Kafka.Retry.NetworkTimeouts.DialTimeout = 10s
    Kafka.Retry.NetworkTimeouts.ReadTimeout = 10s
    Kafka.Retry.NetworkTimeouts.WriteTimeout = 10s
    Kafka.Retry.Metadata.RetryMax = 3
    Kafka.Retry.Metadata.RetryBackoff = 250ms
    Kafka.Retry.Producer.RetryMax = 3
    Kafka.Retry.Producer.RetryBackoff = 100ms
    Kafka.Retry.Consumer.RetryBackoff = 2s
    Kafka.Verbose = false
    Kafka.Version = 0.10.2.0
    Kafka.TLS.Enabled = false
    Kafka.TLS.PrivateKey = ""
    Kafka.TLS.Certificate = ""
    Kafka.TLS.RootCAs = []
    Kafka.TLS.ClientAuthRequired = false
    Kafka.TLS.ClientRootCAs = []
    Kafka.SASLPlain.Enabled = false
    Kafka.SASLPlain.User = ""
    Kafka.SASLPlain.Password = ""
    Kafka.Topic.ReplicationFactor = 3
    Debug.BroadcastTraceDir = ""
    Debug.DeliverTraceDir = ""
    Consensus = map[WALDir:/var/hyperledger/production/orderer/etcdraft/wal SnapDir:/var/hyperledger/production/orderer/etcdraft/snapshot]
    Operations.ListenAddress = "127.0.0.1:8443"
    Operations.TLS.Enabled = false
    Operations.TLS.PrivateKey = ""
    Operations.TLS.Certificate = ""
    Operations.TLS.RootCAs = []
    Operations.TLS.ClientAuthRequired = false
    Operations.TLS.ClientRootCAs = []
    Metrics.Provider = "disabled"
    Metrics.Statsd.Network = "udp"
    Metrics.Statsd.Address = "127.0.0.1:8125"
    Metrics.Statsd.WriteInterval = 30s
    Metrics.Statsd.Prefix = ""
panic: unable to bootstrap orderer. Error reading genesis block file: open /etc/hyperledger/fabric/genesisblock: no such file or directory

goroutine 1 [running]:
github.com/hyperledger/fabric/orderer/common/bootstrap/file.(*fileBootstrapper).GenesisBlock(0xc0002bb2b0, 0xc0002bb2b0)
    /opt/gopath/src/github.com/hyperledger/fabric/orderer/common/bootstrap/file/bootstrap.go:39 +0x1d0
github.com/hyperledger/fabric/orderer/common/server.extractBootstrapBlock(0xc000444900, 0x0)
    /opt/gopath/src/github.com/hyperledger/fabric/orderer/common/server/main.go:532 +0x1bd
github.com/hyperledger/fabric/orderer/common/server.Start(0x1018e03, 0x5, 0xc000444900)
    /opt/gopath/src/github.com/hyperledger/fabric/orderer/common/server/main.go:96 +0x43
github.com/hyperledger/fabric/orderer/common/server.Main()
    /opt/gopath/src/github.com/hyperledger/fabric/orderer/common/server/main.go:91 +0x1ce
main.main()
    /opt/gopath/src/github.com/hyperledger/fabric/orderer/main.go:15 +0x20

When I got this error I made changes to the code follows as below:

environment:
  - OERDERER_GENERAL_GENESISFILE=/etc/hyperledger/fabric/genesis.block
volumes:
  - ./channel-artifacts/:/etc/hyperledger/fabric

But the I got the same error below is the error logs:

2019-10-18 07:49:44.841 UTC [orderer.common.server] Main -> ERRO 001 failed to parse config:  Error reading configuration: Unsupported Config Type ""

Please help me with this issue. please ignore is there are any indentation error


问:
React useReducer: How to combine multiple reducers?
I'm not a Javascript expert so I wondered if anyone has an "elegant" way to combine multiple reducers to create a global state(Like Redux). A function that does not affect performance when a state updating multiple components etc..

Let's say I have a store.js

```<code>import React, { createContext, useReducer } from "react";
import Rootreducer from "./Rootreducer"

export const StoreContext = createContext();

const initialState = {
    ....
};

export const StoreProvider = props => {
  const [state, dispatch] = useReducer(Rootreducer, initialState);

  return (
    <StoreContext.Provider value={[state, dispatch]}>
      {props.children}
    <StoreContext.Provider>
  );
};
</code>```

Rootreducer.js

```<code>import Reducer1 from "./Reducer1"
import Reducer2 from "./Reducer2"
import Reducer3 from "./Reducer3"
import Reducer4 from "./Reducer4"

const rootReducer = combineReducers({
Reducer1,
Reducer2,
Reducer3,
Reducer4
})

export default rootReducer;
</code>```

答:
If you simply want to achieve a combine reducer feature without any third-party library, do it as below.  (REF: Redux source/code)
The working code is here https://codepen.io/rajeshpillai/pen/jOPWYzL?editors=0010

I have two reducers created, one dateReducer and another counterReducer.  I am using it as

const [state, dispatch] = useReducer(combineReducers({
    counter: counterReducer,
    date: dateReducer
  }), initialState);

The combineReducers code

```<code>function combineReducers(reducers) {
  return (state = {}, action) => {
    const newState = {};
    for (let key in reducers) {
      newState[key] = reducers[key](state[key], action);
    }
    return newState;
  }
}
</code>```

Usage: Extract the respective state

```<code>const { counter, date } = state;
</code>```

NOTE:  You can add more redux like features if you wish.

The complete working code (in case codepen is down :))

```<code>const {useReducer, useEffect} = React;

function dateReducer(state, action) {
  switch(action.type) {
    case "set_date":
      return action.payload;
      break;
    default:
      return state;
  }
}

function counterReducer(state, action) {
  console.log('cr:', state);
  switch (action.type) {
    case 'increment': {
      return state + 1;
    }
    case 'decrement': {
      return state - 1;
    }

    default:
      return state;
  }
}

function combineReducers(reducers) {
  return (state = {}, action) => {
    const newState = {};
    for (let key in reducers) {
      newState[key] = reducers[key](state[key], action);
    }
    return newState;
  }
}

const initialState = {
  counter: 0,
  date: new Date
};

function App() {
  const [state, dispatch] = useReducer(combineReducers({
    counter: counterReducer,
    date: dateReducer
  }), initialState);

  console.log("state", state);
  const { counter, date } = state;

  return (
    <div className="app">
      <h3>Counter Reducer</h3>
      <div className="counter">
        <button onClick={() =>
          dispatch({ type: 'increment'})}>+
        </button>

        <h2>{counter.toString()}</h2>
        <button onClick={() =>
             dispatch({ type: 'decrement'})}>-
        </button>
      </div>
      <hr/>
      <h3>Date Reducer</h3>
      {date.toString()}
      <button className="submit"
          type="submit"
          onClick={() =>
             dispatch({ type: 'set_date', payload:new Date })}>
           Set Date
        </button>
    </div>
  );
}

const rootElement = document.querySelector("#root");
ReactDOM.render(<App />, rootElement);
</code>```

NOTE: This is a quick hack (for learning and demonstration purpose only)

Body:
I'm not a Javascript expert so I wondered if anyone has an "elegant" way to combine multiple reducers to create a global state(Like Redux). A function that does not affect performance when a state updating multiple components etc..

Let's say I have a store.js

import React, { createContext, useReducer } from "react";
import Rootreducer from "./Rootreducer"

export const StoreContext = createContext();

const initialState = {
    ....
};

export const StoreProvider = props => {
  const [state, dispatch] = useReducer(Rootreducer, initialState);

  return (
    <StoreContext.Provider value={[state, dispatch]}>
      {props.children}
    <StoreContext.Provider>
  );
};

Rootreducer.js

import Reducer1 from "./Reducer1"
import Reducer2 from "./Reducer2"
import Reducer3 from "./Reducer3"
import Reducer4 from "./Reducer4"

const rootReducer = combineReducers({
Reducer1,
Reducer2,
Reducer3,
Reducer4
})

export default rootReducer;

Body:
If you simply want to achieve a combine reducer feature without any third-party library, do it as below.  (REF: Redux source/code)
The working code is here https://codepen.io/rajeshpillai/pen/jOPWYzL?editors=0010

I have two reducers created, one dateReducer and another counterReducer.  I am using it as

const [state, dispatch] = useReducer(combineReducers({
    counter: counterReducer,
    date: dateReducer
  }), initialState);

The combineReducers code

function combineReducers(reducers) {
  return (state = {}, action) => {
    const newState = {};
    for (let key in reducers) {
      newState[key] = reducers[key](state[key], action);
    }
    return newState;
  }
}

Usage: Extract the respective state

const { counter, date } = state;

NOTE:  You can add more redux like features if you wish.

The complete working code (in case codepen is down :))

const {useReducer, useEffect} = React;

function dateReducer(state, action) {
  switch(action.type) {
    case "set_date":
      return action.payload;
      break;
    default:
      return state;
  }
}

function counterReducer(state, action) {
  console.log('cr:', state);
  switch (action.type) {
    case 'increment': {
      return state + 1;
    }
    case 'decrement': {
      return state - 1;
    }

    default:
      return state;
  }
}

function combineReducers(reducers) {
  return (state = {}, action) => {
    const newState = {};
    for (let key in reducers) {
      newState[key] = reducers[key](state[key], action);
    }
    return newState;
  }
}

const initialState = {
  counter: 0,
  date: new Date
};

function App() {
  const [state, dispatch] = useReducer(combineReducers({
    counter: counterReducer,
    date: dateReducer
  }), initialState);

  console.log("state", state);
  const { counter, date } = state;

  return (
    <div className="app">
      <h3>Counter Reducer</h3>
      <div className="counter">
        <button onClick={() =>
          dispatch({ type: 'increment'})}>+
        </button>

        <h2>{counter.toString()}</h2>
        <button onClick={() =>
             dispatch({ type: 'decrement'})}>-
        </button>
      </div>
      <hr/>
      <h3>Date Reducer</h3>
      {date.toString()}
      <button className="submit"
          type="submit"
          onClick={() =>
             dispatch({ type: 'set_date', payload:new Date })}>
           Set Date
        </button>
    </div>
  );
}

const rootElement = document.querySelector("#root");
ReactDOM.render(<App />, rootElement);

NOTE: This is a quick hack (for learning and demonstration purpose only)


问:
Can I request a certificate for *.user1.example.com from Let's Encrypt if I only own example.com domain
If I only own example.com domain, *.user1 is a CNAME of example.com, but I don't have user1.example.com domain, so there can't satisfy DAN-01 challenge on user1.example.com, the challenge only can be satisfied on example.com. Is it possible that I request a cert for *.user1.example.com for such case? Thanks.</p>

答: If you own domain.com you are free to create user1.domain.com subdomain. And then you can make appropriate changes in DNS to satisfy Lets Encrypt requirements. </p>


问:
How to get a CNContact phone number(s) as string in Swift?
I am attempting to retrieve the names and phone number(s) of all contacts and put them into arrays with Swift in iOS. I have made it this far:

func findContacts() -> [CNContact] {

    marrContactsNumber.removeAllObjects()
    marrContactsName.removeAllObjects()

    let store = CNContactStore()

    let keysToFetch = [CNContactGivenNameKey, CNContactFamilyNameKey, CNContactPhoneNumbersKey]

    let fetchRequest = CNContactFetchRequest(keysToFetch: keysToFetch)

    var contacts = [CNContact]()

    do {
        try store.enumerateContactsWithFetchRequest(fetchRequest, usingBlock: { (let contact, let stop) -> Void in
            contacts.append(contact)

            self.marrContactsName.addObject(contact.givenName + " " + contact.familyName)

            self.marrContactsNumber.addObject(contact.phoneNumbers)

            print(contact.phoneNumbers)
    }
    catch let error as NSError {
        print(error.localizedDescription)
    }

    print(marrContactsName.count)
    print(marrContactsNumber.count)

    return contacts
}
```

<p>Once completed, <code>marrContactsName</code> contains an array of all my contacts' names exactly as expected. i.e. "John Doe". However, <code>marrContactsNumber</code> returns an array of values like </p>

<pre class="lang-none prettyprint-override"><code>[<CNLabeledValue: 0x158a19950: identifier=F831DC7E-5896-420F-AE46-489F6C14DA6E,
label=_$!<Work>!$_, value=<CNPhoneNumber: 0x158a19640: countryCode=us, digits=6751420000>>,
<CNLabeledValue: 0x158a19a80: identifier=ECD66568-C6DD-441D-9448-BDEDDE9A68E1,
label=_$!<Work>!$_, value=<CNPhoneNumber: 0x158a199b0: countryCode=us, digits=5342766455>>]
</code>```

I would like to know how to retrieve JUST the phone number(s) as a string value(s) i.e. "XXXXXXXXXX". Basically, how to call for the digit(s) value. Thanks!

答:
for Swift 5+

```<code>func removeSpecialCharactersFromContactNumberOfUser(_ contactNo : String) -> String? {

    let digits = CharacterSet(charactersIn: "0123456789").inverted
    let modifiedContactNo = contactNo.components(separatedBy: digits).joined(separator: "")

    if modifiedContactNo.count > 9 {

        return modifiedContactNo

    } else {

        return nil
    }
}

var number = phone.value.stringValue
number = number.starts(with: "+91") ? number.replacingOccurrences(of: "+91", with: "") : number

if let formattedNumber = removeSpecialCharactersFromContactNumberOfUser(number)  {
    //use this formattedNumber
}
</code>```

This is to remove +91 from your phone number and it's working fine.

Body:
I am attempting to retrieve the names and phone number(s) of all contacts and put them into arrays with Swift in iOS. I have made it this far:

func findContacts() -> [CNContact] {

    marrContactsNumber.removeAllObjects()
    marrContactsName.removeAllObjects()

    let store = CNContactStore()

    let keysToFetch = [CNContactGivenNameKey, CNContactFamilyNameKey, CNContactPhoneNumbersKey]

    let fetchRequest = CNContactFetchRequest(keysToFetch: keysToFetch)

    var contacts = [CNContact]()

    do {
        try store.enumerateContactsWithFetchRequest(fetchRequest, usingBlock: { (let contact, let stop) -> Void in
            contacts.append(contact)

            self.marrContactsName.addObject(contact.givenName + " " + contact.familyName)

            self.marrContactsNumber.addObject(contact.phoneNumbers)

            print(contact.phoneNumbers)
    }
    catch let error as NSError {
        print(error.localizedDescription)
    }

    print(marrContactsName.count)
    print(marrContactsNumber.count)

    return contacts
}

Once completed, marrContactsName contains an array of all my contacts' names exactly as expected. i.e. "John Doe". However, marrContactsNumber returns an array of values like

[<CNLabeledValue: 0x158a19950: identifier=F831DC7E-5896-420F-AE46-489F6C14DA6E,
label=_$!<Work>!$_, value=<CNPhoneNumber: 0x158a19640: countryCode=us, digits=6751420000>>,
<CNLabeledValue: 0x158a19a80: identifier=ECD66568-C6DD-441D-9448-BDEDDE9A68E1,
label=_$!<Work>!$_, value=<CNPhoneNumber: 0x158a199b0: countryCode=us, digits=5342766455>>]

I would like to know how to retrieve JUST the phone number(s) as a string value(s) i.e. "XXXXXXXXXX". Basically, how to call for the digit(s) value. Thanks!

Body:
for Swift 5+

func removeSpecialCharactersFromContactNumberOfUser(_ contactNo : String) -> String? {

    let digits = CharacterSet(charactersIn: "0123456789").inverted
    let modifiedContactNo = contactNo.components(separatedBy: digits).joined(separator: "")

    if modifiedContactNo.count > 9 {

        return modifiedContactNo

    } else {

        return nil
    }
}

var number = phone.value.stringValue
number = number.starts(with: "+91") ? number.replacingOccurrences(of: "+91", with: "") : number

if let formattedNumber = removeSpecialCharactersFromContactNumberOfUser(number)  {
    //use this formattedNumber
}

This is to remove +91 from your phone number and it's working fine.


问:
Which is best free distributable code to html converter
In my application, I have a requirement to convert Java/VB/VB.net/etc program to HTML, and then use that HTML page (to insert in Word doc).

Sure we can write code for this, but this will entail programming for this too, and from more than one programming languages, and dealing with bugs. Whereas it needs to be released ASAP. Using 3rd party tool for this HTML generation is not an issue.

However this 3rd party tool, code to html formatter, should be free, robust, and should convert upto Java 1.5, and other language's recent version.

Do you know of any such converter (code to html converter/formatter) which is free, distributable, robust, and converts upto recent versions of more than one languages (including Java)?

To elaborate further, I am interested in a utility which will take source code file as input, and will generate HTML file as output. The HTML file should not use javascript to color the code, because then inserting in Word the coloring will be lost.

答: Javadoc will convert your code to HTML (along with the associated class trees and linkages, etc), but doesn't syntax highlight the code unfortunately. What you could do is add the Google Code Prettifier to each page, which could work.</p>

OwnerDisplayName: vikramsjn

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: vikramsjn

OwnerDisplayName: nickf

LastEditorDisplayName: nickf


问:
CSV Downloaded To Chrome - Error: MIME Type text/csv
I am using jQuery to recognise a click on a button which then fires a call to a file:

```<code>window.location.href = "url";
</code>```

This file queries the database, returns results then writes it to a CSV file. I have the following headers set:

```<code>header('Content-Type: text/csv;');
header('Content-Disposition: attachment; filename=data.csv');
</code>```

This works on all browsers except Chrome which returns the following error in the console log "Resource interpreted as Document but transferred with MIME type text/csv: "url"".

The weird thing is that if I call the file directly it works in all browsers.

Code:

```<code>                $fp = fopen('php://output', 'w');

                header('Content-Type: text/csv;');
                header('Content-Disposition: attachment; filename=data.csv');
                header("Expires: 0");
                header("Cache-control: private");

                //Field Headers
                $ncols = oci_num_fields($stid);
                $headers_row = array();
                for ($i = 1; $i <= $ncols; ++$i) {

                    $headers_row[] = oci_field_name($stid, $i);

                }

                while ($row = oci_fetch_array($stid, OCI_NUM+OCI_RETURN_NULLS)) {

                    if(!empty($row)){
                        if(!empty($headers_row)){
                            fputcsv($fp, $headers_row);
                            $headers_row = '';
                        }

                        fputcsv($fp, $row);
                    }

                }

                fclose($fp);
                oci_close($conn);
</code>```

Anyone got any ideas?

答:
Try Application Content Type

header("content-type: application/octet-stream");

Also User Public access so user can download

header("Pragma: public");

Body:
I am using jQuery to recognise a click on a button which then fires a call to a file:

window.location.href = "url";

This file queries the database, returns results then writes it to a CSV file. I have the following headers set:

header('Content-Type: text/csv;');
header('Content-Disposition: attachment; filename=data.csv');

This works on all browsers except Chrome which returns the following error in the console log "Resource interpreted as Document but transferred with MIME type text/csv: "url"".

The weird thing is that if I call the file directly it works in all browsers.

Code:

                $fp = fopen('php://output', 'w');

                header('Content-Type: text/csv;');
                header('Content-Disposition: attachment; filename=data.csv');
                header("Expires: 0");
                header("Cache-control: private");

                //Field Headers
                $ncols = oci_num_fields($stid);
                $headers_row = array();
                for ($i = 1; $i <= $ncols; ++$i) {

                    $headers_row[] = oci_field_name($stid, $i);

                }

                while ($row = oci_fetch_array($stid, OCI_NUM+OCI_RETURN_NULLS)) {

                    if(!empty($row)){
                        if(!empty($headers_row)){
                            fputcsv($fp, $headers_row);
                            $headers_row = '';
                        }

                        fputcsv($fp, $row);
                    }

                }

                fclose($fp);
                oci_close($conn);

Anyone got any ideas?