问:
Ionic 2 Events Not Passing Data To Different Page
I'm using Ionic 2 or 3 events in order to pass data from my login page to one of my Providers that's shared between my pages. After the user logs in, I want to send the token to my provider file and lock up all the routes. Essentially I want to write code such as:

if (token) {allow access to routes} else {no access}

```<code>  doLogin() {
    // this.navCtrl.setRoot('MenuPage')
    let headers = new Headers();
    headers.append('Content-Type', 'application/json');

    this.http.post(this.apiUrl + 'login', JSON.stringify(this.user), {headers:headers})
      .map(res => res.json())
      .subscribe(data => {
        this.events.publish('token:added', data.token)

        if(data.login === 'yes') {
          this.token = data.token;
          this.navCtrl.setRoot('MenuPage')
        }
        else {
          alert('Bad login cridentials');
        }
      })
  }
</code>```

Provider

```<code>  ionViewDidLoad() {
    console.log("are we here?")
    this.events.subscribe('token:added', (data) => {
      console.log('>>>>>>>>>>>>>>>>> token added is ', data)
    })
  }
</code>```

The interesting thing is, my provider is technically not ever loaded to the screen, so I'm not sure if I should be using ionViewDidLoad. But, just to test if ionViewDidLoad is the problem, I imported the function above in my menu page, but I am still not accessing the token: added data. I can see my "are we here?" string logged, but that's it.

I am getting the token back, users are logging in. I just want to authenticate the users using token that my server is sending to the front end.

Are there any other way to pass data from my login function to my providers w/o using the push method since my provider isn't going to be landed to the screen?

答: Provider will not have ionViewDidLoad event. So the subscription to the event should be done in ngOnInit() callback function in provider class, rest of the code looks good. Also make sure that provider is initialized before login event is publishing. In your Menupage the event data is not logged because you are publishing the event before the MenuPage is being loaded. That's why the log added inside the event subscription is not executed.</p>

ContentLicense: CC BY-SA 4.0

Body:
I'm using Ionic 2 or 3 events in order to pass data from my login page to one of my Providers that's shared between my pages. After the user logs in, I want to send the token to my provider file and lock up all the routes. Essentially I want to write code such as:

if (token) {allow access to routes} else {no access}

  doLogin() {
    // this.navCtrl.setRoot('MenuPage')
    let headers = new Headers();
    headers.append('Content-Type', 'application/json');

    this.http.post(this.apiUrl + 'login', JSON.stringify(this.user), {headers:headers})
      .map(res => res.json())
      .subscribe(data => {
        this.events.publish('token:added', data.token)

        if(data.login === 'yes') {
          this.token = data.token;
          this.navCtrl.setRoot('MenuPage')
        }
        else {
          alert('Bad login cridentials');
        }
      })
  }

Provider

  ionViewDidLoad() {
    console.log("are we here?")
    this.events.subscribe('token:added', (data) => {
      console.log('>>>>>>>>>>>>>>>>> token added is ', data)
    })
  }

The interesting thing is, my provider is technically not ever loaded to the screen, so I'm not sure if I should be using ionViewDidLoad. But, just to test if ionViewDidLoad is the problem, I imported the function above in my menu page, but I am still not accessing the token: added data. I can see my "are we here?" string logged, but that's it.

I am getting the token back, users are logging in. I just want to authenticate the users using token that my server is sending to the front end.

Are there any other way to pass data from my login function to my providers w/o using the push method since my provider isn't going to be landed to the screen?


来源: stackexchange

问:
Python script that rectify's a given word in an .rtf file
I'm new to python currently studying on it. I have a syntax like this:

```<code>def main():
#with auto \1 & \2 on replacement
search_replace_mixed = {'eousisienl':'consistent'}
#no auto variable on replacement
search_replace_exact = {'eousisienl':'consistent'}
</code>```

which would rectify a misspelled word and i do not know what's next. My source document is .RTF and I wanted a python script that rectifies a word from the above syntax. Or if you have better ways to do it. Can you help me?

答:
There are a couple ways you can go about this. If you are just trying to switch a set of misspelled words you know are going to be misspelled you could hack together something like this:

```<code>filename = 'words.rtf'

search_replace_exact = {'eousisienl': 'consistent'}

with open(filename, 'r+') as file:

    text = file.read().split(' ')

    for index, word in enumerate(text):
        if word in search_replace_exact:
            text[index] = search_replace_exact[word]

    corrected_text = ''

    for element in text:
        corrected_text += element + ' '

    file.seek(0)
    file.truncate()
    file.write(corrected_text)
</code>```

This will search through your RTF document and replace anything specifically outlined in your serach_replace_exact dictionary.

ContentLicense: CC BY-SA 3.0

Body:
I'm new to python currently studying on it. I have a syntax like this:

def main():
#with auto \1 & \2 on replacement
search_replace_mixed = {'eousisienl':'consistent'}
#no auto variable on replacement
search_replace_exact = {'eousisienl':'consistent'}

which would rectify a misspelled word and i do not know what's next. My source document is .RTF and I wanted a python script that rectifies a word from the above syntax. Or if you have better ways to do it. Can you help me?

Body:
There are a couple ways you can go about this. If you are just trying to switch a set of misspelled words you know are going to be misspelled you could hack together something like this:

filename = 'words.rtf'

search_replace_exact = {'eousisienl': 'consistent'}

with open(filename, 'r+') as file:

    text = file.read().split(' ')

    for index, word in enumerate(text):
        if word in search_replace_exact:
            text[index] = search_replace_exact[word]

    corrected_text = ''

    for element in text:
        corrected_text += element + ' '

    file.seek(0)
    file.truncate()
    file.write(corrected_text)

This will search through your RTF document and replace anything specifically outlined in your serach_replace_exact dictionary.


问:
How can I construct an enum.Enum from a dictionary of values?
I'd like to generate some types at runtime from a config file. For simplity, let's assume I already have the data loaded as a python dictionary:

```<code>color_values = dict(RED = 1, YELLOW = 2, GREEN = 3)
</code>```

How can I transform this into the type (using enum)

```<code>class Color(enum.Enum):
    RED = 1
    YELLOW = 2
    GREEN = 3
</code>```

The following doesn't work

```<code>def make_enum(name, values):
    return type(name, (enum.Enum,), values)
</code>```

```<code>>>> Color = make_enum('Color', color_values)
AttributeError: 'dict' object has no attribute '_member_names'
</code>```

答:
And another one that chooses to hit the metaclass internals instead:

```<code>def make_enum(name, values):
    meta = type(enum.Enum)
    bases = (enum.Enum,)
    dict = meta.__prepare__(name, bases)
    for k, v in values.items():
        dict[k] = v
    return meta(name, bases, dict)
</code>```

Or with less __dunder__:

```<code>import types
def make_enum(name, values):
    def _update(d1, d2):
        for k, v in d2.items():
            d1[k] = v  # calls __setitem__
    return types.new_class(name, (enum.Enum,), None, lambda ns: _update(ns,values))
</code>```

Body:
I'd like to generate some types at runtime from a config file. For simplity, let's assume I already have the data loaded as a python dictionary:

color_values = dict(RED = 1, YELLOW = 2, GREEN = 3)

How can I transform this into the type (using enum)

class Color(enum.Enum):
    RED = 1
    YELLOW = 2
    GREEN = 3

The following doesn't work

def make_enum(name, values):
    return type(name, (enum.Enum,), values)

>>> Color = make_enum('Color', color_values)
AttributeError: 'dict' object has no attribute '_member_names'

Body:
And another one that chooses to hit the metaclass internals instead:

def make_enum(name, values):
    meta = type(enum.Enum)
    bases = (enum.Enum,)
    dict = meta.__prepare__(name, bases)
    for k, v in values.items():
        dict[k] = v
    return meta(name, bases, dict)

Or with less __dunder__:

import types
def make_enum(name, values):
    def _update(d1, d2):
        for k, v in d2.items():
            d1[k] = v  # calls __setitem__
    return types.new_class(name, (enum.Enum,), None, lambda ns: _update(ns,values))


问:
How to modify AndroidManifest.xml in a Meteor 1.5 Cordova App?
I try to register my App into the sharing feature of android and I found that I have to modify the manifest.

I did:

```<code>App.appendToConfig(`
 <universal-links>
   <host name="com.toto.app" />
 </universal-links>
 <platform name="android">
   <config-file target="AndroidManifest.xml" parent="/manifest/application/activity">
           <intent-filter>
               <action android:name="android.intent.action.SEND" />
               <category android:name="android.intent.category.DEFAULT" />
               <data android:mimeType="*/*" />
           </intent-filter>
   </config-file>
 </platform>
`);
</code>```

The new lines appear in the config.xml but the intent-filter does not appear in the manifest and the app is not generated.

here is the error message

```<code>=> Started your app.

=> App running at: http://localhost:3000/
   Type Control-C twice to stop.

=> Errors executing Cordova commands:

   While running Cordova app for platform Android with options --device:
   Error: Command failed: C:\dev\https://youtu.be/toto\.meteor\local\cordova-build\platforms\android\cordova\run --device --device
   Note: Some input files use or override a deprecated API.
   Note: Recompile with -Xlint:deprecation for details.
   Note: Some input files use or override a deprecated API.
   Note: Recompile with -Xlint:deprecation for details.
   C:\dev\toto\.meteor\local\cordova-build\platforms\android\res\xml\config.xml:60: AAPT: Error parsing XML: unbound prefix

   C:\dev\toto\.meteor\local\cordova-build\platforms\android\build\intermediates\res\merged\debug\xml\config.xml:60: error: Error parsing XML: unbound prefix
</code>```

答:
You need the attribute xmlns:android="http://schemas.android.com/apk/res/android" on every element that references the android namespace. In your case, that means:

```<code>App.appendToConfig(`
 <universal-links>
   <host name="com.toto.app" />
 </universal-links>
 <platform name="android">
   <config-file target="AndroidManifest.xml" parent="/manifest/application/activity">
           <intent-filter>
               <action android:name="android.intent.action.SEND" xmlns:android="http://schemas.android.com/apk/res/android" />
               <category android:name="android.intent.category.DEFAULT" xmlns:android="http://schemas.android.com/apk/res/android" />
               <data android:mimeType="*/*" xmlns:android="http://schemas.android.com/apk/res/android" />
           </intent-filter>
   </config-file>
 </platform>
`);
</code>```

Body:
I try to register my App into the sharing feature of android and I found that I have to modify the manifest.

I did:

App.appendToConfig(`
 <universal-links>
   <host name="com.toto.app" />
 </universal-links>
 <platform name="android">
   <config-file target="AndroidManifest.xml" parent="/manifest/application/activity">
           <intent-filter>
               <action android:name="android.intent.action.SEND" />
               <category android:name="android.intent.category.DEFAULT" />
               <data android:mimeType="*/*" />
           </intent-filter>
   </config-file>
 </platform>
`);

The new lines appear in the config.xml but the intent-filter does not appear in the manifest and the app is not generated.

here is the error message

=> Started your app.

=> App running at: http://localhost:3000/
   Type Control-C twice to stop.

=> Errors executing Cordova commands:

   While running Cordova app for platform Android with options --device:
   Error: Command failed: C:\dev\https://youtu.be/toto\.meteor\local\cordova-build\platforms\android\cordova\run --device --device
   Note: Some input files use or override a deprecated API.
   Note: Recompile with -Xlint:deprecation for details.
   Note: Some input files use or override a deprecated API.
   Note: Recompile with -Xlint:deprecation for details.
   C:\dev\toto\.meteor\local\cordova-build\platforms\android\res\xml\config.xml:60: AAPT: Error parsing XML: unbound prefix

   C:\dev\toto\.meteor\local\cordova-build\platforms\android\build\intermediates\res\merged\debug\xml\config.xml:60: error: Error parsing XML: unbound prefix

Body:
You need the attribute xmlns:android="http://schemas.android.com/apk/res/android" on every element that references the android namespace. In your case, that means:

App.appendToConfig(`
 <universal-links>
   <host name="com.toto.app" />
 </universal-links>
 <platform name="android">
   <config-file target="AndroidManifest.xml" parent="/manifest/application/activity">
           <intent-filter>
               <action android:name="android.intent.action.SEND" xmlns:android="http://schemas.android.com/apk/res/android" />
               <category android:name="android.intent.category.DEFAULT" xmlns:android="http://schemas.android.com/apk/res/android" />
               <data android:mimeType="*/*" xmlns:android="http://schemas.android.com/apk/res/android" />
           </intent-filter>
   </config-file>
 </platform>
`);


问:
File Input control get Images path bind in array and show them in ngfor loop?
I was trying a approach to get multiple files from file input control and iterate those files get their path and store them in array and in html i wanted to show all multiple files here is my code.

```<code>pictureschanged(input: any) {
    const fileList = input.target.files;
    this.testimage = this.sanitization.bypassSecurityTrustResourceUrl(input.target.value) ;
    console.log(this.testimage);
    if (fileList != undefined) {
      this.imageColllection = fileList;
      this.imageCount = fileList.length;
      let arr = [];
      for (let i = 0; i < this.imageColllection.length; i++) {
        let file = this.imageColllection[i];
        var reader = new FileReader();
        reader.onload =  this.uploadImage.bind(this);
        // (e): void => {
        //   arr.push(e.target['result']);
        //   reader.readAsDataURL(file);
        // }
      }
      console.log(this.imageColllection);
      // reader.readAsDataURL(input.files[0]);
      // var path = (window.URL).createObjectURL(fileList[key]);
      // console.log(path);
    }
  }
</code>```

My html code

```<code><div class="form-group">
          <label for="" class="control-label col-sm-3">
            Upload picture:
          </label>
          <div class="col-sm-9">
            <div class="row">
              <div class="col-sm-2" *ngFor="let file of imageColllection">
                <div class="picture-holder">
                  <img [src]="testimage" alt="" class="image-prop">
                </div>
              </div>
              <div class="col-xs-12" [ngClass]="{'col-xs-12':imageCount===0,'col-xs-10':imageCount===1,'col-xs-8':imageCount===2,'col-xs-8':imageCount===3}">
                <div class="dropZoneOverlay" (change)="pictureschanged($event)" #imageTemp>
                  <i class="glyphicon glyphicon-plus">
                  </i>
                  <input type="file" multiple accept="image/*" class="control-custom FileUpload">
                  <!-- <div *ngIf="Pictures.touched && Pictures.invalid">
                  Please provide only 3 pictures
                </div> -->
                </div>
              </div>
            </div>
          </div>
        </div>
</code>```

here as you see I m able to get files in picturechanged() method but not able to get their path and if i get path angular wont load it localy because angular prevents local resources not allowed,how can i achieve that functionality.The following task need to do

1)get the paths of files .

2)bind those path to image src property .

答:
Here it is, how you can achieve it :

Component :

```<code>urls = [];
onSelectFile(event) {
    if (event.target.files && event.target.files[0]) {
        var filesAmount = event.target.files.length;
        for (let i = 0; i < filesAmount; i++) {
                var reader = new FileReader();

                reader.onload = (event) => {
                  console.log(event.target.result);
                   this.urls.push(event.target.result);
                }

                reader.readAsDataURL(event.target.files[i]);
        }
    }
}
</code>```

Template :

```<code><img *ngFor='let url of urls'  [src]="url" height="200"> <br/>

<input type='file' (change)="onSelectFile($event)" multiple>
</code>```

Here is the link to working demo :

https://stackblitz.com/edit/angular-multi-file-upload-preview

Body:
I was trying a approach to get multiple files from file input control and iterate those files get their path and store them in array and in html i wanted to show all multiple files here is my code.

pictureschanged(input: any) {
    const fileList = input.target.files;
    this.testimage = this.sanitization.bypassSecurityTrustResourceUrl(input.target.value) ;
    console.log(this.testimage);
    if (fileList != undefined) {
      this.imageColllection = fileList;
      this.imageCount = fileList.length;
      let arr = [];
      for (let i = 0; i < this.imageColllection.length; i++) {
        let file = this.imageColllection[i];
        var reader = new FileReader();
        reader.onload =  this.uploadImage.bind(this);
        // (e): void => {
        //   arr.push(e.target['result']);
        //   reader.readAsDataURL(file);
        // }
      }
      console.log(this.imageColllection);
      // reader.readAsDataURL(input.files[0]);
      // var path = (window.URL).createObjectURL(fileList[key]);
      // console.log(path);
    }
  }

My html code

            Upload picture:

                  <input type="file" multiple accept="image/*" class="control-custom FileUpload">

here as you see I m able to get files in picturechanged() method but not able to get their path and if i get path angular wont load it localy because angular prevents local resources not allowed,how can i achieve that functionality.The following task need to do

1)get the paths of files .

2)bind those path to image src property .

Body:
Here it is, how you can achieve it :

Component :

urls = [];
onSelectFile(event) {
    if (event.target.files && event.target.files[0]) {
        var filesAmount = event.target.files.length;
        for (let i = 0; i < filesAmount; i++) {
                var reader = new FileReader();

                reader.onload = (event) => {
                  console.log(event.target.result);
                   this.urls.push(event.target.result);
                }

                reader.readAsDataURL(event.target.files[i]);
        }
    }
}

Template :

<img *ngFor='let url of urls'  [src]="url" height="200"> <br/>

<input type='file' (change)="onSelectFile($event)" multiple>

Here is the link to working demo :

https://stackblitz.com/edit/angular-multi-file-upload-preview


问:
Multiple query Joins in windows form application C# with MS Access not working
I have three tables in MS Access database

users,
  rooms,
  room_history

room_history contains both users,rooms id. when I try to join users with room_history data successfully retrieve same goes with rooms and room_history.
Here is my query for joining all three tables.

```<code>"SELECT users.*,rooms.room_id,rooms.room_name,rooms.type,room_history.start_date,room_history.end_date FROM users " +
                "LEFT JOIN room_history ON room_history.user_id= users.user_id " +
                "LEFT JOIN rooms ON room_history.room_id = rooms.room_id";
</code>```

Using above query following error occurs.

syntax error (missing operator) in query expression 'room_history.user_id = users.user_id LEFT JOIN rooms on room_history.room_id = rooms.room_i'

I check/change my database tables name, compact the database.

答:
Try with table alias's instead - the problem appears to be Type is a reserved SQL keyword:

```<code>SELECT U.*,R.room_id,R.room_name,R.[type],RH.start_date,RH.end_date FROM users U
LEFT JOIN room_history RH ON RH.user_id= U.user_id
LEFT JOIN room R ON RH.room_id = R.room_id
</code>```

Body:
I have three tables in MS Access database

users,
  rooms,
  room_history

room_history contains both users,rooms id. when I try to join users with room_history data successfully retrieve same goes with rooms and room_history.
Here is my query for joining all three tables.

"SELECT users.*,rooms.room_id,rooms.room_name,rooms.type,room_history.start_date,room_history.end_date FROM users " +
                "LEFT JOIN room_history ON room_history.user_id= users.user_id " +
                "LEFT JOIN rooms ON room_history.room_id = rooms.room_id";

Using above query following error occurs.

syntax error (missing operator) in query expression 'room_history.user_id = users.user_id LEFT JOIN rooms on room_history.room_id = rooms.room_i'

I check/change my database tables name, compact the database.

Body:
Try with table alias's instead - the problem appears to be Type is a reserved SQL keyword:

SELECT U.*,R.room_id,R.room_name,R.[type],RH.start_date,RH.end_date FROM users U
LEFT JOIN room_history RH ON RH.user_id= U.user_id
LEFT JOIN room R ON RH.room_id = R.room_id


问:
Promise resolves before forEach loop completes
I'm building my first CRUD (library) application and recently learned about promises as a means to avoid deeply-nested callbacks. I'm attempting to seed my DB with some data each time the server starts, but I seem to be missing something conceptually.

I have four objects in a bookData array that I want to iterate over and save to the DB using Mongoose:

function seedBooks() {
    return new Promise(function(resolve,reject){
        bookData.forEach(function(seed){
            Book.create(seed, function(err, newBook){
                if(err) {
                    reject(err);
                }
            });
        });
        resolve();
    });
}```
</div>
</div>
</p>

<p>This function is one of a few that I am attempting to chain together, which is why I'm using promises. But I'm finding that <code>seedBooks()</code> resolves with anywhere between 1 and 4 of the sample books created,  </p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>function seedDB() {
    removeAllBooks()
    .then(function(){
        return removeAllUsers();
    })
    .then(function(){
        return seedUsers();
    })
    .then(function(){
        return seedBooks();
    })
    .then(function(){
        return seedBookInstances();
    });
}</code>```

Am I understanding or using promises & resolve incorrectly? Any help is appreciated. Thanks!

答:
If you are using Mongoose, you can just do this:</p>

```<code>const saveBooks = function(books) {
    return books.map(function(seed) {
            return Book.create(seed);  // returns a promise
        });
    });
}

return Promise.all(saveBooks(books)).then(function(){
    // all books are saved
});
</code>```

Body:
I'm building my first CRUD (library) application and recently learned about promises as a means to avoid deeply-nested callbacks. I'm attempting to seed my DB with some data each time the server starts, but I seem to be missing something conceptually.

I have four objects in a bookData array that I want to iterate over and save to the DB using Mongoose:

function seedBooks() {
    return new Promise(function(resolve,reject){
        bookData.forEach(function(seed){
            Book.create(seed, function(err, newBook){
                if(err) {
                    reject(err);
                }
            });
        });
        resolve();
    });
}

This function is one of a few that I am attempting to chain together, which is why I'm using promises. But I'm finding that seedBooks() resolves with anywhere between 1 and 4 of the sample books created,

function seedDB() {
    removeAllBooks()
    .then(function(){
        return removeAllUsers();
    })
    .then(function(){
        return seedUsers();
    })
    .then(function(){
        return seedBooks();
    })
    .then(function(){
        return seedBookInstances();
    });
}

Am I understanding or using promises & resolve incorrectly? Any help is appreciated. Thanks!

Body:
If you are using Mongoose, you can just do this:

const saveBooks = function(books) {
    return books.map(function(seed) {
            return Book.create(seed);  // returns a promise
        });
    });
}

return Promise.all(saveBooks(books)).then(function(){
    // all books are saved
});


问:
Sync multiple client databases to a master SQL server database
We have many sites (above 70, will grow going forward) which will need to work offline sometime (no internet, no network). So we need to install some sort of local lightweight databases to these computers for them to easily work offline. These databases will only have the tables that they need. They need to read and write the data to these databases daily offline.

We also have a master SQL Server 2008 database that needs to sync the data with the above client databases daily when they are back to network.

So the process would be something like: (table1 and table2 in client and master DB are the same structure)

• Client DB: export table1 to a file1 in the folder named "Client" from the shared network drive; then delete all of data from table1 and table2; then import data to table2 from a file2 in the folder named "Server" from the shared network drive.

• Master DB: export table2 data to a file2 in the folder named "Server" from the shared network drive; import table1 data from file1 which is in folder "Client" of the network drive.

So my questions are:

What kind of a lightweight database we should install for the client machines? SQL Server Express/CE/Lite or something else? So that we can sync the client database and master database easily.

How should we sync the client and master databases data daily automatically?  In other words, how can we implement the process above?

Thanks in advance.

答:
you can use navicat or DBSync tool. Then setup windows scheduler via navicat /DBSync.

It will sync database after a certain time interval. If no internet , sync will not work, but when internet come sync will complete


问:
django function based api not recognized in url.py - NameError
I am trying to implement function based view for rest api on Django. It produces this error, how can I solve this.

```<code>url(r'^api/get_employee', get_employee, name='get_employee'),
NameError: name 'get_employee' is not defined
</code>```

Below are some of my code excerps relating to this problem

https://gitlab.com/firdausmah/railercom/blob/master/railercom/urls.py

```<code>from railercomapp import views

urlpatterns = [
    url(r'^doc/', SwaggerSchemaView.as_view()),
    url(r'^api/get_employee', get_employee, name='get_employee'),
</code>```

https://gitlab.com/firdausmah/railercom/blob/master/railercomapp/views.py

```<code>@api_view(['GET'])
def get_employee(request):
    return Response(Employee.objects.all().values(), status=status.HTTP_200_OK)
</code>```

答:
As I can see from your views function that the function is correct but the import is wrong in urls.py
Either your import statement should be

```<code>from railercomapp.views import get_employee
</code>```

or while defining URLs you should give

```<code>url(r'^api/get_employee', views.get_employee, name='get_employee'),
</code>```

P.S After writing the whole answer, I saw @slackmart already solved it in comments. So full credit to him.

Body:
I am trying to implement function based view for rest api on Django. It produces this error, how can I solve this.

url(r'^api/get_employee', get_employee, name='get_employee'),
NameError: name 'get_employee' is not defined

Below are some of my code excerps relating to this problem

https://gitlab.com/firdausmah/railercom/blob/master/railercom/urls.py

from railercomapp import views

urlpatterns = [
    url(r'^doc/', SwaggerSchemaView.as_view()),
    url(r'^api/get_employee', get_employee, name='get_employee'),

https://gitlab.com/firdausmah/railercom/blob/master/railercomapp/views.py

@api_view(['GET'])
def get_employee(request):
    return Response(Employee.objects.all().values(), status=status.HTTP_200_OK)

Body:
As I can see from your views function that the function is correct but the import is wrong in urls.py
Either your import statement should be

from railercomapp.views import get_employee

or while defining URLs you should give

url(r'^api/get_employee', views.get_employee, name='get_employee'),

P.S After writing the whole answer, I saw @slackmart already solved it in comments. So full credit to him.


问:
How can I count data groups sequential order in the same column in SQL Server 2014?
I need to find frequency of sequences of data rows.I have like 17000 rows data which is including almost 120 different kind of data and I need to find which sequences of data how many times repeated?

For instance:

```<code>a
b
c
a
b
d
a
b
c
</code>```

I am trying to find repetition order some people call it frequency sequence. So how many times aa and abc and ab and bc and abca and so on are there in this column? I mean I need to find how many times this data has same group of rows.

For this example it has 4 different data so there are a lot of combination of it. For calculation: C(4,1)*4!+C(4,2)*2!+C(4,3)*3!+C(4,4) different order and I need to calculate it for each order how many times are there?

My short part of real column data example:(each contiguous data is equal to a row)

```<code>3E010000
2010000
2010007
2010008
2010000
2010003
2010009
0201000A
0B01000C
2010002
3E010000
2010000
2010007
0B010014
2010009
0201000A
0B01000C
2010002
</code>```

Now if you could check this whole main column for this group of data:

```<code>3E010000
2010000
2010007
</code>```

and this

```<code>3E010000
2010000
</code>```

and this

```<code>2010009
0201000A
0B01000C
2010002
</code>```

and so on. You can see they were repeated more than once.

These rows repeat in the main first column and I am trying to find 1,2,3,4 and max 5 groups of orders out of 120 kind of data combination.

I am using Microsoft SQL Server 2014. But if it is not possible in Microsoft SQL Server, then you could give me any advice or other tools. Could you help me please? Thank you so much!

Output:

```<code>0B010009 ,0B010009,0B010009,2010005,2010005,2010005     2   9

0B010014 ,0B010014,0B010014,16010002,16010002,16010002     2    3

2010002,2010002,0201FFE0,0201FFE0       2   13

0B0114B5 ,0B0114B5,0B0114B5,2010002,2010002,2010002,2010004,2010004,2010004    3    3

070105B3 ,070105B3,070105B3,2010005,2010005,2010005,0201FFE1 ,0201FFE1,0201FFE1
   3    2

3E010000 ,3E010000,3E010000,0B010010,0B010010,0B010010 ,0B01F61D ,0B01F61D,0B01F61D     3   6

3E010002 ,3E010002,3E010002,0B010013,0B010013,0B010013 ,0B01F80D ,0B01F80D,0B01F80D    3    3

0B010003 ,0B010003,2010006,2010006,0B01000A ,0B01000A,2010005,2010005   4   2

0B01FFE1 ,0B01FFE1,0B01FFE1,0B010013,0B010013,0B010013 ,0B01EAD0 ,0B01EAD0,0B01EAD0,0B010004,0B010004,0B010004     4    4

0B01000C ,0B01000C,0B01000C,0B01FCBD,0B01FCBD,0B01FCBD ,0701FFE0 ,0701FFE0,0701FFE0,0B01000A,0B01000A,0B01000A     4    5
</code>```

答:
Below query finds duplicate patterns for 2, 3, 4 and 5 repeating rows.

It uses 'LEAD' and 'HASHBYTES' functions.

Query works by computing a hash sequence for values in current row + following rows and then grouping on these hash values to find "duplicate" patterns. This process is done for each row.

Note: an ever increasing sequence column (to denote row position) i.e. ID is assumed.

```<code>CREATE TABLE #Data( ID INT IDENTITY PRIMARY KEY, Val VARCHAR( 20 ))
INSERT INTO #Data
VALUES
( '3E010000' ), ( '2010000' ), ( '2010007' ), ( '2010008' ), ( '2010000' ),
( '2010003' ), ( '2010009' ), ( '0201000A' ), ( '0B01000C' ), ( '2010002' ),
( '3E010000' ), ( '2010000' ), ( '2010007' ), ( '0B010014' ), ( '2010009' ),
( '0201000A' ), ( '0B01000C' ), ( '2010002' )

SELECT Pat3Rows, COUNT(*) AS Cnt
FROM(
    SELECT *,
        HASHBYTES( 'MD5', Val + LEAD( Val, 1, '' ) OVER( ORDER BY ID )) AS Pat2Rows,
        HASHBYTES( 'MD5', Val + LEAD( Val, 1, '' ) OVER( ORDER BY ID ) + LEAD( Val, 2, '' ) OVER( ORDER BY ID )) AS Pat3Rows,
        HASHBYTES( 'MD5', Val + LEAD( Val, 1, '' ) OVER( ORDER BY ID ) + LEAD( Val, 2, '' ) OVER( ORDER BY ID ) + LEAD( Val, 3, '' ) OVER( ORDER BY ID )) AS Pat4Rows,
        HASHBYTES( 'MD5', Val + LEAD( Val, 1, '' ) OVER( ORDER BY ID ) + LEAD( Val, 2, '' ) OVER( ORDER BY ID ) + LEAD( Val, 3, '' ) OVER( ORDER BY ID ) + LEAD( Val, 4, '' ) OVER( ORDER BY ID )) AS Pat5Rows
    FROM #Data AS D1
) AS HashedGroups
GROUP BY Pat3Rows
HAVING COUNT(*) > 1
</code>```

Note: there is a possibility, albeit extremely remote, of encountering hash collisions, so the above logic is not guaranteed to handle all theoretically possible cases. In summary I would not recommend using it if someone's life depends on the procedure to always be 100% accurate.

You did not specify how the output should look like so I will leave this up to you.

I have also tested this on my laptop with 18,000 rows and it produces a result in less than 1 second.

Sample use case:

```<code>;WITH DataHashed AS(
SELECT *,
    HASHBYTES( 'MD5', Val + ',' +  LEAD( Val, 1, '' ) OVER( ORDER BY ID )) AS Pat2Rows,
    HASHBYTES( 'MD5', Val + ',' +  LEAD( Val, 1, '' ) OVER( ORDER BY ID ) + ',' + LEAD( Val, 2, '' ) OVER( ORDER BY ID )) AS Pat3Rows,
    HASHBYTES( 'MD5', Val + ',' +  LEAD( Val, 1, '' ) OVER( ORDER BY ID ) + ',' + LEAD( Val, 2, '' ) OVER( ORDER BY ID ) + ',' +  LEAD( Val, 3, '' ) OVER( ORDER BY ID )) AS Pat4Rows,
    HASHBYTES( 'MD5', Val + ',' +  LEAD( Val, 1, '' ) OVER( ORDER BY ID ) + ',' + LEAD( Val, 2, '' ) OVER( ORDER BY ID ) + ',' +  LEAD( Val, 3, '' ) OVER( ORDER BY ID ) + ',' +  LEAD( Val, 4, '' ) OVER( ORDER BY ID )) AS Pat5Rows
FROM #Data ),
RepeatingPatterns AS(
    SELECT MIN( ID ) AS FirstRow, Pat2Rows AS PatternHash, 2 AS PatternSize, COUNT( * ) AS Cnt FROM DataHashed GROUP BY Pat2Rows HAVING COUNT(*) > 1
    UNION ALL
    SELECT MIN( ID ) AS FirstRow, Pat3Rows, 3 AS PatternSize, COUNT( * ) AS Cnt FROM DataHashed GROUP BY Pat3Rows HAVING COUNT(*) > 1
    UNION ALL
    SELECT MIN( ID ) AS FirstRow, Pat4Rows, 4 AS PatternSize, COUNT( * ) AS Cnt FROM DataHashed GROUP BY Pat4Rows HAVING COUNT(*) > 1
    UNION ALL
    SELECT MIN( ID ) AS FirstRow, Pat5Rows, 5 AS PatternSize, COUNT( * ) AS Cnt FROM DataHashed GROUP BY Pat5Rows HAVING COUNT(*) > 1
)
--SELECT * FROM RepeatingPatterns
SELECT
     CONVERT( VARCHAR( 50 ), SUBSTRING(
        ( SELECT ',' + D.Val  AS [text()]
        FROM #Data AS D
        WHERE RP.FirstRow <= D.ID AND D.ID < ( RP.FirstRow + RP.PatternSize )
        ORDER BY D.ID
        FOR XML PATH ('')
        ), 2, 1000 )) AS Pattern, CONVERT( VARCHAR( 35 ), PatternHash, 1 ) AS PatternHash, RP.PatternSize, Cnt
FROM RepeatingPatterns AS RP
</code>```

Sample output:

```<code>Pattern                                            PatternHash                         PatternSize Cnt
-------------------------------------------------- ----------------------------------- ----------- -----------
0201000A,0B01000C                                  0x499D8B1750A9BF57795B4D60D58DCF81  2           2
2010000,2010007                                    0x7EDE1E675D934F3035DACAC53F74DD14  2           2
3E010000,2010000                                   0x85FBFD817CFBB9BD08E983671EB594B7  2           2
2010009,0201000A                                   0x8E18E36B989BD859AF039238711A7F8C  2           2
0B01000C,2010002                                   0xF1EABB115FB3AEF2D162FB3EC7B6AFDA  2           2
0201000A,0B01000C,2010002                          0x6DE203B38A13501881610133C1EDBF85  3           2
2010009,0201000A,0B01000C                          0x9EB3ACFE8580A39FC530C7CA54830602  3           2
3E010000,2010000,2010007                           0xE414661F54C985B7ED9FA82FF05C1219  3           2
2010009,0201000A,0B01000C,2010002                  0x7FCDB748E37A6F6299AE8B269A4B0E49  4           2
</code>```

Body:
I need to find frequency of sequences of data rows.I have like 17000 rows data which is including almost 120 different kind of data and I need to find which sequences of data how many times repeated?

For instance:

a
b
c
a
b
d
a
b
c

I am trying to find repetition order some people call it frequency sequence. So how many times aa and abc and ab and bc and abca and so on are there in this column? I mean I need to find how many times this data has same group of rows.

For this example it has 4 different data so there are a lot of combination of it. For calculation: C(4,1)*4!+C(4,2)*2!+C(4,3)*3!+C(4,4) different order and I need to calculate it for each order how many times are there?

My short part of real column data example:(each contiguous data is equal to a row)

3E010000
2010000
2010007
2010008
2010000
2010003
2010009
0201000A
0B01000C
2010002
3E010000
2010000
2010007
0B010014
2010009
0201000A
0B01000C
2010002

Now if you could check this whole main column for this group of data:

3E010000
2010000
2010007

and this

3E010000
2010000

and this

2010009
0201000A
0B01000C
2010002

and so on. You can see they were repeated more than once.

These rows repeat in the main first column and I am trying to find 1,2,3,4 and max 5 groups of orders out of 120 kind of data combination.

I am using Microsoft SQL Server 2014. But if it is not possible in Microsoft SQL Server, then you could give me any advice or other tools. Could you help me please? Thank you so much!

Output:

0B010009 ,0B010009,0B010009,2010005,2010005,2010005     2   9

0B010014 ,0B010014,0B010014,16010002,16010002,16010002     2    3

2010002,2010002,0201FFE0,0201FFE0       2   13

0B0114B5 ,0B0114B5,0B0114B5,2010002,2010002,2010002,2010004,2010004,2010004    3    3

070105B3 ,070105B3,070105B3,2010005,2010005,2010005,0201FFE1 ,0201FFE1,0201FFE1
   3    2

3E010000 ,3E010000,3E010000,0B010010,0B010010,0B010010 ,0B01F61D ,0B01F61D,0B01F61D     3   6

3E010002 ,3E010002,3E010002,0B010013,0B010013,0B010013 ,0B01F80D ,0B01F80D,0B01F80D    3    3

0B010003 ,0B010003,2010006,2010006,0B01000A ,0B01000A,2010005,2010005   4   2

0B01FFE1 ,0B01FFE1,0B01FFE1,0B010013,0B010013,0B010013 ,0B01EAD0 ,0B01EAD0,0B01EAD0,0B010004,0B010004,0B010004     4    4

0B01000C ,0B01000C,0B01000C,0B01FCBD,0B01FCBD,0B01FCBD ,0701FFE0 ,0701FFE0,0701FFE0,0B01000A,0B01000A,0B01000A     4    5

Body:
Below query finds duplicate patterns for 2, 3, 4 and 5 repeating rows.

It uses 'LEAD' and 'HASHBYTES' functions.

Query works by computing a hash sequence for values in current row + following rows and then grouping on these hash values to find "duplicate" patterns. This process is done for each row.

Note: an ever increasing sequence column (to denote row position) i.e. ID is assumed.

CREATE TABLE #Data( ID INT IDENTITY PRIMARY KEY, Val VARCHAR( 20 ))
INSERT INTO #Data
VALUES
( '3E010000' ), ( '2010000' ), ( '2010007' ), ( '2010008' ), ( '2010000' ),
( '2010003' ), ( '2010009' ), ( '0201000A' ), ( '0B01000C' ), ( '2010002' ),
( '3E010000' ), ( '2010000' ), ( '2010007' ), ( '0B010014' ), ( '2010009' ),
( '0201000A' ), ( '0B01000C' ), ( '2010002' )

SELECT Pat3Rows, COUNT(*) AS Cnt
FROM(
    SELECT *,
        HASHBYTES( 'MD5', Val + LEAD( Val, 1, '' ) OVER( ORDER BY ID )) AS Pat2Rows,
        HASHBYTES( 'MD5', Val + LEAD( Val, 1, '' ) OVER( ORDER BY ID ) + LEAD( Val, 2, '' ) OVER( ORDER BY ID )) AS Pat3Rows,
        HASHBYTES( 'MD5', Val + LEAD( Val, 1, '' ) OVER( ORDER BY ID ) + LEAD( Val, 2, '' ) OVER( ORDER BY ID ) + LEAD( Val, 3, '' ) OVER( ORDER BY ID )) AS Pat4Rows,
        HASHBYTES( 'MD5', Val + LEAD( Val, 1, '' ) OVER( ORDER BY ID ) + LEAD( Val, 2, '' ) OVER( ORDER BY ID ) + LEAD( Val, 3, '' ) OVER( ORDER BY ID ) + LEAD( Val, 4, '' ) OVER( ORDER BY ID )) AS Pat5Rows
    FROM #Data AS D1
) AS HashedGroups
GROUP BY Pat3Rows
HAVING COUNT(*) > 1

Note: there is a possibility, albeit extremely remote, of encountering hash collisions, so the above logic is not guaranteed to handle all theoretically possible cases. In summary I would not recommend using it if someone's life depends on the procedure to always be 100% accurate.

You did not specify how the output should look like so I will leave this up to you.

I have also tested this on my laptop with 18,000 rows and it produces a result in less than 1 second.

Sample use case:

;WITH DataHashed AS(
SELECT *,
    HASHBYTES( 'MD5', Val + ',' +  LEAD( Val, 1, '' ) OVER( ORDER BY ID )) AS Pat2Rows,
    HASHBYTES( 'MD5', Val + ',' +  LEAD( Val, 1, '' ) OVER( ORDER BY ID ) + ',' + LEAD( Val, 2, '' ) OVER( ORDER BY ID )) AS Pat3Rows,
    HASHBYTES( 'MD5', Val + ',' +  LEAD( Val, 1, '' ) OVER( ORDER BY ID ) + ',' + LEAD( Val, 2, '' ) OVER( ORDER BY ID ) + ',' +  LEAD( Val, 3, '' ) OVER( ORDER BY ID )) AS Pat4Rows,
    HASHBYTES( 'MD5', Val + ',' +  LEAD( Val, 1, '' ) OVER( ORDER BY ID ) + ',' + LEAD( Val, 2, '' ) OVER( ORDER BY ID ) + ',' +  LEAD( Val, 3, '' ) OVER( ORDER BY ID ) + ',' +  LEAD( Val, 4, '' ) OVER( ORDER BY ID )) AS Pat5Rows
FROM #Data ),
RepeatingPatterns AS(
    SELECT MIN( ID ) AS FirstRow, Pat2Rows AS PatternHash, 2 AS PatternSize, COUNT( * ) AS Cnt FROM DataHashed GROUP BY Pat2Rows HAVING COUNT(*) > 1
    UNION ALL
    SELECT MIN( ID ) AS FirstRow, Pat3Rows, 3 AS PatternSize, COUNT( * ) AS Cnt FROM DataHashed GROUP BY Pat3Rows HAVING COUNT(*) > 1
    UNION ALL
    SELECT MIN( ID ) AS FirstRow, Pat4Rows, 4 AS PatternSize, COUNT( * ) AS Cnt FROM DataHashed GROUP BY Pat4Rows HAVING COUNT(*) > 1
    UNION ALL
    SELECT MIN( ID ) AS FirstRow, Pat5Rows, 5 AS PatternSize, COUNT( * ) AS Cnt FROM DataHashed GROUP BY Pat5Rows HAVING COUNT(*) > 1
)
--SELECT * FROM RepeatingPatterns
SELECT
     CONVERT( VARCHAR( 50 ), SUBSTRING(
        ( SELECT ',' + D.Val  AS [text()]
        FROM #Data AS D
        WHERE RP.FirstRow <= D.ID AND D.ID < ( RP.FirstRow + RP.PatternSize )
        ORDER BY D.ID
        FOR XML PATH ('')
        ), 2, 1000 )) AS Pattern, CONVERT( VARCHAR( 35 ), PatternHash, 1 ) AS PatternHash, RP.PatternSize, Cnt
FROM RepeatingPatterns AS RP

Sample output:

Pattern                                            PatternHash                         PatternSize Cnt
-------------------------------------------------- ----------------------------------- ----------- -----------
0201000A,0B01000C                                  0x499D8B1750A9BF57795B4D60D58DCF81  2           2
2010000,2010007                                    0x7EDE1E675D934F3035DACAC53F74DD14  2           2
3E010000,2010000                                   0x85FBFD817CFBB9BD08E983671EB594B7  2           2
2010009,0201000A                                   0x8E18E36B989BD859AF039238711A7F8C  2           2
0B01000C,2010002                                   0xF1EABB115FB3AEF2D162FB3EC7B6AFDA  2           2
0201000A,0B01000C,2010002                          0x6DE203B38A13501881610133C1EDBF85  3           2
2010009,0201000A,0B01000C                          0x9EB3ACFE8580A39FC530C7CA54830602  3           2
3E010000,2010000,2010007                           0xE414661F54C985B7ED9FA82FF05C1219  3           2
2010009,0201000A,0B01000C,2010002                  0x7FCDB748E37A6F6299AE8B269A4B0E49  4           2


问:
Angularjs - How to prevent user from going to inner pages without logging in and how to store session upon successfull login
I am using angularjs and angularjs ui-route. I am building a login page and I  want to prevent any user to go to inner pages without logging in. I have found a similar question but it lacks information. Also I want to store session upon successful login.

Here is my homeroute.js

```<code>    'use strict';

var application = angular.module('App', ['ui.router']);

    application.config(['$stateProvider', '$urlRouterProvider',
    function($stateProvider, $urlRouterProvider) {

        // For unmatched routes
        $urlRouterProvider.otherwise('/');

        // Application routes
        $stateProvider
            .state('login', {
                url: '/login',
                templateUrl: './views/login.html',
                controller: 'logincontroller'
            })
            .state('/', {
                url: '/',
                templateUrl: './views/home.html'
            })
             .state('customerHome', {
                url: '/customerHome',
                templateUrl: './views/customerHomepage.html'
            })
            .state('signup', {
                url: '/signup',
                templateUrl: './views/register.html',
                controller: 'registercontroller'
            });
    }
]);

        application.run(function($rootScope, $location) {
        var customerHome = ['/customerHome'];
        $rootScope.$on('$routeLogin', function() {
            if(customerHome.indexOf($location.path()) != -1 && sessionStorage.getItem('userLogin')) {
                $location.path('/login');
            }
        });
    });

    application.controller('registercontroller', ['$scope', '$http', function($scope, $http) {
                $scope.formData = {};
                $scope.userform = "";
                $scope.register = function() {
                    $http({
                        method: 'POST',
                        url: './services/loginsubmit.php',
                        data: $scope.formData
                    }).then(function(response) {
                        console.log(response);
                        if(response.data.empty == true) {
                            $scope.userform = "Please fill the form.";
                        } else if(response.data.emailError == true) {
                            $scope.userform = "Invalid Email.";
                        } else if(response.data.validation == true) {
                            $scope.userform = "Username already exists.";
                        } else if(response.data.validateUsername == true) {
                            $scope.userform = "Username must be more than 5 characters.";
                        } else if(response.data.validatePassword == true) {
                            $scope.userform = "Password must be more than 5 characters.";
                        } else if(response.data.registerSuccess == false) {
                            $scope.userform = "Registration Successful.";
                            $scope.formData = {};
                        } else if(response.data.registerSuccess == true) {
                            $scope.userform = "Registration Failed";
                        }
                    });
                }
            }]);

    application.controller('logincontroller', ['$scope', '$http', '$location', '$rootScope', function($scope, $http, $location, $rootScope) {
        $scope.loginData = {};
        $scope.loginUser = "";
        $scope.login = function() {
            $http({
                method: 'POST',
                url: './services/loginservice.php',
                data: $scope.loginData
            }).then(function(response) {
                console.log(response);
                if(response.data.UsernameLogin == true) {
                    $scope.loginUser = "Invalid username or password.";
                } else {
                    sessionStorage.setItem('userLogin', response.data.usernameSession);
                    $location.path('/customerHome');
                }
            });
        }
    }]);
</code>```

Here is my loginservice.php

```<code>    <?php

    include '../connection/connect.php';

    $formLogin = json_decode(file_get_contents("php://input"));

    $data = array();
    $check_UsernameLogin = false;

    $username = $formLogin->username;
    $password = $formLogin->password;

    $login = mysqli_query($conn, "SELECT username FROM customer WHERE username='$username' AND customer_password='$password'");

    $check_username = mysqli_num_rows($login);

    if($check_username == 0) {
        $check_UsernameLogin = true;
    } else {
        $check_UsernameLogin = false;
    }

    $data["UsernameLogin"] = $check_UsernameLogin;
    $data["usernameSession"] = $login;

    echo json_encode($data);

 ?>
</code>```

Here is my login.html

```<code>    <!-- Navigation Bar -->
    <nav class="navbar navbar-inverse navbar-fixed-top">
      <div class="container-fluid">
        <div class="navbar-header">
          <a class="navbar-brand" href="#!/">Hostelry Service</a>
        </div>
        <ul class="nav navbar-nav">
          <li><a href="#!/">Home</a></li>
          <li><a href="#">Hostelries</a></li>
          <li><a href="#">Compare</a></li>
          <li><a href="#">About Us</a></li>
          <li><a href="#">Contact</a></li>
        </ul>
        <ul class="nav navbar-nav navbar-right">
          <li><a href="#!signup"><span class="glyphicon glyphicon-user"></span> Sign Up</a></li>
          <li><a href="#!login"><span class="glyphicon glyphicon-log-in"></span> Login</a></li>
        </ul>
      </div>
    </nav>
<div class="row"  style="padding-top: 100px;">
  <div class="col-md-4 col-md-offset-4">
    <div class="panel panel-primary">
      <div class="panel-heading" style="padding-left: 190px;">Log in</div>
      <div class="panel-body">
        <form method="POST" ng-submit="login()">
          <input class="form-control" type="text" ng-model="loginData.username" placeholder="Username"><br>
          <input class="form-control" type="password" ng-model="loginData.password" placeholder="Password"><br>
          <button type="submit" class="btn btn-primary btn-block">Submit</button><br>
          <p class="alert alert-success" ng-show="loginUser">{{loginUser}}</p>
        </form>
      </div>
  </div>
</div>
</code>```

Here is my customerHomepage.html

```<code>    <!-- Navigation Bar -->
    <nav class="navbar navbar-inverse navbar-fixed-top">
      <div class="container-fluid">
        <div class="navbar-header">
          <a class="navbar-brand" href="#!/">Hostelry Service</a>
        </div>
        <ul class="nav navbar-nav">
          <li><a href="#!/">Home</a></li>
          <li><a href="#">Hostelries</a></li>
          <li><a href="#">Compare</a></li>
          <li><a href="#">About Us</a></li>
          <li><a href="#">Contact</a></li>
        </ul>
        <ul class="nav navbar-nav navbar-right">
          <li><a href="#!signup"><span class="glyphicon glyphicon-user"></span> Sign Up</a></li>
          <li><a href="#!login"><span class="glyphicon glyphicon-log-in"></span> Login</a></li>
        </ul>
      </div>
    </nav>
<div class="row"  style="padding-top: 100px;">
  <div class="col-md-4 col-md-offset-4">
    <div class="panel panel-primary">
      <div class="panel-heading" style="padding-left: 190px;">Log in</div>
      <div class="panel-body">
        <form method="POST" ng-submit="login()">
          <input class="form-control" type="text" ng-model="loginData.username" placeholder="Username"><br>
          <input class="form-control" type="password" ng-model="loginData.password" placeholder="Password"><br>
          <button type="submit" class="btn btn-primary btn-block">Submit</button><br>
          <p class="alert alert-success" ng-show="loginUser">{{loginUser}}</p>
        </form>
      </div>
  </div>
</div>
</code>```

I am new to using .run() and $rootScope on angularjs.

答:
To do this with PHP, you need to save user credentials (or login status) to $_SESSION and verify them everytime you serve a file. You need to give your files php extension for compatibility.

Set you index.php to call itself on form submission.

When called with the user name and password, authenticate them, and set the  $_SESSION['authenticated'] variable to true in case of authentic login.

Now check this $_SESSION variable everytime you serve your templates.

```<code>  <?PHP
    if ($_SESSION['authenticated'] == false)
        die('Permission denied');
  ?>
</code>```

However, although it works, there are lot of new and more secure ways to handle this via methods such as jwt.

Body:
I am using angularjs and angularjs ui-route. I am building a login page and I  want to prevent any user to go to inner pages without logging in. I have found a similar question but it lacks information. Also I want to store session upon successful login.

Here is my homeroute.js

    'use strict';

var application = angular.module('App', ['ui.router']);

    application.config(['$stateProvider', '$urlRouterProvider',
    function($stateProvider, $urlRouterProvider) {

        // For unmatched routes
        $urlRouterProvider.otherwise('/');

        // Application routes
        $stateProvider
            .state('login', {
                url: '/login',
                templateUrl: './views/login.html',
                controller: 'logincontroller'
            })
            .state('/', {
                url: '/',
                templateUrl: './views/home.html'
            })
             .state('customerHome', {
                url: '/customerHome',
                templateUrl: './views/customerHomepage.html'
            })
            .state('signup', {
                url: '/signup',
                templateUrl: './views/register.html',
                controller: 'registercontroller'
            });
    }
]);

        application.run(function($rootScope, $location) {
        var customerHome = ['/customerHome'];
        $rootScope.$on('$routeLogin', function() {
            if(customerHome.indexOf($location.path()) != -1 && sessionStorage.getItem('userLogin')) {
                $location.path('/login');
            }
        });
    });

    application.controller('registercontroller', ['$scope', '$http', function($scope, $http) {
                $scope.formData = {};
                $scope.userform = "";
                $scope.register = function() {
                    $http({
                        method: 'POST',
                        url: './services/loginsubmit.php',
                        data: $scope.formData
                    }).then(function(response) {
                        console.log(response);
                        if(response.data.empty == true) {
                            $scope.userform = "Please fill the form.";
                        } else if(response.data.emailError == true) {
                            $scope.userform = "Invalid Email.";
                        } else if(response.data.validation == true) {
                            $scope.userform = "Username already exists.";
                        } else if(response.data.validateUsername == true) {
                            $scope.userform = "Username must be more than 5 characters.";
                        } else if(response.data.validatePassword == true) {
                            $scope.userform = "Password must be more than 5 characters.";
                        } else if(response.data.registerSuccess == false) {
                            $scope.userform = "Registration Successful.";
                            $scope.formData = {};
                        } else if(response.data.registerSuccess == true) {
                            $scope.userform = "Registration Failed";
                        }
                    });
                }
            }]);

    application.controller('logincontroller', ['$scope', '$http', '$location', '$rootScope', function($scope, $http, $location, $rootScope) {
        $scope.loginData = {};
        $scope.loginUser = "";
        $scope.login = function() {
            $http({
                method: 'POST',
                url: './services/loginservice.php',
                data: $scope.loginData
            }).then(function(response) {
                console.log(response);
                if(response.data.UsernameLogin == true) {
                    $scope.loginUser = "Invalid username or password.";
                } else {
                    sessionStorage.setItem('userLogin', response.data.usernameSession);
                    $location.path('/customerHome');
                }
            });
        }
    }]);

Here is my loginservice.php

    <?php

    include '../connection/connect.php';

    $formLogin = json_decode(file_get_contents("php://input"));

    $data = array();
    $check_UsernameLogin = false;

    $username = $formLogin->username;
    $password = $formLogin->password;

    $login = mysqli_query($conn, "SELECT username FROM customer WHERE username='$username' AND customer_password='$password'");

    $check_username = mysqli_num_rows($login);

    if($check_username == 0) {
        $check_UsernameLogin = true;
    } else {
        $check_UsernameLogin = false;
    }

    $data["UsernameLogin"] = $check_UsernameLogin;
    $data["usernameSession"] = $login;

    echo json_encode($data);

 ?>

Here is my login.html

          Hostelry Service

Home

Hostelries

Compare

About Us

Contact

 Sign Up

 Login

Log in

        <form method="POST" ng-submit="login()">
          <input class="form-control" type="text" ng-model="loginData.username" placeholder="Username">

          <input class="form-control" type="password" ng-model="loginData.password" placeholder="Password">

          <button type="submit" class="btn btn-primary btn-block">Submit</button>

{{loginUser}}

        </form>

Here is my customerHomepage.html

          Hostelry Service

Home

Hostelries

Compare

About Us

Contact

 Sign Up

 Login

Log in

        <form method="POST" ng-submit="login()">
          <input class="form-control" type="text" ng-model="loginData.username" placeholder="Username">

          <input class="form-control" type="password" ng-model="loginData.password" placeholder="Password">

          <button type="submit" class="btn btn-primary btn-block">Submit</button>

{{loginUser}}

        </form>

I am new to using .run() and $rootScope on angularjs.

Body:
To do this with PHP, you need to save user credentials (or login status) to $_SESSION and verify them everytime you serve a file. You need to give your files php extension for compatibility.

Set you index.php to call itself on form submission.

When called with the user name and password, authenticate them, and set the  $_SESSION['authenticated'] variable to true in case of authentic login.

Now check this $_SESSION variable everytime you serve your templates.

  <?PHP
    if ($_SESSION['authenticated'] == false)
        die('Permission denied');
  ?>

However, although it works, there are lot of new and more secure ways to handle this via methods such as jwt.


问:
Lazily loaded module in Angular 4 errors with "Component X is not part of any NgModule"
I have an app with loads of modules. It works perfectly. I want to make one module lazy load as it is not often hit by normal users.

So, I change the route for LazyModule to use loadChildren, the main app still loads ok, but when I try and hit one of the child routes of LazyModule, it gives me this error:

Error: Uncaught (in promise): Error: Component HomeComponent is not
  part of any NgModule or the module has not been imported into your
  module.

HomeComponent is not used in LazyModule. It is part of a different module, call it MainModule.

MainModule and LazyModule are both imported and exported to/from ComponentsModule which then gets imported into the app.module.

There is also SharedModule which is imported to all the other modules mentioned.

So my questions:

Why does LazyModule try to load components in MainModule when it has absolutely no dependencies on it?

Why does it work with normal routing, but not with lazy loading?

Thanks in advance for your help.

Modules are here:

LazyModule

```<code>import ...;

const routes: Routes = [
    {
        path: '',
        redirectTo: '/lazy-page/1',
        pathMatch: 'full'
    },
    {
        path: '1',
        component: LazyPage1Component
    }
];

@NgModule({
  imports: [
      RouterModule.forChild(routes),
      SharedModule
  ],
  declarations: [
      LazyPage1Component
  ]
})
export class LazyModule { }
</code>```

MainModule

```<code>import ...;

@NgModule({
  imports: [
      SharedModule
  ],
  declarations: [
      HomeComponent
  ],
  exports: [
      HomeComponent
  ]
})
export class MainModule { }
</code>```

ComponentsModule

```<code>import ...;

@NgModule({
  imports: [
    SharedModule,
    MainModule,
    LazyModule
  ],
  declarations: [],
  exports: [
    SharedModule,
    MainModule,
    LazyModule
  ]
})
export class ComponentsModule { }
</code>```

AppModule

```<code>import ...;

@NgModule({
  imports: [
    ComponentsModule
  ],
  declarations: [
    AppComponent
  ],
  providers: [{provide: APP_BASE_HREF, useValue : '/' }],
  bootstrap: [AppComponent]
})
export class AppModule { }
</code>```

AppRoutingModule

```<code>const routes: Routes = [
{
    path: '',
    component: HomeComponent
},
{
    path: 'lazy-page',
    loadChildren: './components/lazy/lazy.module#LazyModule',
},
</code>```

EDIT: I found a hack to get around it for now, but I really want a proper solution. The hack is just to import every single module in my app into LazyModule as well as AppModule. This is a terrible solution, because the whole idea of having a lazy-loaded module is to decouple it from the rest of the app as it is separate. I don't want to import everything twice, and nor should I need to since none of the modules imported are ever used or referenced inside LazyModule.

答:
Looking at your code, I just want to comment that lazy loaded modules need not be imported into your app module as your are adding it to Component module and importing to app module.

Lazy loaded modules can remain as independent module from app and will be loaded when the route needs activation.

Body:
I have an app with loads of modules. It works perfectly. I want to make one module lazy load as it is not often hit by normal users.

So, I change the route for LazyModule to use loadChildren, the main app still loads ok, but when I try and hit one of the child routes of LazyModule, it gives me this error:

Error: Uncaught (in promise): Error: Component HomeComponent is not
  part of any NgModule or the module has not been imported into your
  module.

HomeComponent is not used in LazyModule. It is part of a different module, call it MainModule.

MainModule and LazyModule are both imported and exported to/from ComponentsModule which then gets imported into the app.module.

There is also SharedModule which is imported to all the other modules mentioned.

So my questions:

Why does LazyModule try to load components in MainModule when it has absolutely no dependencies on it?

Why does it work with normal routing, but not with lazy loading?

Thanks in advance for your help.

Modules are here:

LazyModule

import ...;

const routes: Routes = [
    {
        path: '',
        redirectTo: '/lazy-page/1',
        pathMatch: 'full'
    },
    {
        path: '1',
        component: LazyPage1Component
    }
];

@NgModule({
  imports: [
      RouterModule.forChild(routes),
      SharedModule
  ],
  declarations: [
      LazyPage1Component
  ]
})
export class LazyModule { }

MainModule

import ...;

@NgModule({
  imports: [
      SharedModule
  ],
  declarations: [
      HomeComponent
  ],
  exports: [
      HomeComponent
  ]
})
export class MainModule { }

ComponentsModule

import ...;

@NgModule({
  imports: [
    SharedModule,
    MainModule,
    LazyModule
  ],
  declarations: [],
  exports: [
    SharedModule,
    MainModule,
    LazyModule
  ]
})
export class ComponentsModule { }

AppModule

import ...;

@NgModule({
  imports: [
    ComponentsModule
  ],
  declarations: [
    AppComponent
  ],
  providers: [{provide: APP_BASE_HREF, useValue : '/' }],
  bootstrap: [AppComponent]
})
export class AppModule { }

AppRoutingModule

const routes: Routes = [
{
    path: '',
    component: HomeComponent
},
{
    path: 'lazy-page',
    loadChildren: './components/lazy/lazy.module#LazyModule',
},

EDIT: I found a hack to get around it for now, but I really want a proper solution. The hack is just to import every single module in my app into LazyModule as well as AppModule. This is a terrible solution, because the whole idea of having a lazy-loaded module is to decouple it from the rest of the app as it is separate. I don't want to import everything twice, and nor should I need to since none of the modules imported are ever used or referenced inside LazyModule.


问:
angular cli install command showing errors
npm install -g @angular/cli

I am trying to install angular cli on Windows 10, I have already installed npm and node, and have verified their version, they are above then what is required for angular cli to install but when I run install command on the prompt it show error.

答:
first try to see node and npm is installed successfully using following commands on cmd

```<code>node -v
</code>```

for node and it will return the version of node,then

```<code>npm -v
</code>```

then it will return the version of npm after that in windows go to environment variables and see node environmental varible is there. after that

```<code>npm cache clean --force
</code>```

use to clean the cache and go to users/Appdata/roaming and delete all the node modules in npm cache folder and restart your computer and give the following command.

```<code>npm install -g @angular/cli
</code>```

Body:
first try to see node and npm is installed successfully using following commands on cmd

node -v

for node and it will return the version of node,then

npm -v

then it will return the version of npm after that in windows go to environment variables and see node environmental varible is there. after that

npm cache clean --force

use to clean the cache and go to users/Appdata/roaming and delete all the node modules in npm cache folder and restart your computer and give the following command.

npm install -g @angular/cli


问:
Google cloud 404 after verifying file exists
I have another project where this same code works successfully, so it may be some configuration option I've missed this time around. I'm using the google cloud API to access firebase storage.

For clarity, the file does exist.

var storage = require('@google-cloud/storage')({
  keyFilename: 'serviceAccountKey.json',
  projectId: 'my-id'
 });
var bucket = storage.bucket('my-id.appspot.com');

var file = bucket.file('directory/file.json'); //this exists!
file.exists(function(err, exists){
   console.log("Checking for challenges file. Results:" + exists + ", err:" + err); //returns "Checking for challenges file. Results:true, err:nil"
       if (exists) {
     console.log("File exists. Printing."); //prints "File exists. Printing."
     file.download().then(function(currentFileData) {
      console.log("This line is never reached.");
     }).catch(err => {
      console.error('ERROR:', err); //gives a 404 error
     });
       }
});```

Instead of printing "this line is never reached.", it prints the following caught error:
ERROR: { ApiError: Not Found at Object.parseHttpRespMessage (/user_code/node_modules/@google-cloud/storage/node_modules/@google-cloud/common/src/util.js:156:33) at Object.handleResp ... ... The full error is colossal, so I won't post it here in its entirety unless required.

答:
It's possible the user that is trying to access the file only have access over the bucket but not over the file. Check the ACLs of both the bucket and the file in both projects and compare what you get:

```<code>myBucket.acl.get()
    .then(acls => console.log("Bucket ACLs:", acls));
myFile.acl.get()
    .then(acls => console.log("File ACLs:", acls));
</code>```

You should see an output like this:

```<code>[ [ { entity: 'user-abenavides333@gmail.com', role: 'OWNER' },
    { entity: 'user-dwilches@gmail.com', role: 'OWNER' } ],
  { kind: 'storage#objectAccessControls',
    items: [ [Object], [Object] ] } ]
</code>```

If there is no difference there, try the following more verbose versions of the same code:

```<code>myBucket.acl.get()
    .then(acls => console.log("Bucket ACLs:", JSON.stringify(acls, null, '\t')));
myFile.acl.get()
    .then(acls => console.log("File ACLs:", JSON.stringify(acls, null, '\t')));
</code>```

Body:
I have another project where this same code works successfully, so it may be some configuration option I've missed this time around. I'm using the google cloud API to access firebase storage.

For clarity, the file does exist.

var storage = require('@google-cloud/storage')({
  keyFilename: 'serviceAccountKey.json',
  projectId: 'my-id'
 });
var bucket = storage.bucket('my-id.appspot.com');

var file = bucket.file('directory/file.json'); //this exists!
file.exists(function(err, exists){
   console.log("Checking for challenges file. Results:" + exists + ", err:" + err); //returns "Checking for challenges file. Results:true, err:nil"
       if (exists) {
     console.log("File exists. Printing."); //prints "File exists. Printing."
     file.download().then(function(currentFileData) {
      console.log("This line is never reached.");
     }).catch(err => {
      console.error('ERROR:', err); //gives a 404 error
     });
       }
});

Instead of printing "this line is never reached.", it prints the following caught error:
ERROR: { ApiError: Not Found at Object.parseHttpRespMessage (/user_code/node_modules/@google-cloud/storage/node_modules/@google-cloud/common/src/util.js:156:33) at Object.handleResp ... ... The full error is colossal, so I won't post it here in its entirety unless required.

Body:
It's possible the user that is trying to access the file only have access over the bucket but not over the file. Check the ACLs of both the bucket and the file in both projects and compare what you get:

myBucket.acl.get()
    .then(acls => console.log("Bucket ACLs:", acls));
myFile.acl.get()
    .then(acls => console.log("File ACLs:", acls));

You should see an output like this:

[ [ { entity: 'user-abenavides333@gmail.com', role: 'OWNER' },
    { entity: 'user-dwilches@gmail.com', role: 'OWNER' } ],
  { kind: 'storage#objectAccessControls',
    items: [ [Object], [Object] ] } ]

If there is no difference there, try the following more verbose versions of the same code:

myBucket.acl.get()
    .then(acls => console.log("Bucket ACLs:", JSON.stringify(acls, null, '\t')));
myFile.acl.get()
    .then(acls => console.log("File ACLs:", JSON.stringify(acls, null, '\t')));


问:
Escape Single Quote Characters when Importing to SQLite
I have a records.txt file like this:

```<code>INSERT INTO 'blogtitles' VALUES('Kelly's at house');
INSERT INTO 'blogtitles' VALUES('Nice catch!');
</code>```

When i try to import records.txt into the db: sqlite3 my.db < records.txt
It gives an error because of the first line.
I have many lines like this in the records.txt file.
I need a sed syntax that will escape all these single quotes within the strings. So there will not be any problem when importing.
I really need this :(
Thank you!

答:
That's what I often use :

```<code>cat myfile \
| sed -e "s/X/XX/g" \
| sed -e "s/^\([^']*\)'\([^']\)*'\([^']\)*'/\1XQ\2XQ\3XQ/" \
| sed -e "s/'\([^']*\)$/XQ\1" \
| sed -e "s/'/''/g" \
| sed -e "s/XQ/'/g" \
| sed -e "s/XX/X/g"
</code>```

The main advantage compared to Aaron's answer is that even if the begining of the line isn't always the same, it still works, although to the expense of longer code.

It's easy to remember :

Choose an 'escape character'

Escape it itself

Escape the occurrences of your character that you want to keep (but don't let the original character appear in the escaped sequence)

Transform the occurrences of your character

Unescape your character

Unescape the escape character

Or, in short :

Escape everything execpt what you need to transform

Transform

Unescape everything

OwnerDisplayName: Mehmet Güzerler

ContentLicense: CC BY-SA 2.5

Body:
I have a records.txt file like this:

INSERT INTO 'blogtitles' VALUES('Kelly's at house');
INSERT INTO 'blogtitles' VALUES('Nice catch!');

When i try to import records.txt into the db: sqlite3 my.db < records.txt
It gives an error because of the first line.
I have many lines like this in the records.txt file.
I need a sed syntax that will escape all these single quotes within the strings. So there will not be any problem when importing.
I really need this :(
Thank you!

Body:
That's what I often use :

cat myfile \
| sed -e "s/X/XX/g" \
| sed -e "s/^\([^']*\)'\([^']\)*'\([^']\)*'/\1XQ\2XQ\3XQ/" \
| sed -e "s/'\([^']*\)$/XQ\1" \
| sed -e "s/'/''/g" \
| sed -e "s/XQ/'/g" \
| sed -e "s/XX/X/g"

The main advantage compared to Aaron's answer is that even if the begining of the line isn't always the same, it still works, although to the expense of longer code.

It's easy to remember :

Choose an 'escape character'

Escape it itself

Escape the occurrences of your character that you want to keep (but don't let the original character appear in the escaped sequence)

Transform the occurrences of your character

Unescape your character

Unescape the escape character

Or, in short :

Escape everything execpt what you need to transform

Transform

Unescape everything


问:
Editing an array of strings in c
I'm writing code for a poker game and in my main function I have:

```<code>const char *suits[4] = { "Spades", "Clubs", "Hearts", "Diamonds" };
const char *faces[13] = { "Ace", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten", "Jack", "Queen", "King" };

int deck[4][13] = { 0 };

srand((unsigned)time(NULL));

char *hand[5] = { "\0" };

shuffle(deck);
deal(deck, faces, suits, hand);

for (int i = 0; i < 5; i++) {
    printf("%s", hand[i]);
}
</code>```

This is where my general problem is. hand wont print out the values given to it in deal, which are 5 cards.

shuffle() simply shuffles the deck, no errors there so I am not going to include it in this question.

deal() has the following code (ignore the curly-bracket/whitespace discrepancies, I'm still adjusting to the formatting of this site):

```<code>void deal(const int wDeck[][13], const char *wFace[], const char *wSuit[],
char *hand[]) {

int row = 0;    /* row number */
int column = 0; /*column number */
int card = 0;   /* card counter */

                /* deal 5 of the 52 cards */
for (card = 1; card <= 5; card++)
{
    /* loop through rows of wDeck */
    for (row = 0; row <= 3; row++)
    {
        /* loop through columns of wDeck for current row */
        for (column = 0; column <= 12; column++)
        {
            /* if slot contains current card, deal card */
            if (wDeck[row][column] == card)
            {
                char str1[10];
                strcpy(str1, wFace[column]);
                char str2[10];
                strcpy(str2, wSuit[row]);
                char str3[6] = " of ";
                char str[26] = "";
                strcat(str, str1);
                strcat(str, str3);
                strcat(str, str2);
                puts(str);

                hand[card - 1] = str;
                printf("%s\n", hand[card - 1]);
            }
         }
      }
   }
}
</code>```

The code in the if statement works just fine.
The problem arises in main() when I try to print the values given to hand, however in deal() the values in hand print fine. I assume that I am not passing hand into the function correctly, but no matter the different methods I've tried to get the program to run correctly, nothing works.

An example of the program as is can be seen here:
Example of program running

答:
in you deal() function:

```<code>hand[card - 1] = str;
</code>```

str is local character array whose address will get invalidated once you return from deal()
right way to do it will be allocate memory to each element(max number of elements being 5) of hand, then copy value of str using strcpy into element of hand

e.g.

```<code> hand[card - 1] = malloc(26);
 strcpy(hand[card - 1],str);
</code>```

Title: Editing an array of strings in c

Body:
I'm writing code for a poker game and in my main function I have:

const char *suits[4] = { "Spades", "Clubs", "Hearts", "Diamonds" };
const char *faces[13] = { "Ace", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten", "Jack", "Queen", "King" };

int deck[4][13] = { 0 };

srand((unsigned)time(NULL));

char *hand[5] = { "\0" };

shuffle(deck);
deal(deck, faces, suits, hand);

for (int i = 0; i < 5; i++) {
    printf("%s", hand[i]);
}

This is where my general problem is. hand wont print out the values given to it in deal, which are 5 cards.

shuffle() simply shuffles the deck, no errors there so I am not going to include it in this question.

deal() has the following code (ignore the curly-bracket/whitespace discrepancies, I'm still adjusting to the formatting of this site):

void deal(const int wDeck[][13], const char *wFace[], const char *wSuit[],
char *hand[]) {

int row = 0;    /* row number */
int column = 0; /*column number */
int card = 0;   /* card counter */

                /* deal 5 of the 52 cards */
for (card = 1; card <= 5; card++)
{
    /* loop through rows of wDeck */
    for (row = 0; row <= 3; row++)
    {
        /* loop through columns of wDeck for current row */
        for (column = 0; column <= 12; column++)
        {
            /* if slot contains current card, deal card */
            if (wDeck[row][column] == card)
            {
                char str1[10];
                strcpy(str1, wFace[column]);
                char str2[10];
                strcpy(str2, wSuit[row]);
                char str3[6] = " of ";
                char str[26] = "";
                strcat(str, str1);
                strcat(str, str3);
                strcat(str, str2);
                puts(str);

                hand[card - 1] = str;
                printf("%s\n", hand[card - 1]);
            }
         }
      }
   }
}

The code in the if statement works just fine.
The problem arises in main() when I try to print the values given to hand, however in deal() the values in hand print fine. I assume that I am not passing hand into the function correctly, but no matter the different methods I've tried to get the program to run correctly, nothing works.

An example of the program as is can be seen here:
Example of program running

Body:
in you deal() function:

hand[card - 1] = str;

str is local character array whose address will get invalidated once you return from deal()
right way to do it will be allocate memory to each element(max number of elements being 5) of hand, then copy value of str using strcpy into element of hand

e.g.

 hand[card - 1] = malloc(26);
 strcpy(hand[card - 1],str);


问:
C UART not working all the time
I'm having an issue connecting a serial device to an embedded device I'm writing code for.

The device I am writing has two serial ports, an incoming from my laptop, and an outgoing to an external device.

When I connect both terminals to my laptop and view the data, I get exactly the data I am expecting.

When I connect my laptop to the external device directly, I am getting exactly what I expect, and a response.

When I connect the laptop and the external device to the embedded device I am working on, the laptop sends data to it, it receives it, it passes it on to the external device.  This works as expected.

However, the external device doesn't send back the response.

If I send data to the external device from the embedded device, each new message I send allows it to send the original reply.

I know the first message got through correctly because the external device whirrs to live, and I know when it is sending the response by running and logic analyser on the tx/rx comms and viewing the traffic.

I considered that the embedded device is holding the rx line and preventing its transmission, but I don't see how that possible in the code. Also if that is the case it shouldn't work when I plug both lines into my laptop.

I also considered the DTR was not set high, but checked this and it appears to be set high.

Does anyone know a reason which would prevent a device from responding?

Note: When I say Serial Ports I am referring to the UART when referring to the embedded device. All device use a DB9 connector running RS232.

Edit: Operating System on laptop is Windows 10.  Embedded device is a Atmega324p.

Edit 2:  Did some more testing.  It appears that it sometimes work and sometimes doesn't.

I have added an image which show a almost perfect signal of the response.

The blue section is a gap in the signal that shouldn't be there.

答:
Ended up finding a solution.

The RTS line was held via the embedded device at 1.2v, while the Pc was holding it at 5.2v.

Pulling the RTS line up to 5v fixed the issue.

Title: C UART not working all the time


问:
Output 'NaN' Incrementing state value by using ReactJS
In React I am trying to make a button increment a value stored in state. However using the code below function. When I click "minusbutton" or "plusbutton" and the output is 'NaN' when using buttonplus_quantity and buttonminus_quantity.

Here is my code:

```<code>class EnterOrder extends Component {

    constructor(props) {
      super(props)
      this.buttonplus_quantity = this.buttonplus_quantity.bind(this);
      this.buttonminus_quantity = this.buttonminus_quantity.bind(this);

      this.state= {
          num_quantity :0
      }

      buttonplus_quantity=()=>{
      this.setState({num_quantity: this.state.num_quantity +1});
      console.log("a");
    }

    buttonminus_quantity=()=>{
      this.setState({num_quantity: this.state.num_quantity -1});
      console.log("b");
    }
}
</code>```

And the Render():

```<code> render(){
  let {num_quantity} = this.state;
   return(
    <Button onClick={this.buttonminus_quantity} name="minus" id="minus"
    value="-">-</Button>
    <p id='num'>{this.state.num_quantity}</p>
    <Button  onClick={this.buttonplus_quantity} name="plus" id="plus"
    value="+">+</Button>
    );
}
</code>```

And the output when I click is 'NaN' like this picture below:

What I am doing wrong? Thank you guys so much for helping.

答:
You can't rebind arrow functions. I think the problem is with your binding the functions. Here is the working pen with your code: https://codepen.io/danegit/pen/EbvopX?editors=0010

Also use functional setState if you are relying on previous state to update next state, as dhilt pointed out.

EDIT Also you can only render just one child inside render the code in your question wouldn't run at all. Always paste the full code if possible.

Body:
In React I am trying to make a button increment a value stored in state. However using the code below function. When I click "minusbutton" or "plusbutton" and the output is 'NaN' when using buttonplus_quantity and buttonminus_quantity.

Here is my code:

class EnterOrder extends Component {

    constructor(props) {
      super(props)
      this.buttonplus_quantity = this.buttonplus_quantity.bind(this);
      this.buttonminus_quantity = this.buttonminus_quantity.bind(this);

      this.state= {
          num_quantity :0
      }

      buttonplus_quantity=()=>{
      this.setState({num_quantity: this.state.num_quantity +1});
      console.log("a");
    }

    buttonminus_quantity=()=>{
      this.setState({num_quantity: this.state.num_quantity -1});
      console.log("b");
    }
}

And the Render():

 render(){
  let {num_quantity} = this.state;
   return(
    <Button onClick={this.buttonminus_quantity} name="minus" id="minus"
    value="-">-</Button>

{this.state.num_quantity}

    <Button  onClick={this.buttonplus_quantity} name="plus" id="plus"
    value="+">+</Button>
    );
}

And the output when I click is 'NaN' like this picture below:

What I am doing wrong? Thank you guys so much for helping.


问:
Cannot install tflearn in python 3
I have tensorflow 1.11.9 for python 3 and am trying to install tflearn.

I tried installation using:

"pip3 install git+https://github.com/tflearn/tflearn.git"

"pip3 install tflearn"

"pip install git+https://github.com/tflearn/tflearn.git"

"pip install git+https://github.com/tflearn/tflearn.git"

Nothing seems to work. pip install is installing a tflearn version for python 2 (I have python2.7 and 3.4 on Ubuntu 14.04), whereas pip3 is claiming that installation is successful, but I get an error saying

"No module named 'tensorflow.contrib.rnn.python.ops.core_rnn'".

Can anyone suggest what am I doing wrong? I would be happy to provide any further information that might be required. Thanks in advance.

答:
I figured out that I was installing tensorflow using

sudo pip3 install --upgrade tfBinaryURL,

where, tfBinaryURL identifies the proper URL of the TensorFlow Python package. Doing the tensorflow installation using

pip3 install tensorflow

and then installling tflearn using

pip3 install git+github.com/tflearn/tflearn.git

solves my problem.

Title: Cannot install tflearn in python 3


问:
Can PHP trigger an event on a remote Windows Server
Is there a way for PHP to send a signal to a Windows Server to run a script?

I am writing a web application which generates database entries that are later synced by a program on a remote Windows Server.  PHP & mySQL are running on AWS.
The application on the windows server syncs the mySql database with Quickbooks.  Ideally I would like to send a signal from PHP so that if PHP has updated the database, letting the remote Windows server know which script to run to in order to initiate the sync program.  I would need to be pointed in the right direction both on the PHP commands as well as how to setup the listening service on Windows.

I was thinking if I could get Windows to listen on a specific port for a short XML file, PHP could send a password and entity ID number to identify which script to run.

Any suggestions?

Thanks!

答: You can use php on both end. Just install php server on windows, then when request happened execute a windows command. Php can do that. </p>


问:
C++ loop stack allocation
While doing an assignment for a course and learning C++ while doing it, I was reading up on when to use stack allocation and dynamic allocation. I'm aware that in a lot of cases it is easier and better to use stack allocation. But there is a simple situation I'm puzzeled about.

Lets say you have a for loop:

```<code>for(int i = 0; i < 10; i++)
{
   MyObject obj(file);
   obj.doSomething();
}
</code>```

Now the problem is that if the Object contains state, it keeps it state (stays the same object) while iterating through the iterations from 1 til 10. Maybe coming from a Java/C# background gets me on the wrong path. But I only see two ways of solving this:

Using dynamic memory.

Not giving file to the constructor but instead to the method doSomething(file) but this isn't very nice if you have more than one method manipulating the file object e.g. doSomethingElse(file).

So what do you guys do in such a situation, or do you never get yourself in such a situation at all?

Update:
Turns out i misunderstood and it is working as expected. Check the awnsers below! Thanks everyone

答:
In this code, obj is created (its constructor is called) each time through the loop when the line containing its declaration is reached and it is destroyed (its destructor is called) at the end of each loop iteration.

If you want it to be created once and have it save its state over loop iterations, declare it outside of the loop:

```<code>MyObject obj(file);
for (int i = 0; i < 10; i++)
{
    obj.doSomething();
}
</code>```

If you need to have the same object used across multiple iterations like this and you need to change the state of the object during iteration (e.g. by changing the file), you will need to have some member function that allows you to change that state (either a dedicated member function like useThisFile(file) or an additional parameter to the member functions being used like doSomething(file)).

Title: C++ loop stack allocation

Body:
While doing an assignment for a course and learning C++ while doing it, I was reading up on when to use stack allocation and dynamic allocation. I'm aware that in a lot of cases it is easier and better to use stack allocation. But there is a simple situation I'm puzzeled about.

Lets say you have a for loop:

for(int i = 0; i < 10; i++)
{
   MyObject obj(file);
   obj.doSomething();
}

Now the problem is that if the Object contains state, it keeps it state (stays the same object) while iterating through the iterations from 1 til 10. Maybe coming from a Java/C# background gets me on the wrong path. But I only see two ways of solving this:

Using dynamic memory.

Not giving file to the constructor but instead to the method doSomething(file) but this isn't very nice if you have more than one method manipulating the file object e.g. doSomethingElse(file).

So what do you guys do in such a situation, or do you never get yourself in such a situation at all?

Update:
Turns out i misunderstood and it is working as expected. Check the awnsers below! Thanks everyone

Body:
In this code, obj is created (its constructor is called) each time through the loop when the line containing its declaration is reached and it is destroyed (its destructor is called) at the end of each loop iteration.

If you want it to be created once and have it save its state over loop iterations, declare it outside of the loop:

MyObject obj(file);
for (int i = 0; i < 10; i++)
{
    obj.doSomething();
}

If you need to have the same object used across multiple iterations like this and you need to change the state of the object during iteration (e.g. by changing the file), you will need to have some member function that allows you to change that state (either a dedicated member function like useThisFile(file) or an additional parameter to the member functions being used like doSomething(file)).


问:
Is Flux' Dispatcher over-engineering since Javascript is single-threaded?
I was looking at how Flux's Dispatcher.js is implemented, which raised some questions in light of my understanding that javascript is single threaded:

Will isDispatching() ever return anything other than false? The _isDispatching flag is set in the beginning of dispatch() and then set back to false right before the end of the method. If there is only one thread executing the Dispatcher, what else can call isDispatching()?

Similarly, aren't _isPending and _isHandled booleans on each callback superfluous?

答:
They're there as checks to prevent a callback from immediately attempting to dispatch again (causing infinite loops.)

Try to picture what would happen if one of the listeners called dispatch while the previous dispatch was still looping through this._callbacks


问:
Return from inside an observable
I'm think fundamentally i'm doing something wrong. I'm trying to find a single entity by pulling it from filtered list, if there isn't an entity there I need to create one.

I feel like this function is wrong because I should be returning an observable but instead returning nothing

```<code>getOrCreateNew(receiverId: number) : Observable<Conversation> {
    var userId = this.identity.userInfo.id;

    //TODO: you should be using an expression here, and having a builder for generating your
    //filters in case you want to switch them in the future
    var employerFilter = new PropertyFilterNode("EmployerUserId", FilterCondition.Equal, receiverId.toString());
    var employeeFilter = new PropertyFilterNode("EmployeeUserId", FilterCondition.Equal, userId.toString());
    let conversationFilter = new BinaryFilterNode(employerFilter, employeeFilter, Combiner.Or);

    this.getList(conversationFilter).subscribe(entities => {
        if (entities == null || entities.length == 0) {
            let conversation: Conversation;
            conversation.employerUserId = receiverId;
            conversation.employeeUserId = userId;
            return this.create(conversation);
        }
        else {
            let entity = entities[0];
            return Observable.of(entity); //.Return(entity)
        }
    });

    return null;
}
</code>```

How can I return an observable which is return from inside subscribe?

答:
Place the return before this.getList also :

```<code>return this.getList(conversationFilter).subscribe(entities => {
</code>```

Title: Return from inside an observable

Body:
I'm think fundamentally i'm doing something wrong. I'm trying to find a single entity by pulling it from filtered list, if there isn't an entity there I need to create one.

I feel like this function is wrong because I should be returning an observable but instead returning nothing

getOrCreateNew(receiverId: number) : Observable<Conversation> {
    var userId = this.identity.userInfo.id;

    //TODO: you should be using an expression here, and having a builder for generating your
    //filters in case you want to switch them in the future
    var employerFilter = new PropertyFilterNode("EmployerUserId", FilterCondition.Equal, receiverId.toString());
    var employeeFilter = new PropertyFilterNode("EmployeeUserId", FilterCondition.Equal, userId.toString());
    let conversationFilter = new BinaryFilterNode(employerFilter, employeeFilter, Combiner.Or);

    this.getList(conversationFilter).subscribe(entities => {
        if (entities == null || entities.length == 0) {
            let conversation: Conversation;
            conversation.employerUserId = receiverId;
            conversation.employeeUserId = userId;
            return this.create(conversation);
        }
        else {
            let entity = entities[0];
            return Observable.of(entity); //.Return(entity)
        }
    });

    return null;
}

How can I return an observable which is return from inside subscribe?

Body:
Place the return before this.getList also :

return this.getList(conversationFilter).subscribe(entities => {


答:
```<code>$ awk -v dq='"' '{for(i=1;i<=NF;i++) if($i~/^0/ && $i!~/[./]/) $i=dq $i dq} 1' file
1234 "012345"
0.000
01/02/03
"01234"
"05554567"
"0qwertyu"
"0099"
"0000" "000012"
1800.000000
"099000"
"0123456789"
</code>```

this won't preserve the input spacing though, if input is tab separated, set FS/OFS accordingly.. awk -v dq='"' 'BEGIN{FS=OFS="\t"} {for(i=1;i<=NF;i++) if($i~/^0/ && $i!~/[./]/) $i=dq $i dq} 1'

-v dq='"' variable to store a double quote

for(i=1;i<=NF;i++) iterate over all input fields

if($i~/^0/ && $i!~/[./]/) if any field starts with 0 and doesn't have . or /

$i=dq $i dq surround that field with double quotes

1 print the input record, including any changes made to the fields

To preserve spacing

```<code>$ perl -lpe 's#(^|\h)\K0[^./\h]+(?=\h|$)#"$&"#g' file
1234    "012345"
0.000
01/02/03
"01234"
"05554567"
"0qwertyu"
"0099"
"0000"  "000012"
1800.000000
"099000"
"0123456789"
</code>```

Title: Need to replace all the strings staring with 0 (except having / and .) in a text file with same string in double quotes

Body:
    awk '{for(i=1;i<=NF;i++){if($i~/^0[a-z,0-9][a-z,0-9]/){print $i}}}' test1 > test3

 doWork()

 { rm /tmp/test1 && awk '{sub(/'$I'/, "\"'$I'\"", $0); print}' >test1;} < test1

 for I in `cat /tmp/test3`
 do doWork;
 done;

Input text file:

/tmp # cat test1 1234      012345
  0.000 01/02/03 01234 05554567 0qwertyu 0099 0000           000012
  1800.000000 099000 0123456789

Current Output:

1234      ""01234"5"
  0.000 01/02/03 "01234" "05554567" "0qwertyu" "0099" "0000"           "000012"
  1800."0000"00 "099000" ""01234"5"6789

Expected output:

1234      "012345"
  0.000 01/02/03 "01234" "05554567" "0qwertyu" 0099 "0000"           "000012"
  1800.000000 "099000" "0123456789"

Body:
$ awk -v dq='"' '{for(i=1;i<=NF;i++) if($i~/^0/ && $i!~/[./]/) $i=dq $i dq} 1' file
1234 "012345"
0.000
01/02/03
"01234"
"05554567"
"0qwertyu"
"0099"
"0000" "000012"
1800.000000
"099000"
"0123456789"

this won't preserve the input spacing though, if input is tab separated, set FS/OFS accordingly.. awk -v dq='"' 'BEGIN{FS=OFS="\t"} {for(i=1;i<=NF;i++) if($i~/^0/ && $i!~/[./]/) $i=dq $i dq} 1'

-v dq='"' variable to store a double quote

for(i=1;i<=NF;i++) iterate over all input fields

if($i~/^0/ && $i!~/[./]/) if any field starts with 0 and doesn't have . or /

$i=dq $i dq surround that field with double quotes

1 print the input record, including any changes made to the fields

To preserve spacing

$ perl -lpe 's#(^|\h)\K0[^./\h]+(?=\h|$)#"$&"#g' file
1234    "012345"
0.000
01/02/03
"01234"
"05554567"
"0qwertyu"
"0099"
"0000"  "000012"
1800.000000
"099000"
"0123456789"


问:
DNN : Change Portals/0 to Portals/<random> for security measures
We want to make a DNN 9 more secure.

Is it possible and feasible to change the default "portals/0" to "portals/

Would the correct way be to update the Folders.StorageLocation?

What problems would I run into?

答:
It's likely to be cumbersome.

What I would do is export the portal and it's contents, and then create a new portal with the export as a template.  You can, I think, also specifiy a name for the root portal.

You may have issues with links in your content that refer to the old root.  You may also have problems if you have modules that don't export/import content.  So, you'll have to fix that stuff manually.  There are modules available to to search/replace within a portal to fix link issues.  If you are using portal level skins, you'll need to move those early on -- I think before touching anything that will alter settings.

If you aren't sure what you're doing, ask for some help.

Oh, and you'll probably want to make the portal files all "secure" do obfuscate directory names, some of which may refer to the portal root.  And don't put files in the root directory either.