问:
Android Kotlin : TextView.text not working as expected
I have an app that makes user sign in with Firebase if they are not already signed in. If user signs in their user profile info shows properly. Upon closing the app and reopening the user name and email does not set and goes to my defaulted text. But if I sign out and back in it will show. I feel like it has something to do with updating ui but stuck.

I can post code after my lunch break is over if needed

update with code

This is the relevent code in MainActivity this is where I check if user is logged in if so allow them to go from there if not to start signin activity.

```<code>class MainActivity : AppCompatActivity(), NavigationView.OnNavigationItemSelectedListener {

val TAG = "MainActivity"

var mAuth: FirebaseAuth? = null
var mUser: FirebaseUser? = null
var userEmailTV: TextView? = null
var userDispNameTV: TextView? = null
val RC_SIGN_IN = 123

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_main)
    setSupportActionBar(toolbar)

    val toggle = ActionBarDrawerToggle(
            this, drawer_layout, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close)
    drawer_layout.addDrawerListener(toggle)
    toggle.syncState()
    nav_view.setNavigationItemSelectedListener(this)

}

 override fun onStart() {
    super.onStart()

    mAuth = FirebaseAuth.getInstance()
    mUser = mAuth?.currentUser

    if (mUser != null) {

        userEmailTV = findViewById<View>(R.id.userEmail) as TextView?
        userEmailTV?.text = mUser?.email
        userDispNameTV = findViewById<View>(R.id.userName) as TextView?
        userDispNameTV?.text = mUser?.displayName

        Log.i(TAG, "User Display Name : ${mUser?.displayName}")
        Log.i(TAG, "Users Email :  ${mUser?.email}")

    } else {
        startActivityForResult(
                // Get an instance of AuthUI based on the default app
                AuthUI.getInstance().createSignInIntentBuilder().build(),
                RC_SIGN_IN)
    }

}
</code>```

This is the layout info that holds the user profile info inside the navigation drawer

```<code> <TextView
    android:id="@+id/userName"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:paddingTop="@dimen/nav_header_vertical_spacing"
    android:textAppearance="@style/TextAppearance.AppCompat.Body1"
    android:text="Username"/>

<TextView
    android:id="@+id/userEmail"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="youremail@something.com"/>
</code>```

答: Are you sure that "findView" succeeded? Try calling it on navigation header view receiver</p>

Body:
I have an app that makes user sign in with Firebase if they are not already signed in. If user signs in their user profile info shows properly. Upon closing the app and reopening the user name and email does not set and goes to my defaulted text. But if I sign out and back in it will show. I feel like it has something to do with updating ui but stuck.

I can post code after my lunch break is over if needed

update with code

This is the relevent code in MainActivity this is where I check if user is logged in if so allow them to go from there if not to start signin activity.

class MainActivity : AppCompatActivity(), NavigationView.OnNavigationItemSelectedListener {

val TAG = "MainActivity"

var mAuth: FirebaseAuth? = null
var mUser: FirebaseUser? = null
var userEmailTV: TextView? = null
var userDispNameTV: TextView? = null
val RC_SIGN_IN = 123

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_main)
    setSupportActionBar(toolbar)

    val toggle = ActionBarDrawerToggle(
            this, drawer_layout, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close)
    drawer_layout.addDrawerListener(toggle)
    toggle.syncState()
    nav_view.setNavigationItemSelectedListener(this)

}

 override fun onStart() {
    super.onStart()

    mAuth = FirebaseAuth.getInstance()
    mUser = mAuth?.currentUser

    if (mUser != null) {

        userEmailTV = findViewById<View>(R.id.userEmail) as TextView?
        userEmailTV?.text = mUser?.email
        userDispNameTV = findViewById<View>(R.id.userName) as TextView?
        userDispNameTV?.text = mUser?.displayName

        Log.i(TAG, "User Display Name : ${mUser?.displayName}")
        Log.i(TAG, "Users Email :  ${mUser?.email}")

    } else {
        startActivityForResult(
                // Get an instance of AuthUI based on the default app
                AuthUI.getInstance().createSignInIntentBuilder().build(),
                RC_SIGN_IN)
    }

}

This is the layout info that holds the user profile info inside the navigation drawer

 <TextView
    android:id="@+id/userName"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:paddingTop="@dimen/nav_header_vertical_spacing"
    android:textAppearance="@style/TextAppearance.AppCompat.Body1"
    android:text="Username"/>

<TextView
    android:id="@+id/userEmail"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="youremail@something.com"/>


来源: stackexchange

问:
no data in firebase crashlytics reports after 1 day
My iOS app is running firebase reports since several weeks.
I added crashlytics 2 days ago by following the official steps:
https://firebase.google.com/docs/crashlytics/get-started?authuser=0

in fact, It seems all I had to do was to install these pods:

```<code>pod 'Fabric', '~> 1.7.2'
pod 'Crashlytics', '~> 3.9.3'
</code>```

I also added "DWARF with dSYM File" for the debug information format on both debug and release build settings

Now when I start the app I can see in the log :

```<code>[Crashlytics] Version 3.9.3 (128)
</code>```

Then I forced a crash from an app launched manually (not with the debugger), and I can see the following in the logs after I restart the app from xcode:

[Crashlytics:Crash:Reports] Packaged report with id '9aeb11f6423b4f11b95a0f3263fc7510' for submission

nothing else regarding crashlytics

my question : Why I can't see any data in the firebase crashlytics reports?

答:
FYI I had a similar experience, except that my errors started showing up within a few hours. Here are the two sets of instructions I followed, the second of which is actually necessary even though it isn't included in "get started":

https://firebase.google.com/docs/crashlytics/get-started

https://firebase.google.com/docs/crashlytics/force-a-crash

The steps I followed, in case you want to go down the list and make sure you didn't miss anything:

Add pods to podfile.

pod install.

Restart xcode.

Add build step.

Change build settings to DWARF with dSYM File.

Add a button that calls Crashlytics.sharedInstance().crash().

Run the app on simulator, stop the app, restart by clicking it, tap the crash button. Restart the app.

Instead of Crashlytics.sharedInstance().crash(), call:

let x: Int? = nil

let y = 5 + x!

Run, stop, click, tap button, crash. Restart.

I'd advise looking at system logs, but it looks like you've already done that. I hope some part of this gives you an idea that helps.

ContentLicense: CC BY-SA 3.0

Body:
My iOS app is running firebase reports since several weeks.
I added crashlytics 2 days ago by following the official steps:
https://firebase.google.com/docs/crashlytics/get-started?authuser=0

in fact, It seems all I had to do was to install these pods:

pod 'Fabric', '~> 1.7.2'
pod 'Crashlytics', '~> 3.9.3'

I also added "DWARF with dSYM File" for the debug information format on both debug and release build settings

Now when I start the app I can see in the log :

[Crashlytics] Version 3.9.3 (128)

Then I forced a crash from an app launched manually (not with the debugger), and I can see the following in the logs after I restart the app from xcode:

[Crashlytics:Crash:Reports] Packaged report with id '9aeb11f6423b4f11b95a0f3263fc7510' for submission

nothing else regarding crashlytics

my question : Why I can't see any data in the firebase crashlytics reports?


问:
How do I live stream game content to a website using Node and Java?
I am currently using Socket.io to sort of "stream" video from a Java game application to a ReactJS website. It's pretty slow, and a little janky, but it works.

The programs work by taking a screenshot of the game with Java, compressing it to JPEG, then sending the compressed, Base64 string over Socket.io to the server. The server then sends this Base64 string to the web client (ReactJS), which then renders the Base64 string as an image using CSS.

This method works. I can control the framerate (to an extent...it runs my CPU through the roof if I use 60 FPS or higher), and I can definitely control the compression of the JPEG (the quality of the image).

It does have its limitations though, and I'm still convinced there's a better way of going about this. I've looked on google for a way to stream video from one application to another, but I haven't found one.

What is the best approach to streaming a game, in a Java client, to a website, in ReactJS?

答:
This is not a way to go!

Streaming codecs are much more effective than JPEG screenshots. For example, any movie compression alghorithm adjusts itself based on available bandwidth and does not keep all the frames. In your case you're rendering all the frames for your game, which kills your machine performance (JPEG rendering is much more power-hungry than rendering a proper video).

Another thing - you should just stream the content as it is, by sending stream of data instead of using base-64, providing a constant stream of video footage.

So, final solution would look somewhat like that:

Capture the view, using FFMPEG library

Create stream out of captured footage

Expose stream via socket

Get binary output on the other side of the network

Probably, just use HTML5 player that should support all the popular encoding/streaming formats.

These links may be helpful to start with:

https://github.com/yev/java-ffmpeg-pipe

https://github.com/vbence/stream-m

http://www.xuggle.com/xuggler/

http://fmj-sf.net/ffmpeg-java/getting_started.php

And something in this thread: Stream video in Java


问:
How to search for functions in module?
I want to have a search function like a man page inside a Python module.

Is there a built-in or module function to search a string/wildcard char in function name/class name/object name or function of class?

e.g. find(get_*)?

This would find all get_* functions, such as get_height, get_weight, get_area, get_volume as well as square.get_area,rectange.get_area
or have a find(get?int) to find get_int, etc.

I can have a list in help(module) but there is too much clutter and no search function I can find.
If not, how can I write a function to do the same?

答:
So... From what I can glean from your post, you want to be able to find and return a list of all the functions within your module that matches a given pattern. Sounds to me like a job for re!
Here's my python.

```<code>import re
def find(the_module,regex=''):
  match = re.compile(regex)
  matched_values = []
  for i in dir(the_module):
    if match.search(i):
      matched_values.append(i)
  return matched_values
</code>```

Title: How to search for functions in module?

Body:
So... From what I can glean from your post, you want to be able to find and return a list of all the functions within your module that matches a given pattern. Sounds to me like a job for re!
Here's my python.

import re
def find(the_module,regex=''):
  match = re.compile(regex)
  matched_values = []
  for i in dir(the_module):
    if match.search(i):
      matched_values.append(i)
  return matched_values


问:
ExpressionChangedAfterItHasBeenCheckedError cause
I have the follow design:

```<code>Parent
+ Child 1
  + Child 2
</code>```

Child 2 contains and input field, the user hits ENTER and it emits an event.  Child 1 intercepts it and emits an execute event which is intercepted by the Parent.  The Parent executes a search and sends the results back to Child 1 via an Input().

In one scenario when the user navigates to the Parent with a reload=Y flag the search is run automatically based on the previously saved criteria. I do this in ngOnInit by checking the route params reload=Y and then emitting the same execute event, it goes to the parent and the results come back via Input(), this is working however I also get this error in the console -

ExpressionChangedAfterItHasBeenCheckedError: Expression has changed after it was checked. Previous value: 'undefined'. Current value: '[object Object]'.

I followed this article:
https://blog.angularindepth.com/everything-you-need-to-know-about-the-expressionchangedafterithasbeencheckederror-error-e3fd9ce7dbb4

and used a setTimeout() as described and now the error is gone.  What exactly happened here?

What exactly is setTimeout doing. The official explanation is "The setTimeout function schedules a "macrotask" which will be executed in the following VM turn".

So setTimetout delays the execution of the defined function until the next change detection cycle?  What is meant by "next VM turn"?

答:
By using the SetTimeout you’re basically branching part of your flow into a new change detection cycle. The one that will happen after completing the task.

The error you are seeing is basically a defence mechanism from Angular to prevent multiple sources updating the same property several times in the same change detection cycle. If this was allowed it would be really tricky to figure out the final value displayed and who produced it.

That’s the reason you no longer see the error, because the multiple changes will no longer be done on the same change detection cycle. You are taking ownership of splitting them into different timings so Angular is fine with that

Body:
I have the follow design:

Parent
+ Child 1
  + Child 2

Child 2 contains and input field, the user hits ENTER and it emits an event.  Child 1 intercepts it and emits an execute event which is intercepted by the Parent.  The Parent executes a search and sends the results back to Child 1 via an Input().

In one scenario when the user navigates to the Parent with a reload=Y flag the search is run automatically based on the previously saved criteria. I do this in ngOnInit by checking the route params reload=Y and then emitting the same execute event, it goes to the parent and the results come back via Input(), this is working however I also get this error in the console -

ExpressionChangedAfterItHasBeenCheckedError: Expression has changed after it was checked. Previous value: 'undefined'. Current value: '[object Object]'.

I followed this article:
https://blog.angularindepth.com/everything-you-need-to-know-about-the-expressionchangedafterithasbeencheckederror-error-e3fd9ce7dbb4

and used a setTimeout() as described and now the error is gone.  What exactly happened here?

What exactly is setTimeout doing. The official explanation is "The setTimeout function schedules a "macrotask" which will be executed in the following VM turn".

So setTimetout delays the execution of the defined function until the next change detection cycle?  What is meant by "next VM turn"?


问:
Angular 4 not loading component
I'm trying to use Angular Routes in Angular 4 app, but the app is not able to load the component matching the requested route:

Here is app-routing.module.ts:

```<code>import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { DashboardComponent } from './dashboard/dashboard.component';

const routes: Routes = [
  { path: 'dashboard', component: DashboardComponent },
  { path: '', redirectTo: '/dashboard', pathMatch: 'full' },
];

@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule]
})
export class AppRoutingModule { }
</code>```

app.module.ts looks like this:

```<code>import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';

import { AppComponent } from './app.component';
import { DashboardComponent } from './dashboard/dashboard.component';
import { AppRoutingModule } from './app-routing.module';

@NgModule({
  declarations: [
    AppComponent,
    DashboardComponent,
  ],
  imports: [
    BrowserModule,
    AppRoutingModule,
  ],
  providers: [ ],
  bootstrap: [ AppComponent ]
})
export class AppModule { }
</code>```

app.component.html:

```<code><h1>
    Welcome to {{title}}!
</h1>
<router-outlet></router-outlet>
</code>```

My dashboard.component.html :

```<code><p>dashboard works!</p>
</code>```

I'm trying to figure out whats wrong, also looked at the Angular 4 Routing tutorial. Please help.

答:
well, i got the wrong thing

```<code>exports: [RouterModule]
</code>```

you are exporting a core module from @angular/router so your AppModule get extended by  RouterModule, not your route and instead of creating the whole module just export the const
like

```<code>export const routing: ModuleWithProviders = RouterModule.forRoot(routes);
</code>```

and import routing in your appmodule

Title: Angular 4 not loading component

Body:
I'm trying to use Angular Routes in Angular 4 app, but the app is not able to load the component matching the requested route:

Here is app-routing.module.ts:

import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { DashboardComponent } from './dashboard/dashboard.component';

const routes: Routes = [
  { path: 'dashboard', component: DashboardComponent },
  { path: '', redirectTo: '/dashboard', pathMatch: 'full' },
];

@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule]
})
export class AppRoutingModule { }

app.module.ts looks like this:

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';

import { AppComponent } from './app.component';
import { DashboardComponent } from './dashboard/dashboard.component';
import { AppRoutingModule } from './app-routing.module';

@NgModule({
  declarations: [
    AppComponent,
    DashboardComponent,
  ],
  imports: [
    BrowserModule,
    AppRoutingModule,
  ],
  providers: [ ],
  bootstrap: [ AppComponent ]
})
export class AppModule { }

app.component.html:

    Welcome to {{title}}!

<router-outlet></router-outlet>

My dashboard.component.html :

dashboard works!

I'm trying to figure out whats wrong, also looked at the Angular 4 Routing tutorial. Please help.

Body:
well, i got the wrong thing

exports: [RouterModule]

you are exporting a core module from @angular/router so your AppModule get extended by  RouterModule, not your route and instead of creating the whole module just export the const
like

export const routing: ModuleWithProviders = RouterModule.forRoot(routes);

and import routing in your appmodule


问:
Difference between inheritance and creating new class
What is the difference between these two:

```<code>class Machine {
    public int x = 2;
}

class Car {
    public void start(Machine myMachine) {
         myMachine.x = 10;
    }
}
</code>```

And:

```<code>class Machine {
    public int x = 2;
}

class Car extends Machine {
    public void start() {
        super.x = 10;
    }
}
</code>```

In the first example, I'm creating a new kind of object with the Car class, and I can use variable x from the Machine class.

In the second example I'm inheriting from the Machine class to the Car class, so I can use variables from Machine in Car.

But I don't know when should I use first the one instead of the second one, which is better, and so on.

Could someone explain the difference?

答:
In the first example you say "I want Car to assign a value of 10 to some Machine's (Car isn't really connected with that Machine, it could be "Gate", "Garage" or other classes that Car can cooperate with Car, but they are not in the relation "Car is a..." ) variable x"

In the second one you say "Car is a machine and I want it to be able to change value of it's own x variable to 10". (You could say "I want my car to start its own engine, for example).

I know that in the first example I'm creating kind of new object (am I right?) - it's not about creating new Machine reference by passing it as an argument. You rather say that you want instance of Car class to be able to change x value of the one specific instance of Machine class. Not to all Machines, just to the one you pass as an argument to the start() method. Example: myFerrari.start(gateThree)
Car has a functionality to open the gate when you want it to, but Car is not a Gate.

But I don't know when should I use first one and when the second one, which is better, and so on. In the second example you say Car is a Machine - so it is able to perform all actions that Machines are able to perform and it also is able to perform some actions specific only to Cars and not to all Machines. To use inheritance you should be sure that you can say Car is a Machine.

ContentLicense: CC BY-SA 4.0

Body:
What is the difference between these two:

class Machine {
    public int x = 2;
}

class Car {
    public void start(Machine myMachine) {
         myMachine.x = 10;
    }
}

And:

class Machine {
    public int x = 2;
}

class Car extends Machine {
    public void start() {
        super.x = 10;
    }
}

In the first example, I'm creating a new kind of object with the Car class, and I can use variable x from the Machine class.

In the second example I'm inheriting from the Machine class to the Car class, so I can use variables from Machine in Car.

But I don't know when should I use first the one instead of the second one, which is better, and so on.

Could someone explain the difference?


问:
Local variable array of ints defaults to zero
Why is it that when an array of 'ints' is made as a local variable they default to zero?

```<code>       public static void main(String [] args) {
           int []arrayInts = new int[5];
           for(int i: arrayInts)
                System.out.println(i);
           //Prints out zeros
       }
</code>```

While if an 'int' variable is declared as a local variable it does not get initialized.

```<code>       public static void main(String [] args) {
           int a;
            System.out.println(a);
           //Compilation error: The local variable a may not have been initialized
       }
</code>```

答:
These two examples aren't comparable.

In the first one, you are actively initializing your array.  The default value for an array of ints is 0.

In the second example, you've not initialized the variable a, either explicitly or implicitly, and you're attempting to make use of it.  Java will complain about this action.

Body:
Why is it that when an array of 'ints' is made as a local variable they default to zero?

       public static void main(String [] args) {
           int []arrayInts = new int[5];
           for(int i: arrayInts)
                System.out.println(i);
           //Prints out zeros
       }

While if an 'int' variable is declared as a local variable it does not get initialized.

       public static void main(String [] args) {
           int a;
            System.out.println(a);
           //Compilation error: The local variable a may not have been initialized
       }


问:
PHP: File upload won't work
I'm having trouble making file uploads with my PHP code. I've checked out a few tutorials and some debug tips and advice (on here and off here), but nothing is working. print_r($_FILES) yields no results. Here's my HTML code:

```<code><form action="admin_avatars.php" method="post" enctype="multipart/form-data">
    <p>Image: <input type="file" name="avatar" id="avatar" /></p>
    <p class="buttonset"><input type="submit" value="Upload" /></p>
</form>
</code>```

And here's my PHP code (with an ini_get just to make sure my file_uploads is set to "on"):

```<code>print("[ini get: ".ini_get("file_uploads")."]<br />");
print("[".$_FILES["avatar"]["name"]. "==".$_FILES["avatar"]["tmp_name"]."]<br />");
</code>```

And, for this, I get the output:

```<code>[ini get: 1]
[==]
</code>```

Kinda stumped at this point why nothing is uploading or why $_FILES isn't being filled with anything. What small detail am I missing?

Thanks!

答:
Ok, for some reason it suddenly works. And I'm not sure why. All the elements that I can see remain the same, but here's my PHP code (PHP is the only thing I changed):

```<code>if($_FILES["character_image"]["name"] <> "") {
    $newfilename = $directory_characters . "/" . createfilename($_REQUEST["character_name"]) . "." . pathinfo($_FILES["character_image"]["name"], PATHINFO_EXTENSION);
    $imagesizeinformation = getimagesize($_FILES["character_image"]["tmp_name"]);
    copy($_FILES["character_image"]["tmp_name"], $newfilename);
}
</code>```

Just in case, here's my HTML code at its barest:

```<code><form action="admin_characters.php" method="post" enctype="multipart/form-data">
    Image: <input type="file" name="character_image" id="character_image" />
    <p class="buttonset"><input type="submit" value="Add" /></p>
</form>
</code>```

If anybody knows what fixed my problem, please let everyone know. I'm stumped what happened here that suddenly allowed the images to come through.

Title: PHP: File upload won't work

Body:
I'm having trouble making file uploads with my PHP code. I've checked out a few tutorials and some debug tips and advice (on here and off here), but nothing is working. print_r($_FILES) yields no results. Here's my HTML code:

<form action="admin_avatars.php" method="post" enctype="multipart/form-data">

Image: <input type="file" name="avatar" id="avatar" />

<input type="submit" value="Upload" />

</form>

And here's my PHP code (with an ini_get just to make sure my file_uploads is set to "on"):

print("[ini get: ".ini_get("file_uploads")."]
");
print("[".$_FILES["avatar"]["name"]. "==".$_FILES["avatar"]["tmp_name"]."]
");

And, for this, I get the output:

[ini get: 1]
[==]

Kinda stumped at this point why nothing is uploading or why $_FILES isn't being filled with anything. What small detail am I missing?

Thanks!

Body:
Ok, for some reason it suddenly works. And I'm not sure why. All the elements that I can see remain the same, but here's my PHP code (PHP is the only thing I changed):

if($_FILES["character_image"]["name"] <> "") {
    $newfilename = $directory_characters . "/" . createfilename($_REQUEST["character_name"]) . "." . pathinfo($_FILES["character_image"]["name"], PATHINFO_EXTENSION);
    $imagesizeinformation = getimagesize($_FILES["character_image"]["tmp_name"]);
    copy($_FILES["character_image"]["tmp_name"], $newfilename);
}

Just in case, here's my HTML code at its barest:

<form action="admin_characters.php" method="post" enctype="multipart/form-data">
    Image: <input type="file" name="character_image" id="character_image" />
    <p class="buttonset"><input type="submit" value="Add" /></p>
</form>

If anybody knows what fixed my problem, please let everyone know. I'm stumped what happened here that suddenly allowed the images to come through.


问:
react-redux-react-router v4 url, updates but the component does not
First off, I have read through just about every example I can find and looked through various boilerplates to see how others have done this. I am having issues loading pages when clicking <Link>'s with react-router v4. I have also installed the package react-router-connected and have been trying that out as well but no improvement can be seen (however it shows the changes in the redux-logger which is nice).

Currently, the url updates just fine and if I manually change the url and press enter, then the next page will load. But, it will not redirect if I click a link. I am also using create-react app for the project, just for your reference. My actual app is setup as the exact example from usage with react-router in the official redux docs. For simplicity, I have changed my routes to only include links to basic components that do nothing but redirect to one another.

Root.js which houses my routes

```<code>import React from 'react';
import { BrowserRouter as Router, Route, Switch } from "react-router-dom";
import { Provider } from 'react-redux';
import { ConnectedRouter } from 'connected-react-router'
// import App from './App';
import NewComponent from './NewComponent';
import OldComponentent from './OldComponent';

const Root = ({ store, history }) => (
  <Provider store={store}>
    <ConnectedRouter history={history}>
      <Router>
        <Switch>
          <Route exact path='/' component={OldComponentent}/>
          <Route path='/new' component={NewComponent}/>
          {/* <Route path='/' component={App}/>
          <Route path='/:filter' component={App}/> */}
        </Switch>
      </Router>
    </ConnectedRouter>
  </Provider>
)

export default Root;
</code>```

Home component

```<code>import React from 'react';
import { connect } from 'react-redux';
import { push } from 'connected-react-router';
import { withRouter } from 'react-router';
import { Link } from 'react-router-dom';
import Button from 'material-ui/Button';

class OldComponent extends React.Component {
  redirectPage = () => { this.props.dispatch(push('/new')); };
  redirectPage1 = () => { this.props.dispatch(push('/')); };

  render() {
    return (
      <div>
        OLD COMPONENT
        <Button onClick={this.redirectPage}>Redirect new</Button>
        <Button onClick={this.redirectPage1}>Redirect /</Button>
        <Link to='/new'>Redirect Link</Link>
      </div>
    )
  }
}

export default withRouter(connect()(OldComponent));
</code>```

Other basic component for redirection purposes

```<code>import React from 'react';
import { connect } from 'react-redux';
import { push } from 'connected-react-router';
import { withRouter } from 'react-router';
import { Link } from 'react-router-dom';
import Button from 'material-ui/Button';

class NewComponent extends React.Component {
  redirectPage = () => { this.props.dispatch(push('/')); };
  redirectPage1 = () => { this.props.dispatch(push('/new')); };

  render() {
    return (
      <div>
        NEW COMPONENT
        <Button onClick={this.redirectPage}>Redirect /</Button>
        <Button onClick={this.redirectPage1}>Redirect new</Button>
        <Link to='/new'>Redirect Link</Link>
      </div>
    )
  }
}

export default withRouter(connect()(NewComponent));
</code>```

As you can see, they are essentially the same component with minor differences. The url will change to /new or / and will also update the pathname found in the @@router/LOCATION-CHANGE state objects created by react-router-connected package. The url will also change by clicking the <Link> tag but with no redirect.

Any help on how to approach this would be greatly appreciated.

答: The comment posted by @Supertopoz works this.props.history.push('/pathname') works. However, after setting that up, the <Link> now works as well. I am also using withRouter (which I was before) throughout, so that was another important factor in egtting it to work.

Body:
First off, I have read through just about every example I can find and looked through various boilerplates to see how others have done this. I am having issues loading pages when clicking <Link>'s with react-router v4. I have also installed the package react-router-connected and have been trying that out as well but no improvement can be seen (however it shows the changes in the redux-logger which is nice).

Currently, the url updates just fine and if I manually change the url and press enter, then the next page will load. But, it will not redirect if I click a link. I am also using create-react app for the project, just for your reference. My actual app is setup as the exact example from usage with react-router in the official redux docs. For simplicity, I have changed my routes to only include links to basic components that do nothing but redirect to one another.

Root.js which houses my routes

import React from 'react';
import { BrowserRouter as Router, Route, Switch } from "react-router-dom";
import { Provider } from 'react-redux';
import { ConnectedRouter } from 'connected-react-router'
// import App from './App';
import NewComponent from './NewComponent';
import OldComponentent from './OldComponent';

const Root = ({ store, history }) => (
  <Provider store={store}>
    <ConnectedRouter history={history}>
      <Router>
        <Switch>
          <Route exact path='/' component={OldComponentent}/>
          <Route path='/new' component={NewComponent}/>
          {/* <Route path='/' component={App}/>
          <Route path='/:filter' component={App}/> */}
        </Switch>
      </Router>
    </ConnectedRouter>
  </Provider>
)

export default Root;

Home component

import React from 'react';
import { connect } from 'react-redux';
import { push } from 'connected-react-router';
import { withRouter } from 'react-router';
import { Link } from 'react-router-dom';
import Button from 'material-ui/Button';

class OldComponent extends React.Component {
  redirectPage = () => { this.props.dispatch(push('/new')); };
  redirectPage1 = () => { this.props.dispatch(push('/')); };

  render() {
    return (

        OLD COMPONENT
        <Button onClick={this.redirectPage}>Redirect new</Button>
        <Button onClick={this.redirectPage1}>Redirect /</Button>
        <Link to='/new'>Redirect Link</Link>

    )
  }
}

export default withRouter(connect()(OldComponent));

Other basic component for redirection purposes

import React from 'react';
import { connect } from 'react-redux';
import { push } from 'connected-react-router';
import { withRouter } from 'react-router';
import { Link } from 'react-router-dom';
import Button from 'material-ui/Button';

class NewComponent extends React.Component {
  redirectPage = () => { this.props.dispatch(push('/')); };
  redirectPage1 = () => { this.props.dispatch(push('/new')); };

  render() {
    return (

        NEW COMPONENT
        <Button onClick={this.redirectPage}>Redirect /</Button>
        <Button onClick={this.redirectPage1}>Redirect new</Button>
        <Link to='/new'>Redirect Link</Link>

    )
  }
}

export default withRouter(connect()(NewComponent));

As you can see, they are essentially the same component with minor differences. The url will change to /new or / and will also update the pathname found in the @@router/LOCATION-CHANGE state objects created by react-router-connected package. The url will also change by clicking the <Link> tag but with no redirect.

Any help on how to approach this would be greatly appreciated.


问:
How do I invoke a private static method using reflection (Java)?
I would like to invoke a private static method. I have its name. I've heard it can be done using Java reflection mechanism. How can I do it?

EDIT: One problem I encountered when trying to invoke the method is how to specify the type of its argument. My method receives one argument and its type is Map. Therefore I cannot do Map<User, String>.TYPE (In run time there's no such a thing as Map because of Java Type erasure). Is there another way to get the method?

答:
```<code>Object insecure; //This needs to be an initialized reference

Class c = insecure.getClass();
Method m = c.getMethod(name, parameterTypes); //Fill the name and types in
m.setAccessible(true);
m.invoke( insecure, parameters ); //Fill in the parameters you would like
</code>```

There are a number of checked exceptions which may be thrown.  Both parameterTypes and parameters are ellipse arguments (variable length), fill them in as needed.  The JVM by specification has a strongly typed calling convention so you need to know the parameter types.

With that said, unless you are writing some sort of application container, server component container, RMI-like system, or JVM based langauge you should avoid doing this.

ContentLicense: CC BY-SA 2.5

Body:
Object insecure; //This needs to be an initialized reference

Class c = insecure.getClass();
Method m = c.getMethod(name, parameterTypes); //Fill the name and types in
m.setAccessible(true);
m.invoke( insecure, parameters ); //Fill in the parameters you would like

There are a number of checked exceptions which may be thrown.  Both parameterTypes and parameters are ellipse arguments (variable length), fill them in as needed.  The JVM by specification has a strongly typed calling convention so you need to know the parameter types.

With that said, unless you are writing some sort of application container, server component container, RMI-like system, or JVM based langauge you should avoid doing this.


问:
XAML : How to change background color only in Design mode?
I have a control with white text foreground color and transparent background color.
Later on this usercontrol will be added into a different control that carries the real background color.

However during designing this, control due white foreground on white background in VS 2010, I can't obviously see anything. In there anyway to define a different color for just the design time?

I have tried this:

```<code>if (System.ComponentModel.DesignerProperties.IsInDesignTool)
{
    LayoutRoot.Background = new SolidColorBrush(Colors.Blue);
}
</code>```

But this doesn't work. Any tips?

UPDATE:

I dont understand how this works for you guys. I have created a new Silverlight 4.0 Application and have inserted this line of code into the ctor:

```<code>public MainPage()
        {
            InitializeComponent();
            LayoutRoot.Background = new SolidColorBrush(Colors.Blue);

        }

<UserControl x:Class="SilverlightApplication3.MainPage"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    mc:Ignorable="d"
    d:DesignHeight="300" d:DesignWidth="400">

    <Grid x:Name="LayoutRoot">

    </Grid>
</UserControl>
</code>```

When I go into Designer, I still dont see it as blue. And I dont even have any isInDesignTime Condition there. What I am missing here?

Thanks,
Kave

答:
Another technique mentioned in this SO question is to use the undocumented property d:DesignerProperties.DesignStyle, which works great for applying a design-time-only style to a single control, but which doesn't appear to work for a Style in a ResourceDictionary that would apply to all of the appropriately-typed controls or elements under the scope of the dictionary.

To solve this, on that same page I provide a simple solution for deploying a designer-only style into a ResourceDictionary. Here is a summary of that answer:

First, put the desired style in a XAML dictionary in the normal way.

```<code><Window.Resources>
    <Style TargetType="TreeViewItem">
        <Setter Property="IsExpanded" Value="True" />
    </Style>
</Window.Resources>
</code>```

Then, in the C# code, remove the style from the ResourceDictionary when design mode is not detected. Do this is in the OnInitialized override:

```<code>protected override void OnInitialized(EventArgs e)
{
    if (DesignerProperties.GetIsInDesignMode(this) == false)
        Resources.Remove(typeof(TreeViewItem));

    base.OnInitialized(e);
}
</code>```

Design Mode:                                                        Runtime Mode:

Body:
I have a control with white text foreground color and transparent background color.
Later on this usercontrol will be added into a different control that carries the real background color.

However during designing this, control due white foreground on white background in VS 2010, I can't obviously see anything. In there anyway to define a different color for just the design time?

I have tried this:

if (System.ComponentModel.DesignerProperties.IsInDesignTool)
{
    LayoutRoot.Background = new SolidColorBrush(Colors.Blue);
}

But this doesn't work. Any tips?

UPDATE:

I dont understand how this works for you guys. I have created a new Silverlight 4.0 Application and have inserted this line of code into the ctor:

public MainPage()
        {
            InitializeComponent();
            LayoutRoot.Background = new SolidColorBrush(Colors.Blue);

        }

<UserControl x:Class="SilverlightApplication3.MainPage"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    mc:Ignorable="d"
    d:DesignHeight="300" d:DesignWidth="400">

    <Grid x:Name="LayoutRoot">

    </Grid>
</UserControl>

When I go into Designer, I still dont see it as blue. And I dont even have any isInDesignTime Condition there. What I am missing here?

Thanks,
Kave

Body:
Another technique mentioned in this SO question is to use the undocumented property d:DesignerProperties.DesignStyle, which works great for applying a design-time-only style to a single control, but which doesn't appear to work for a Style in a ResourceDictionary that would apply to all of the appropriately-typed controls or elements under the scope of the dictionary.

To solve this, on that same page I provide a simple solution for deploying a designer-only style into a ResourceDictionary. Here is a summary of that answer:

First, put the desired style in a XAML dictionary in the normal way.

<Window.Resources>
    <Style TargetType="TreeViewItem">
        <Setter Property="IsExpanded" Value="True" />
    </Style>
</Window.Resources>

Then, in the C# code, remove the style from the ResourceDictionary when design mode is not detected. Do this is in the OnInitialized override:

protected override void OnInitialized(EventArgs e)
{
    if (DesignerProperties.GetIsInDesignMode(this) == false)
        Resources.Remove(typeof(TreeViewItem));

    base.OnInitialized(e);
}

Design Mode:                                                        Runtime Mode:


问:
solution for a real-time client-server socket programming between ionic and windows approaches (like asp.mvc, iis, ...)
I'm implementing server/client solution with real-time interaction. I use windows approaches (Asp.mvc published on IIS web server) as server and a mobile App (ionic approach) as Client.

I'm locking for a solution to interact with the mobile App developed by ionic using WebSocket programming.

I also find some good modules like 'Ionic socket.IO', But it needs Nodejs at server, meanwhile i have use IIS as webserver.

Does anyone have any clue, how to implement and establish socket based communication between server (asp.mvc) and client(ionic mobile app).

It's notable that "I cannot switch to a total new framework (both in server and client)". I mean i cannot switch from asp.mvc to any other frameworks like Nodejs as server-side webserver; At the mean time, I cannot re-develop already developed ionic app to any other frameworks (like phonegap/react-native etc...)

--------------------------- EDITED -------------------------------------

My software suppose to be a full two way binding solution. As i already mentioned, It is Real-Time solution (like a stock trader software). means that App can send data to server and server can send data to App as well.

I have already lunched a webApi.

mobile app can call exposed WebApi functions. but there should be a way for server to push new events to specific cellphone. the WebSocket is the answer for sure.

I'm wondering to know "If there is a way (component or manner) to connect to ionic developed App from server and push new data into target cellphone"?

By the way! vote for closing this message, may frustrate others who have the same scenario

答:
Since you are using IIS already you need a web api to communicate with your mobile app asp.net WebAPI si the way to go and use Signal R with webAPI

https://www.asp.net/signalr/overview/guide-to-the-api


问:
Interval for output messages node.js
So many messages. How i can do periodical output?</p>

```<code>ws.on('message', function incoming(message)
{
    var obj = JSON.parse(message);
    var objj = JSON.parse(obj.data);
    console.log( objj.ui_price);
);
</code>```

答:
To output the most recent price only once every 2 seconds, you can do this:

```<code>let recentPrice = -1;
setInterval(function() {
    if (recentPrice !== -1) {
        console.log(recentPrice);
        recentPrice = -1;
    }
}, 2000);

ws.on('message', function incoming(message) {
    let obj = JSON.parse(message);
    let objj = JSON.parse(obj.data);
    recentPrice = objj.ui_price;
});
</code>```

Do you really have JSON embedded in JSON?  Or, can you skip the JSON.parse(obj.data) and just refer directly to obj.data.ui_price?

Title: Interval for output messages node.js

Body:
So many messages. How i can do periodical output?

ws.on('message', function incoming(message)
{
    var obj = JSON.parse(message);
    var objj = JSON.parse(obj.data);
    console.log( objj.ui_price);
);

Body:
To output the most recent price only once every 2 seconds, you can do this:

let recentPrice = -1;
setInterval(function() {
    if (recentPrice !== -1) {
        console.log(recentPrice);
        recentPrice = -1;
    }
}, 2000);

ws.on('message', function incoming(message) {
    let obj = JSON.parse(message);
    let objj = JSON.parse(obj.data);
    recentPrice = objj.ui_price;
});

Do you really have JSON embedded in JSON?  Or, can you skip the JSON.parse(obj.data) and just refer directly to obj.data.ui_price?


问:
Using special characters in python Popen call
I'm working on a python 2.7 application that is intended to upload files to a 2007 Sharepoint. The server is running on a OpenSUSE machine. The way I'm doing this right now is to use subprocess' Popen to execute a curl command. However, python raises UnicodeEncodeError when the filename has special characters ('á', 'õ', 'ç', e.g.).

I could work around the Unicode Error by forcing a conversion

from str to Unicode for the command string, but then the file goes to Sharepoint with a bad formatting name (Manutenção becomes Manuten'c~ao, for instance). The following image describes the implementation of the functions I'm using: functions used

Does anyone have a clue on how should I proceed?

P.S.: I would prefer to stay with the curl command for the execution of the request, but we're open to other solutions

EDIT: Didn't try pycurl, but I'll take a look on it. The Linux dist running the server is 3.11.10.
The execution flow is as following:

Read the file name and path from a utf-8 database

Choose the destination url for file in Sharepoint

Build a curl command similar to "curl --ntlm -u usr:pwd --upload-file filelocalPath fileSharepointUrl -k"

Use the convert_to_utf_8 function (check attached image)

Use Popen to make the request (as in __execute_curl_cmd_and_wait function)

答:
Ok, guys, I figured out the problem

Since I was running my code on a Linux machine, the Popen command was encoded in utf-8 and sent to Sharepoint this way. However, it seems the encoding used by Sharepoint 2007 is some of latin-1 or windows-1252.

I came to this conclusion after running that same code on a Windows machine and encoding the line with a bunch of other encodings. As expected, the upload went OK whenever the encoding was windows-1252 or latin-1 (recognized by the win cmd).

Thanks for the replies.


问:
What does exclamation point after variable mean in TypeScript?
I've seen in some React/TypeScript implementations such as :

ref={ ref => this.container = ref! }

What does the exclamation point means in ref!?
Is that something specific in TypeScript, or a new standard JavaScript notation?

答:
In TypeScript, a postfix ! removes null and undefined from the type of an expression.

This is useful when you know, for reasons outside TypeScript's inference ability, that a variable that "could" be null or undefined actually isn't.


问:
Setting bootstrap dropdown width less than 240px
I am using ngx-boostrap (AngularJS for Bootstrap) for drop-downs.

I an trying to have the max-width of lets say 120px for my dropdown, but I never gets small than 240px. Is there any reason behind it

This photo is the design

and this photo is what I am building

The html, js codes are as exactly as what is put in ngx-bootstrap, nothing fancy.
For css, I am putting max-width=120px on everything inside the dropdown-menu and itself and I can not make that smaller.

What is any remedy?

答:
You're on the right track!  If you inspect .dropdown-menu you'll see it has the following value:

min-width: 160px

Since your max-width is less than that nothings going to happen; min-width is bigger and it's going to win.  Easiest solution is going to be to reset that value in your override:

```<code>.dropdown-menu {
  min-width: 0px;
  max-width: 120px;
}
</code>```

Just keep in mind that any contents inside of .dropdown-menu that exceed this width will flow out of the container box.

Body:
You're on the right track!  If you inspect .dropdown-menu you'll see it has the following value:

min-width: 160px

Since your max-width is less than that nothings going to happen; min-width is bigger and it's going to win.  Easiest solution is going to be to reset that value in your override:

.dropdown-menu {
  min-width: 0px;
  max-width: 120px;
}

Just keep in mind that any contents inside of .dropdown-menu that exceed this width will flow out of the container box.


问:
fmap applied to types other than the type variable
I have a datatype which keeps track of a 'block' of numbers (kinda like a matrix).

```<code>newtype Block a = Block [[a]]
</code>```

I would like to make it an instance of Functor. However, I am trying to do it in such a way that fmap can apply to the whole list block, so that fmap has type fmap :: [[a]] -> [[b]] instead of type fmap :: a -> b.

The reason is because I would like to map into my Block functor functions like transpose which apply to the list block [[a]] not to each element a. That is, I would like to be able to define functions like

```<code>transposeBlock :: Block a -> Block a
transposeBlock = (transpose <$>)
</code>```

I tried to declare my functor instance as the following.

```<code>instance Functor (Block [[a]]) where
  fmap f (Block x) = Block (f x)
</code>```

But I ran into the type errors that arise from attempting to compile this.

```<code>error:
• Expecting one fewer argument to ‘Block [[a]]’
  Expected kind ‘* -> *’, but ‘Block [[a]]’ has kind ‘*’
• In the first argument of ‘Functor’, namely ‘Block [[a]]’
  In the instance declaration for ‘Functor (Block [[a]])’
</code>```

What are some ways that I could map functions into the list block [[a]] of my Block type?

答:
Others have already commented on the opportunity of using fmap for this.

Wrapping / unwrapping newtypes is boring, but safe coercions can make this immediate.

```<code>import Data.Coerce

newtype Block a = Block [[a]]

onBlock :: ([[a]] -> [[b]]) -> Block a -> Block b
onBlock = coerce
</code>```

Indeed, one might even avoid onBlock completely, and directly use coerce as needed.

Body:
I have a datatype which keeps track of a 'block' of numbers (kinda like a matrix).

newtype Block a = Block [[a]]

I would like to make it an instance of Functor. However, I am trying to do it in such a way that fmap can apply to the whole list block, so that fmap has type fmap :: [[a]] -> [[b]] instead of type fmap :: a -> b.

The reason is because I would like to map into my Block functor functions like transpose which apply to the list block [[a]] not to each element a. That is, I would like to be able to define functions like

transposeBlock :: Block a -> Block a
transposeBlock = (transpose <$>)

I tried to declare my functor instance as the following.

instance Functor (Block [[a]]) where
  fmap f (Block x) = Block (f x)

But I ran into the type errors that arise from attempting to compile this.

error:
• Expecting one fewer argument to ‘Block [[a]]’
  Expected kind ‘* -> *’, but ‘Block [[a]]’ has kind ‘*’
• In the first argument of ‘Functor’, namely ‘Block [[a]]’
  In the instance declaration for ‘Functor (Block [[a]])’

What are some ways that I could map functions into the list block [[a]] of my Block type?

Body:
Others have already commented on the opportunity of using fmap for this.

Wrapping / unwrapping newtypes is boring, but safe coercions can make this immediate.

import Data.Coerce

newtype Block a = Block [[a]]

onBlock :: ([[a]] -> [[b]]) -> Block a -> Block b
onBlock = coerce

Indeed, one might even avoid onBlock completely, and directly use coerce as needed.


问:
How to call CMake from a python script using the environment set up by vcvarsall.bat?
I have a python script for a C++ project that uses CMake as the build system. I want to use the CMake Ninja generator instead of the Visual Studio generator. However, the Ninja generator expects the environment to be set up as performed by the vcvarsall.bat batch file provided with the Visual Studio installation.

It's easy if you do everything manually because you can just call the vcvarsall.bat file, get a command prompt with the correct environment set up and then you can fire the cmake -G Ninja command from there.

Things become more difficult when trying to use a python script that has not been started in such an environment. How do I call the vcvarsall.bat file programmatically from python, followed by a cmake call in that environment?

I assume that the only way is to just fire one subprocess from python. But I cannot come up with a parameter list that would do the job.

答:
I'm lucky enough to have found an answer to my own question.

Here is the right python call to be used:

src_dir   = ... # set your source dir here
build_dir = ... # set your build dir here

# retrieve visual studio installation path using vswhere.
# See: https://github.com/Microsoft/vswhere
vswhere = os.path.join(os.environ['ProgramFiles(x86)'],
                       "Microsoft Visual Studio",
                       "Installer",
                       "vswhere.exe")

# get installation path of Visual Studio 2017
vspath = subprocess.Popen([vswhere, "-property", "installationPath", "-version", "[15,16)"],
                          stdout=subprocess.PIPE).communicate()[0].rstrip()

# build path to vcvarsall.bat file
vcvarsall = os.path.join(vspath, "VC", "Auxiliary", "Build", "vcvarsall.bat")

# vcvarsall.bat changes the current directory to the one specified
# by the environment variable %VSCMD_START_DIR%
my_env = os.environ
my_env["VSCMD_START_DIR"] = build_dir

# set up the environment and then call cmake with Ninja generator
subprocess.call('call "' + vcvarsall + '" x64 && cmake -G Ninja "' + src_dir + '"', shell=True, env=my_env)
```


问:
applying a rule once only child selector maybe?
```<code>#mainContent .container{
    background-image:url("/images/index_33.jpg");
    background-repeat:no-repeat;
    padding-left:85px;
    margin-top:10px;
}
</code>```

how can only apply those rules to the first div with a class container?

答:
```<code>.container div:first-child {
 /* ... */
}
</code>```

Body:
#mainContent .container{
    background-image:url("/images/index_33.jpg");
    background-repeat:no-repeat;
    padding-left:85px;
    margin-top:10px;
}

how can only apply those rules to the first div with a class container?


问:
Adjacency matrix from Pandas edgelist dataframe for undirected graphs
```<code>data1 = { 'node1': [1,1,1,2],
     'node2': [2,3,5,4],
     'weight': [1,1,1,1], }
df1 = pd.DataFrame(data1, columns = ['node1','node2','weight'])
</code>```

I want to create an adjacency matrix from pandas dataframe.The dataframe has edgelist of the undirected graph

OUTPUT:

```<code>0 1 1 0 1
1 0 0 1 0
1 0 0 0 0
0 1 0 0 0
1 0 0 0 0
</code>```

My code:

```<code>def adjmat():
    print 'begun creating adjen mat'
    data = sc.loadtxt('training.csv', dtype='str', delimiter=',',skiprows=1)
    data = sc.transpose(data)
    row1 = data[1].astype(int)
    row2 = data[2].astype(int)
    weight=data[3].astype(int)
    n=0
    n1=0
    n2=0

    n1=max(row1)
    n2=max(row2)

    if n1>n2:

        Amat=sc.zeros((n1,n1))
        #matrix=sc.zeros((n1,n1))
        n=n1

    else:
        Amat=sc.zeros((n2,n2))
        #matrix=sc.zeros((n2,n2))
        n=n2

    for i in range(0,len(row1)):

        row=row1[i]
        col=row2[i]

        Amat[row-1][col-1]=weight[i]

    i_lower = np.tril_indices(n, -1)
    Amat[i_lower] = Amat.T[i_lower]

    return Amat
</code>```

I am looking for code which will be scalable.right now I am deaing with dataset which has 100,000 nodes and this code is not able to handle such large dataset.

答:
```<code>Using networkx.....

data1 = { 'node1': [1,1,1,2],
 'node2': [2,3,5,4],
 'weight': [1,1,1,1], }
df1 = pd.DataFrame(data1, columns = ['node1','node2','weight'])
G=nx.from_pandas_dataframe(df1,'node1','node2','weight')

Adjtraining = nx.adjacency_matrix(G)

print Adjtraining.todense()

output

[[0 1 1 0 1]
 [1 0 0 1 0]
 [1 0 0 0 0]
 [0 1 0 0 0]
 [1 0 0 0 0]]
</code>```

Body:
data1 = { 'node1': [1,1,1,2],
     'node2': [2,3,5,4],
     'weight': [1,1,1,1], }
df1 = pd.DataFrame(data1, columns = ['node1','node2','weight'])

I want to create an adjacency matrix from pandas dataframe.The dataframe has edgelist of the undirected graph

OUTPUT:

0 1 1 0 1
1 0 0 1 0
1 0 0 0 0
0 1 0 0 0
1 0 0 0 0

My code:

def adjmat():
    print 'begun creating adjen mat'
    data = sc.loadtxt('training.csv', dtype='str', delimiter=',',skiprows=1)
    data = sc.transpose(data)
    row1 = data[1].astype(int)
    row2 = data[2].astype(int)
    weight=data[3].astype(int)
    n=0
    n1=0
    n2=0

    n1=max(row1)
    n2=max(row2)

    if n1>n2:

        Amat=sc.zeros((n1,n1))
        #matrix=sc.zeros((n1,n1))
        n=n1

    else:
        Amat=sc.zeros((n2,n2))
        #matrix=sc.zeros((n2,n2))
        n=n2

    for i in range(0,len(row1)):

        row=row1[i]
        col=row2[i]

        Amat[row-1][col-1]=weight[i]

    i_lower = np.tril_indices(n, -1)
    Amat[i_lower] = Amat.T[i_lower]

    return Amat

I am looking for code which will be scalable.right now I am deaing with dataset which has 100,000 nodes and this code is not able to handle such large dataset.


问:
DocuSign Decline Reasons Radio button with Textbox
I need to have radio button list with few options with an additional textbox in docusign decline reasons.

I'm able to create a radio button list by updating the signing resources with

```<code><data name="DocuSign_DeclineReasons">800=Decline Reason 1;900=Decline Reason 2;1000=Decline Reason 3</data>
</code>```

Docusign Sample UI modified

However adding any html tags is not working in it.

答: You cannot add html related attributes in signing resource file. HTML tags work only on email resource file.

Body:
I need to have radio button list with few options with an additional textbox in docusign decline reasons.

I'm able to create a radio button list by updating the signing resources with

<data name="DocuSign_DeclineReasons">800=Decline Reason 1;900=Decline Reason 2;1000=Decline Reason 3</data>

Docusign Sample UI modified

However adding any html tags is not working in it.


问:
Websocket Private Chat Application
I am new to the websocket concept and that's why I am writing this topic. I would like to know how I can secure a chat room so that only two specific users can only subscribe to it. To be clearer let me give you an example.

/chats/room/{firstUserId}-{secondUserId}

which for user ids 114 & 43 will be

/chats/room/114-43

and only those users will be able to join that room. Thank you in advance!

答:
Client opens a websocket by issuing an HTTP GET on a URL. It's exactly the same as a normal HTTP GET with a few header fields set, like:

```<code>Connection: Upgrade
Upgrade: websocket
</code>```

The server subsequently hijacks that connection. In other words, nothing prevents you from using exactly the scheme you want, i.e. /chats/room/114-43, if you like it. Websocket URL is just an URL.

Title: Websocket Private Chat Application

Body:
Client opens a websocket by issuing an HTTP GET on a URL. It's exactly the same as a normal HTTP GET with a few header fields set, like:

Connection: Upgrade
Upgrade: websocket

The server subsequently hijacks that connection. In other words, nothing prevents you from using exactly the scheme you want, i.e. /chats/room/114-43, if you like it. Websocket URL is just an URL.


问:
How to visualize actual hexdec in memory in visual studio
Sounds crazy but in my class on Writing Secure Code the professor had us all configure or add a plugin to actually visualize the hexdec address values in memory for a process. We used it to define how to see the pointer that was the stack bound/offset and then fill the stack beyond that point. Just wondering if anyone is familiar with this capability in VS.</p>

答:
The watch window allows a great deal of configuration of how variables are displayed, for example, if you watch "variable,x" it will format the value in hex, if you do "variable,[10]x" it will expand it as an array of 10 hex values.

See more at https://msdn.microsoft.com/en-us/library/75w45ekt.aspx


问:
Selectively use dependent modules in AngularJS
I'm writing a small application where I have all AngularJS code inside of one file. This file is included in every HTML page. How would I filter which dependent modules are needed for specific HTML page? I.e. if I have e.g.:

```<code>var app = angular.module('MyApp', ['ngTouch', 'ngMessages']);
</code>```

but I only need ngTouch on some pages and on the other pages only ngMessages, how would I prevent loading the other, unnecessary dependent module for each page?

答:
You would use specialized modules to depend on a core module to separate the concerns. So for example, you could have something similar to this:

```<code>angular.module('app.core', ['ngAnimate']);
angular.module('PicadviceApp', ['app.core', 'ngTouch']);
angular.module('messages', ['app.core', 'ngMessages']);
</code>```

This would essentially declare the 'app.core' module as the core module that every page in your application needs to load, and on specific pages you would then have specialized modules that load any additional dependencies.

One page can load up the PicadviceApp module and another page would load up the messages module. But both pages would have access to the ngAnimate module because of the app.core dependency.

Body:
I'm writing a small application where I have all AngularJS code inside of one file. This file is included in every HTML page. How would I filter which dependent modules are needed for specific HTML page? I.e. if I have e.g.:

var app = angular.module('MyApp', ['ngTouch', 'ngMessages']);

but I only need ngTouch on some pages and on the other pages only ngMessages, how would I prevent loading the other, unnecessary dependent module for each page?

Body:
You would use specialized modules to depend on a core module to separate the concerns. So for example, you could have something similar to this:

angular.module('app.core', ['ngAnimate']);
angular.module('PicadviceApp', ['app.core', 'ngTouch']);
angular.module('messages', ['app.core', 'ngMessages']);

This would essentially declare the 'app.core' module as the core module that every page in your application needs to load, and on specific pages you would then have specialized modules that load any additional dependencies.

One page can load up the PicadviceApp module and another page would load up the messages module. But both pages would have access to the ngAnimate module because of the app.core dependency.


问:
verify (bitwise) if a value matches multiple specific flags of an enum
I would like to check if a value corresponds to a set of flags (from an enum or object alike).

Right now, I have come up with the following function in javascript (praise the snippet :3):

function hasFlags(flags, value) {
    let s = flags.reduce((sum, v) => sum += v, 0);

    return (s & value) === s
}

FLAGS = {
    STEP_0: 1 << 0,
    STEP_1: 1 << 1,
    STEP_2: 1 << 2,
    STEP_3: 1 << 3,
    STEP_4: 1 << 4,
    STEP_5: 1 << 5,
    STEP_6: 1 << 6,
    STEP_7: 1 << 7
}

const needed = [
    FLAGS.STEP_2,
    FLAGS.STEP_3,
    FLAGS.STEP_6,
]

console.log(hasFlags(needed, 4));                  // false
console.log(hasFlags(needed, 8));                  // false
console.log(hasFlags(needed, 64));                 // false
console.log(hasFlags(needed, 4 + 8));              // false
console.log(hasFlags(needed, 4 + 64));             // false
console.log(hasFlags(needed, 8 + 64));             // false
console.log(hasFlags(needed, 4 + 8 + 64));         // true
console.log(hasFlags(needed, 4 + 8 + 64 + 1));     // true
console.log(hasFlags(needed, 4 + 8 + 64 + 2));     // true
console.log(hasFlags(needed, 4 + 8 + 64 + 1 + 2)); // true
// etc...```
</div>
</div>
</p>

<p>In python the function would look like this:</p>

```def hasFlags(flags, value):
    s = sum(flags)
    return (s & value) == s

print hasFlags((4,8,64), 4)  # False
print hasFlags((4,8,64), 4+8+64)  # True
# ...
```

Is there a better way (that is, more idiomatic ... or more pythonic) to do this same verification?

Edit: Solutions in both python and javascript are appreciated, but I am  especially looking for an algorithm (whatever the language), as I've searched a lot across the web and never found any, while it seems to me that it's a common problem.

答:
When combinations of flags are represented as bit-masks you can do mutations and tests on all the flags at once, directly, using bit-wise operators.</p>

```<code>STEP_0 = 1 << 0
STEP_1 = 1 << 1
STEP_2 = 1 << 2
STEP_3 = 1 << 3
STEP_4 = 1 << 4
STEP_5 = 1 << 5
STEP_6 = 1 << 6
STEP_7 = 1 << 7

def has_flags(flags_to_check_for, cur_flags):
    return (cur_flags & flags_to_check_for) == flags_to_check_for

desired_flags = STEP_2 | STEP_3 | STEP_6

cur_flags = STEP_2
print has_flags(desired_flags, cur_flags)   # False
cur_flags |= STEP_3
cur_flags |= STEP_6
print has_flags(desired_flags, cur_flags)  # True
# ...
</code>```

Body:
I would like to check if a value corresponds to a set of flags (from an enum or object alike).

Right now, I have come up with the following function in javascript (praise the snippet :3):

function hasFlags(flags, value) {
    let s = flags.reduce((sum, v) => sum += v, 0);

    return (s & value) === s
}

FLAGS = {
    STEP_0: 1 << 0,
    STEP_1: 1 << 1,
    STEP_2: 1 << 2,
    STEP_3: 1 << 3,
    STEP_4: 1 << 4,
    STEP_5: 1 << 5,
    STEP_6: 1 << 6,
    STEP_7: 1 << 7
}

const needed = [
    FLAGS.STEP_2,
    FLAGS.STEP_3,
    FLAGS.STEP_6,
]

console.log(hasFlags(needed, 4));                  // false
console.log(hasFlags(needed, 8));                  // false
console.log(hasFlags(needed, 64));                 // false
console.log(hasFlags(needed, 4 + 8));              // false
console.log(hasFlags(needed, 4 + 64));             // false
console.log(hasFlags(needed, 8 + 64));             // false
console.log(hasFlags(needed, 4 + 8 + 64));         // true
console.log(hasFlags(needed, 4 + 8 + 64 + 1));     // true
console.log(hasFlags(needed, 4 + 8 + 64 + 2));     // true
console.log(hasFlags(needed, 4 + 8 + 64 + 1 + 2)); // true
// etc...

In python the function would look like this:

def hasFlags(flags, value):
    s = sum(flags)
    return (s & value) == s

print hasFlags((4,8,64), 4)  # False
print hasFlags((4,8,64), 4+8+64)  # True
# ...

Is there a better way (that is, more idiomatic ... or more pythonic) to do this same verification?

Edit: Solutions in both python and javascript are appreciated, but I am  especially looking for an algorithm (whatever the language), as I've searched a lot across the web and never found any, while it seems to me that it's a common problem.

Body:
When combinations of flags are represented as bit-masks you can do mutations and tests on all the flags at once, directly, using bit-wise operators.

STEP_0 = 1 << 0
STEP_1 = 1 << 1
STEP_2 = 1 << 2
STEP_3 = 1 << 3
STEP_4 = 1 << 4
STEP_5 = 1 << 5
STEP_6 = 1 << 6
STEP_7 = 1 << 7

def has_flags(flags_to_check_for, cur_flags):
    return (cur_flags & flags_to_check_for) == flags_to_check_for

desired_flags = STEP_2 | STEP_3 | STEP_6

cur_flags = STEP_2
print has_flags(desired_flags, cur_flags)   # False
cur_flags |= STEP_3
cur_flags |= STEP_6
print has_flags(desired_flags, cur_flags)  # True
# ...


问:
Problems with big query and subquery
I thought that I'll be clever and use subquery to get my report in one go. But after running into problems and reading documentation I saw that my approach does not work in MySQL. My inner query returns ~100 records and outer query scans 20000 records.
When I restricted outer query to 20 records then it run 20 sec - really slow.

I wonder is it possible to restructure it somehow so that inner query wouldn't be run EVERY time for every record in the outer query?

```<code>select p1.surname ,p1.name,p1.id,r1.start_date,r1.end_date,c1.short_name
FROM ejl_players p1
left JOIN ejl_registration r1 ON ( r1.player_id = p1.id )
left JOIN ejl_teams t1 ON ( r1.team_id = t1.id )
left JOIN ejl_clubs c1 ON ( t1.club_id = c1.id )
where  r1.season=2008
and p1.id in
 (
SELECT p.id
FROM ejl_players p
left JOIN ejl_registration r ON (r.player_id = p.id)
left JOIN ejl_teams t ON (r.team_id = t.id)
left JOIN ejl_clubs c ON (t.club_id = c.id)
WHERE r.season = 2008
GROUP BY p.id
HAVING COUNT(DISTINCT c.id)  > 1
)
</code>```

Explain (I restricted outer query to maximum 20 records:

```<code>id  select_type  table  type  possible_keys  key  key_len  ref  rows  Extra
1 PRIMARY p1 range PRIMARY PRIMARY 4 NULL 19 Using where
1 PRIMARY r1 ref team_id,season season 10 const,d17528sd14898.p1.id 1 Using where
1 PRIMARY t1 eq_ref PRIMARY PRIMARY 4 d17528sd14898.r1.team_id 1
1 PRIMARY c1 eq_ref PRIMARY PRIMARY 4 d17528sd14898.t1.club_id 1
2 DEPENDENT SUBQUERY p index PRIMARY PRIMARY 5 NULL 23395 Using index
2 DEPENDENT SUBQUERY r ref team_id,season season 10 const,d17528sd14898.p.id 1 Using where; Using index
2 DEPENDENT SUBQUERY t eq_ref PRIMARY PRIMARY 4 d17528sd14898.r.team_id 1
2 DEPENDENT SUBQUERY c eq_ref PRIMARY PRIMARY 4 d17528sd14898.t.club_id 1 Using index
</code>```

答:
Like I commented on your question the other day, you don't need to use a LEFT JOIN in this example.  Outer joins often perform slower than inner joins, so you can get some better performance by using a simple inner join.

You would need to use an outer join only if you need to show all players, even those who don't have any registration.

It seems that your query is looking for players who have been on teams in more than one club this year (like your earlier question), and then outputting some details of their registration and club name.  Here's how I would solve this query:

```<code>SELECT p.surname, p.name, p.id, r.start_date, r.end_date, c1.short_name
FROM ejl_players p
 INNER JOIN ejl_registration r1 ON (r.player_id = p.id)
 INNER JOIN ejl_teams t1 ON (r.team_id = t1.id)
 INNER JOIN ejl_clubs c1 ON (t1.club_id = c1.id)
 INNER JOIN ejl_teams t2 ON (r.team_id = t2.id)
 INNER JOIN ejl_clubs c2 ON (t2.club_id = c2.id)
WHERE r.season = 2008
GROUP BY r.player_id, r.team_id
HAVING COUNT(DISTINCT c2.id) > 1;
</code>```

This works in MySQL because MySQL is permissive about the Single-Value Rule.  That is, the columns in your GROUP BY clause don't have to be the same as the non-aggregated columns named in your select-list.  In other brands of RDBMS, this query would generate an error.

OwnerDisplayName: Riho

Title: Problems with big query and subquery

Body:
I thought that I'll be clever and use subquery to get my report in one go. But after running into problems and reading documentation I saw that my approach does not work in MySQL. My inner query returns ~100 records and outer query scans 20000 records.
When I restricted outer query to 20 records then it run 20 sec - really slow.

I wonder is it possible to restructure it somehow so that inner query wouldn't be run EVERY time for every record in the outer query?

select p1.surname ,p1.name,p1.id,r1.start_date,r1.end_date,c1.short_name
FROM ejl_players p1
left JOIN ejl_registration r1 ON ( r1.player_id = p1.id )
left JOIN ejl_teams t1 ON ( r1.team_id = t1.id )
left JOIN ejl_clubs c1 ON ( t1.club_id = c1.id )
where  r1.season=2008
and p1.id in
 (
SELECT p.id
FROM ejl_players p
left JOIN ejl_registration r ON (r.player_id = p.id)
left JOIN ejl_teams t ON (r.team_id = t.id)
left JOIN ejl_clubs c ON (t.club_id = c.id)
WHERE r.season = 2008
GROUP BY p.id
HAVING COUNT(DISTINCT c.id)  > 1
)

Explain (I restricted outer query to maximum 20 records:

id  select_type  table  type  possible_keys  key  key_len  ref  rows  Extra
1 PRIMARY p1 range PRIMARY PRIMARY 4 NULL 19 Using where
1 PRIMARY r1 ref team_id,season season 10 const,d17528sd14898.p1.id 1 Using where
1 PRIMARY t1 eq_ref PRIMARY PRIMARY 4 d17528sd14898.r1.team_id 1
1 PRIMARY c1 eq_ref PRIMARY PRIMARY 4 d17528sd14898.t1.club_id 1
2 DEPENDENT SUBQUERY p index PRIMARY PRIMARY 5 NULL 23395 Using index
2 DEPENDENT SUBQUERY r ref team_id,season season 10 const,d17528sd14898.p.id 1 Using where; Using index
2 DEPENDENT SUBQUERY t eq_ref PRIMARY PRIMARY 4 d17528sd14898.r.team_id 1
2 DEPENDENT SUBQUERY c eq_ref PRIMARY PRIMARY 4 d17528sd14898.t.club_id 1 Using index

LastEditorDisplayName: Riho

Body:
Like I commented on your question the other day, you don't need to use a LEFT JOIN in this example.  Outer joins often perform slower than inner joins, so you can get some better performance by using a simple inner join.

You would need to use an outer join only if you need to show all players, even those who don't have any registration.

It seems that your query is looking for players who have been on teams in more than one club this year (like your earlier question), and then outputting some details of their registration and club name.  Here's how I would solve this query:

SELECT p.surname, p.name, p.id, r.start_date, r.end_date, c1.short_name
FROM ejl_players p
 INNER JOIN ejl_registration r1 ON (r.player_id = p.id)
 INNER JOIN ejl_teams t1 ON (r.team_id = t1.id)
 INNER JOIN ejl_clubs c1 ON (t1.club_id = c1.id)
 INNER JOIN ejl_teams t2 ON (r.team_id = t2.id)
 INNER JOIN ejl_clubs c2 ON (t2.club_id = c2.id)
WHERE r.season = 2008
GROUP BY r.player_id, r.team_id
HAVING COUNT(DISTINCT c2.id) > 1;

This works in MySQL because MySQL is permissive about the Single-Value Rule.  That is, the columns in your GROUP BY clause don't have to be the same as the non-aggregated columns named in your select-list.  In other brands of RDBMS, this query would generate an error.

OwnerDisplayName: Bill Karwin


问:
Using breakpoints to debug Javascript in IE and VS2008
I am not able to use the breakpoint in Studio with Javascript.  I'm able to debug if I use the debugger;

I've seen this Breakpoint not hooked up when debugging in VS.Net 2005 question already.  I tried the answer and it didn't work.

Looking in the Modules window, V.Mvc.Jobtrakt.PDB is loaded properly, but it points to a temp folder
C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\Temporary ASP.NET Files\root\dbc0c0c5\f64a99b3\assembly\dl3\9de055b3\eb1303b1_9760c901\V.Mvc.Jobtrak.pdb: Symbols loaded.

I would have thought that it would point to:
  \JobTrak\Website\V.Mvc.Jobtrak\V.Mvc.Jobtrak\obj\Debug ( this is within the project directory)

But regardless of the location I closed VS 2008 and then blew away the temp folder (listed above), the bin and obj folders.

Opened VS 2008 and did a clean.  I set a break point in the js and it seemed like it would work now ( The breakpoint was filled in)
Started to debug and it never breaks on the breakpoint. Look at the break point and it now is a red circle with a red dot and a warning indicator.  Hovering over the breakpoint gives me this useful information: The breakpoint will not currently be hit. The location could not be mapped to a client side script. See help for ASPX Breakpoint mapping. I am not being redirected, the breakpoint is with in a function. blah blah blah this should be working.

So I was wondering if anyone has any ideas?
Is anyone able to set breakpoints in VS2008 and have them work?

答: this happened to me also. The breakpoints stopped to work in some functions. In my case, the problem was that I used <%=..%> inside the script. As far as I could figure out reading MSDN, this happens because Visual Studio maps the breakpoint lines from the .ASPX to the resulting HTML based on line content, so when you put a <%=..> your resulting script will be different from the one in the .ASPX file.

LastEditorDisplayName: Kent Fredric


问:
How to convert case class to HList than to modify than to create case class again by shapeless?
Hello I am new in shapeless, I want to create Hlist from case class, than to modify fields than to create case class again, its possible by shapeless:

```<code>        val user:RfModelCalibration = users.head
        val transformer  = Generic[RfModelCalibration]
        val beforeTransform = transformer.to(user)
        val afterTransform = beforeTransform.map(enumTransform)
        val newCaseClass = transformer.from(afterTransform)
</code>```

But I can't exec "beforeTransform.map(enumTransform)" Can I do It by shapeless?

答:
Yes, you can.

The following code should compile:

```<code>  import shapeless.{Generic, Poly1}

  case class RfModelCalibration(field1: Field1, field2: Field2)

  val user: RfModelCalibration = users.head
  val transformer  = Generic[RfModelCalibration]
  val beforeTransform = transformer.to(user)
  val afterTransform = beforeTransform.map(enumTransform)
  val newCaseClass = transformer.from(afterTransform)

  object enumTransform extends Poly1 {
    implicit val cse1: Case.Aux[Field1, Field1] = at(x => ???)
    implicit val cse2: Case.Aux[Field2, Field2] = at(x => ???)
  }
</code>```

Body:
Hello I am new in shapeless, I want to create Hlist from case class, than to modify fields than to create case class again, its possible by shapeless:

        val user:RfModelCalibration = users.head
        val transformer  = Generic[RfModelCalibration]
        val beforeTransform = transformer.to(user)
        val afterTransform = beforeTransform.map(enumTransform)
        val newCaseClass = transformer.from(afterTransform)

But I can't exec "beforeTransform.map(enumTransform)" Can I do It by shapeless?

Body:
Yes, you can.

The following code should compile:

  import shapeless.{Generic, Poly1}

  case class RfModelCalibration(field1: Field1, field2: Field2)

  val user: RfModelCalibration = users.head
  val transformer  = Generic[RfModelCalibration]
  val beforeTransform = transformer.to(user)
  val afterTransform = beforeTransform.map(enumTransform)
  val newCaseClass = transformer.from(afterTransform)

  object enumTransform extends Poly1 {
    implicit val cse1: Case.Aux[Field1, Field1] = at(x => ???)
    implicit val cse2: Case.Aux[Field2, Field2] = at(x => ???)
  }


问:
Angular 4 - BehaviourSubject not returning json data properly
I'm trying to creating a global service in angular app with BehaviorSubject.

I have created a method in this service where I have defined a HTTP get method and loading JSON file.

Now the issue I'm facing is when I'm subscribing this BehaviourSubject as asObservable in any component and assign the result to a particular variable in the typescript file, the HTML template renders this value correctly via structured Directive *ngFor but when I'm trying to get the same value in typescript file, it does not work.

For example;

When I'm trying to print this value

```<code>console.log(this.data.boxes.length);
</code>```

then it gives me an error

[ERROR TypeError: Cannot read property 'length' of undefined]

and when I'm trying to print this value without length

```<code>console.log(this.data.boxes);
</code>```

it gives me a proper value of an array in the console panel.

Now If I change BehaviorSubject to Subject, then its working fine means I am also getting length value.

However, I want to use BehaviorSubject instead of Subject.

What am I doing wrong and how can I achieve it?

答:
Behavior subject is emitting current value to subscriber even if subject next is not called before subscription, in other words:

yours subscription is subscribed to subject before first "next" value. I assume that initial value of behavior subject is undefined or similar, so that first value that is emitted to subscriber is causing error.
Could you check declaration of subject and ensure that initial value is in correct form, like:

```<code>public exampleSubject = new BeahviourSubject<yourType[]>(<yourType[]>[]);
</code>```

Body:
I'm trying to creating a global service in angular app with BehaviorSubject.

I have created a method in this service where I have defined a HTTP get method and loading JSON file.

Now the issue I'm facing is when I'm subscribing this BehaviourSubject as asObservable in any component and assign the result to a particular variable in the typescript file, the HTML template renders this value correctly via structured Directive *ngFor but when I'm trying to get the same value in typescript file, it does not work.

For example;

When I'm trying to print this value

console.log(this.data.boxes.length);

then it gives me an error

[ERROR TypeError: Cannot read property 'length' of undefined]

and when I'm trying to print this value without length

console.log(this.data.boxes);

it gives me a proper value of an array in the console panel.

Now If I change BehaviorSubject to Subject, then its working fine means I am also getting length value.

However, I want to use BehaviorSubject instead of Subject.

What am I doing wrong and how can I achieve it?

Body:
Behavior subject is emitting current value to subscriber even if subject next is not called before subscription, in other words:

yours subscription is subscribed to subject before first "next" value. I assume that initial value of behavior subject is undefined or similar, so that first value that is emitted to subscriber is causing error.
Could you check declaration of subject and ensure that initial value is in correct form, like:

public exampleSubject = new BeahviourSubject<yourType[]>(<yourType[]>[]);


问:
Cakephp3 odd behavior with external link that has https in url parameters (first https gets remove)
Ok I'm trying using LinkedIn's api and when I build out a sample call, example below

```<code><a href="https://www.linkedin.com/oauth/v2/authorization?response_type=code&client_id=123456789&redirect_uri=https://www.example.com/auth/linkedin&state=987654321">Login</a>
</code>```

It displays like this on the front end of cakephp 3, the first https is getting striped away

```<code><a href="/oauth/v2/authorization?response_type=code&client_id=123456789&redirect_uri=https://www.example.com/auth/linkedin&state=wGg4ksv8WHpx26dV">Login in</a>
</code>```

As soon as I remove the https from the redirct_uir parameter or the whole redirct_uri parameter it display currently. Anyone know how to fix this or a good work around. I need have a https in both urls for the api to work correctly.

答:
You are using invalid characters in your query parameters. I'm going to guess that the browser is stripping the https since there are :// characters after the ? query identifier.

You have to call urlencode("https://www.example.com/auth/linkedin") and use the result as the query parameter.

Body:
Ok I'm trying using LinkedIn's api and when I build out a sample call, example below

Login

It displays like this on the front end of cakephp 3, the first https is getting striped away

Login in

As soon as I remove the https from the redirct_uir parameter or the whole redirct_uri parameter it display currently. Anyone know how to fix this or a good work around. I need have a https in both urls for the api to work correctly.


问:
NER types for 'en' model?
Is there a way to get all the built-in and added custom NER types in spaCy? The method suggested here doesn't seem to work anymore. On trying

```<code>nlp.entity.cfg
</code>```

I get back,

```<code>{u'hist_size': 0, u'pretrained_dims': 0L, u'hist_width': 0, u'beam_density':
0.0, u'cnn_maxout_pieces': 3, u'maxout_pieces': 2, u'hidden_depth': 1,
u'token_vector_width': 128, u'nr_class': 73, u'beam_width': 1,
u'hidden_width': 200}
</code>```

There are no 'actions' and 'extra_labels' keys in this dictionary.

答:
Not quite sure if this is the way it's to be done. I figured out on calling

```<code>nlp.entity.move_names
</code>```

returns,

```<code>[u'B-PERSON', u'B-CARDINAL', u'B-ORG', u'B-GPE', u'B-FAC', u'B-MONEY', u'B-NORP', u'B-DATE', u'B-TIME', u'B-ORDINAL', u'B-PERCENT', u'B-PRODUCT', u'B-LANGUAGE', u'B-LOC', u'B-QUANTITY', u'B-WORK_OF_ART', u'B-EVENT', u'B-LAW', u'I-PERSON', u'I-CARDINAL', u'I-ORG', u'I-GPE', u'I-FAC', u'I-MONEY', u'I-NORP', u'I-DATE', u'I-TIME', u'I-ORDINAL', u'I-PERCENT', u'I-PRODUCT', u'I-LANGUAGE', u'I-LOC', u'I-QUANTITY', u'I-WORK_OF_ART', u'I-EVENT', u'I-LAW', u'L-PERSON', u'L-CARDINAL', u'L-ORG', u'L-GPE', u'L-FAC', u'L-MONEY', u'L-NORP', u'L-DATE', u'L-TIME', u'L-ORDINAL', u'L-PERCENT', u'L-PRODUCT', u'L-LANGUAGE', u'L-LOC', u'L-QUANTITY', u'L-WORK_OF_ART', u'L-EVENT', u'L-LAW', u'U-PERSON', u'U-CARDINAL', u'U-ORG', u'U-GPE', u'U-FAC', u'U-MONEY', u'U-NORP', u'U-DATE', u'U-TIME', u'U-ORDINAL', u'U-PERCENT', u'U-PRODUCT', u'U-LANGUAGE', u'U-LOC', u'U-QUANTITY', u'U-WORK_OF_ART', u'U-EVENT', u'U-LAW', u'O']
</code>```

This also shows any additional custom entities added to the model, like u'EMAIL' in my case:

```<code>[u'B-PERSON', u'B-CARDINAL', u'B-ORG', u'B-GPE', u'B-FAC', u'B-MONEY', u'B-NORP', u'B-DATE', u'B-TIME', u'B-ORDINAL', u'B-PERCENT', u'B-PRODUCT', u'B-LANGUAGE', u'B-LOC', u'B-QUANTITY', u'B-WORK_OF_ART', u'B-EVENT', u'B-LAW', u'I-PERSON', u'I-CARDINAL', u'I-ORG', u'I-GPE', u'I-FAC', u'I-MONEY', u'I-NORP', u'I-DATE', u'I-TIME', u'I-ORDINAL', u'I-PERCENT', u'I-PRODUCT', u'I-LANGUAGE', u'I-LOC', u'I-QUANTITY', u'I-WORK_OF_ART', u'I-EVENT', u'I-LAW', u'L-PERSON', u'L-CARDINAL', u'L-ORG', u'L-GPE', u'L-FAC', u'L-MONEY', u'L-NORP', u'L-DATE', u'L-TIME', u'L-ORDINAL', u'L-PERCENT', u'L-PRODUCT', u'L-LANGUAGE', u'L-LOC', u'L-QUANTITY', u'L-WORK_OF_ART', u'L-EVENT', u'L-LAW', u'U-PERSON', u'U-CARDINAL', u'U-ORG', u'U-GPE', u'U-FAC', u'U-MONEY', u'U-NORP', u'U-DATE', u'U-TIME', u'U-ORDINAL', u'U-PERCENT', u'U-PRODUCT', u'U-LANGUAGE', u'U-LOC', u'U-QUANTITY', u'U-WORK_OF_ART', u'U-EVENT', u'U-LAW', u'O', u'B-EMAIL', u'I-EMAIL', u'L-EMAIL', u'U-EMAIL']
</code>```

Title: NER types for 'en' model?

Body:
Is there a way to get all the built-in and added custom NER types in spaCy? The method suggested here doesn't seem to work anymore. On trying

nlp.entity.cfg

I get back,

{u'hist_size': 0, u'pretrained_dims': 0L, u'hist_width': 0, u'beam_density':
0.0, u'cnn_maxout_pieces': 3, u'maxout_pieces': 2, u'hidden_depth': 1,
u'token_vector_width': 128, u'nr_class': 73, u'beam_width': 1,
u'hidden_width': 200}

There are no 'actions' and 'extra_labels' keys in this dictionary.

Body:
Not quite sure if this is the way it's to be done. I figured out on calling

nlp.entity.move_names

returns,

[u'B-PERSON', u'B-CARDINAL', u'B-ORG', u'B-GPE', u'B-FAC', u'B-MONEY', u'B-NORP', u'B-DATE', u'B-TIME', u'B-ORDINAL', u'B-PERCENT', u'B-PRODUCT', u'B-LANGUAGE', u'B-LOC', u'B-QUANTITY', u'B-WORK_OF_ART', u'B-EVENT', u'B-LAW', u'I-PERSON', u'I-CARDINAL', u'I-ORG', u'I-GPE', u'I-FAC', u'I-MONEY', u'I-NORP', u'I-DATE', u'I-TIME', u'I-ORDINAL', u'I-PERCENT', u'I-PRODUCT', u'I-LANGUAGE', u'I-LOC', u'I-QUANTITY', u'I-WORK_OF_ART', u'I-EVENT', u'I-LAW', u'L-PERSON', u'L-CARDINAL', u'L-ORG', u'L-GPE', u'L-FAC', u'L-MONEY', u'L-NORP', u'L-DATE', u'L-TIME', u'L-ORDINAL', u'L-PERCENT', u'L-PRODUCT', u'L-LANGUAGE', u'L-LOC', u'L-QUANTITY', u'L-WORK_OF_ART', u'L-EVENT', u'L-LAW', u'U-PERSON', u'U-CARDINAL', u'U-ORG', u'U-GPE', u'U-FAC', u'U-MONEY', u'U-NORP', u'U-DATE', u'U-TIME', u'U-ORDINAL', u'U-PERCENT', u'U-PRODUCT', u'U-LANGUAGE', u'U-LOC', u'U-QUANTITY', u'U-WORK_OF_ART', u'U-EVENT', u'U-LAW', u'O']

This also shows any additional custom entities added to the model, like u'EMAIL' in my case:

[u'B-PERSON', u'B-CARDINAL', u'B-ORG', u'B-GPE', u'B-FAC', u'B-MONEY', u'B-NORP', u'B-DATE', u'B-TIME', u'B-ORDINAL', u'B-PERCENT', u'B-PRODUCT', u'B-LANGUAGE', u'B-LOC', u'B-QUANTITY', u'B-WORK_OF_ART', u'B-EVENT', u'B-LAW', u'I-PERSON', u'I-CARDINAL', u'I-ORG', u'I-GPE', u'I-FAC', u'I-MONEY', u'I-NORP', u'I-DATE', u'I-TIME', u'I-ORDINAL', u'I-PERCENT', u'I-PRODUCT', u'I-LANGUAGE', u'I-LOC', u'I-QUANTITY', u'I-WORK_OF_ART', u'I-EVENT', u'I-LAW', u'L-PERSON', u'L-CARDINAL', u'L-ORG', u'L-GPE', u'L-FAC', u'L-MONEY', u'L-NORP', u'L-DATE', u'L-TIME', u'L-ORDINAL', u'L-PERCENT', u'L-PRODUCT', u'L-LANGUAGE', u'L-LOC', u'L-QUANTITY', u'L-WORK_OF_ART', u'L-EVENT', u'L-LAW', u'U-PERSON', u'U-CARDINAL', u'U-ORG', u'U-GPE', u'U-FAC', u'U-MONEY', u'U-NORP', u'U-DATE', u'U-TIME', u'U-ORDINAL', u'U-PERCENT', u'U-PRODUCT', u'U-LANGUAGE', u'U-LOC', u'U-QUANTITY', u'U-WORK_OF_ART', u'U-EVENT', u'U-LAW', u'O', u'B-EMAIL', u'I-EMAIL', u'L-EMAIL', u'U-EMAIL']


问:
Bubble sorting in dynamic array of objects in C++
I have class City with following private data: name of city, width,length and height of the city. I have to make dynamic array, which is inserted by constructor by default- City(),when the programs starts.Then the program uses method output() and prints inserted array of cities.

I should use bubble sort to sort the cities by their length. And when this is done, the program should show the sorted cities in increasing lengths.

The problem is that my data are in private(in public everything works excellent but principle of capsulation is violated!) so I can't do bubble sort.

I tried to do another dynamic array of type double double Lengths[n], which content is lengths of first array. Then I do sorting, but program prints only sorted lengths and this is not my goal.

I should print the names of cities sorted by their lengths.

Code:

```<code>class City{
private: char *name;
         double width;
         double length;
         double height;
public:void Output();
    City();
    ~City();
    double GetLength()
    {
        return length;
    }
    double GetWidth(){ return width; }
    double GetHeight(){ return height; }
    char GetName(){ return *name; }

};
City::City()
{
    char ime[20];
    cout << "Name= ";
    cin >> ime;
    name = new char[strlen(ime) + 1];
    for (int i = 0; i <=strlen(ime); i++)
        name[i] = ime[i];

    cout << "Width= ";
    cin >> width;
    cout << "Length= ";
    cin >> length;
    cout << "Height= ";
    cin >> height;
}
void City::Output()
{
    cout << "Name is: " << name << endl;
    cout << " Width is: " << width <<" deg"<< endl;;
    cout << " Length is: " << length << " deg"<<endl;
    cout << " Height is: " << height <<" m"<<endl;
    return;
}
City::~City()
{
    cout << " " << endl;
cout << "Destructor of City!" << endl;
delete[] name;
}

int main()
{
    //City town;

    //town.Input();
    //town.Output();
    int n;
    City *mA;
    cout << "Input number of cities: " << endl;
    cin >> n;
    mA = new City[n];
    for (int j = 0; j < n; j++)
    {
        mA[j].Output();
    }
    cout << "Cities from west to east, sorted by their length" << endl;
    double *Lengths = new double[n];
    for (int j = 0; j < n; j++)
    {
        Lengths[j] = mA[j].GetLength();

    }
int k = 0;//counter
    double max = Lengths[0];
    for (int j = 1; j < n; j++)
    {
        if (Lengths[j - 1] >Lengths[j])
        {
            max = Lengths[j - 1];
            Lengths[j - 1] = Lengths[j];
            Lengths[j] = max;
        }
    }

    for (int j = 0; j < n; j++)//cycle for output
    {
        mA[j].Output();
    }

    delete[]mA;
    return 0;

}
</code>```

答:
As I can't quite comment on your response, I will give you a few bits of advice. First in the line of:

Array[j]=mA[j].GetName() ;

You have a random space which may be a copy change and relatively minor but for reading purposes that is wrong.

Second your naming conventions are really something you should work on. I should be able to read a variable and understand what it means but instead I struggle to understand what a variable named mA means.

Third your else clause does nothing literally. Your not moving any parts of the array if that is your intention my saying this:

```<code>mA[j+1];
</code>```

you are simply targeting the element in the array that is above the iteration. I see you stuck with your idea of making something similar to a parallel array for the bubble sort, and that is fine but you lack any action in the first loop.

This is not bubble sort what so ever as you are simply going  through each iteration and checking if the element in Lengths is equal in length to the element in mA and then storing that element in array but your else statement does nothing.

Your loop should look similar to something like this but I'm gonna get rid of the character array and the extra array for some reason as it is unnecessary and lets say you start out with an array of your objects:

```<code>        if(myObjects[i].GetLength() > myObjects[i+1].GetLength()) //Shortest to longest name or vice versa?
        {
             //Store myObject[i] in temp spot
             //myObject[i] = myObject[i+1]
             //myObject[i+1] = temp Storage
        }
</code>```

This will give you a bubble sort of the objects on the first round. Of course your going to have to find out how to iterate through the array in  loop to verify all of the elements have been sorted correctly as this will of course take many iterations for bubble sort.

Body:
I have class City with following private data: name of city, width,length and height of the city. I have to make dynamic array, which is inserted by constructor by default- City(),when the programs starts.Then the program uses method output() and prints inserted array of cities.

I should use bubble sort to sort the cities by their length. And when this is done, the program should show the sorted cities in increasing lengths.

The problem is that my data are in private(in public everything works excellent but principle of capsulation is violated!) so I can't do bubble sort.

I tried to do another dynamic array of type double double Lengths[n], which content is lengths of first array. Then I do sorting, but program prints only sorted lengths and this is not my goal.

I should print the names of cities sorted by their lengths.

Code:

class City{
private: char *name;
         double width;
         double length;
         double height;
public:void Output();
    City();
    ~City();
    double GetLength()
    {
        return length;
    }
    double GetWidth(){ return width; }
    double GetHeight(){ return height; }
    char GetName(){ return *name; }

};
City::City()
{
    char ime[20];
    cout << "Name= ";
    cin >> ime;
    name = new char[strlen(ime) + 1];
    for (int i = 0; i <=strlen(ime); i++)
        name[i] = ime[i];

    cout << "Width= ";
    cin >> width;
    cout << "Length= ";
    cin >> length;
    cout << "Height= ";
    cin >> height;
}
void City::Output()
{
    cout << "Name is: " << name << endl;
    cout << " Width is: " << width <<" deg"<< endl;;
    cout << " Length is: " << length << " deg"<<endl;
    cout << " Height is: " << height <<" m"<<endl;
    return;
}
City::~City()
{
    cout << " " << endl;
cout << "Destructor of City!" << endl;
delete[] name;
}

int main()
{
    //City town;

    //town.Input();
    //town.Output();
    int n;
    City *mA;
    cout << "Input number of cities: " << endl;
    cin >> n;
    mA = new City[n];
    for (int j = 0; j < n; j++)
    {
        mA[j].Output();
    }
    cout << "Cities from west to east, sorted by their length" << endl;
    double *Lengths = new double[n];
    for (int j = 0; j < n; j++)
    {
        Lengths[j] = mA[j].GetLength();

    }
int k = 0;//counter
    double max = Lengths[0];
    for (int j = 1; j < n; j++)
    {
        if (Lengths[j - 1] >Lengths[j])
        {
            max = Lengths[j - 1];
            Lengths[j - 1] = Lengths[j];
            Lengths[j] = max;
        }
    }

    for (int j = 0; j < n; j++)//cycle for output
    {
        mA[j].Output();
    }

    delete[]mA;
    return 0;

}

Body:
As I can't quite comment on your response, I will give you a few bits of advice. First in the line of:

Array[j]=mA[j].GetName() ;

You have a random space which may be a copy change and relatively minor but for reading purposes that is wrong.

Second your naming conventions are really something you should work on. I should be able to read a variable and understand what it means but instead I struggle to understand what a variable named mA means.

Third your else clause does nothing literally. Your not moving any parts of the array if that is your intention my saying this:

mA[j+1];

you are simply targeting the element in the array that is above the iteration. I see you stuck with your idea of making something similar to a parallel array for the bubble sort, and that is fine but you lack any action in the first loop.

This is not bubble sort what so ever as you are simply going  through each iteration and checking if the element in Lengths is equal in length to the element in mA and then storing that element in array but your else statement does nothing.

Your loop should look similar to something like this but I'm gonna get rid of the character array and the extra array for some reason as it is unnecessary and lets say you start out with an array of your objects:

        if(myObjects[i].GetLength() > myObjects[i+1].GetLength()) //Shortest to longest name or vice versa?
        {
             //Store myObject[i] in temp spot
             //myObject[i] = myObject[i+1]
             //myObject[i+1] = temp Storage
        }

This will give you a bubble sort of the objects on the first round. Of course your going to have to find out how to iterate through the array in  loop to verify all of the elements have been sorted correctly as this will of course take many iterations for bubble sort.


问:
How should I name my CSS classes?
How should my class names be?

For example, a CSS class for a vote count, how should I name it?

```<code>.vote-count-post     (1) // SO uses this
.VoteCountPost       (2)
.voteCountPost       (3)
.vote.count-post     (4)
.vote .count-post    (5)
.vote .count.post    (6)
</code>```

What are the advantages and disadvantages of each?

Which is most used and why?

Are there any implications in any of these?

May I have any uppercase in my CSS?

答: i suggest use this <code>.VoteCountPost</code> less space and readable.. </p>

Title: How should I name my CSS classes?

Body:
How should my class names be?

For example, a CSS class for a vote count, how should I name it?

.vote-count-post     (1) // SO uses this
.VoteCountPost       (2)
.voteCountPost       (3)
.vote.count-post     (4)
.vote .count-post    (5)
.vote .count.post    (6)

What are the advantages and disadvantages of each?

Which is most used and why?

Are there any implications in any of these?

May I have any uppercase in my CSS?

Body: i suggest use this .VoteCountPost less space and readable..