问:
valgrind says i have conditional jump or move depends on initialized value(s)
I am having an issue where valgrind is saying that i have a conditional jump or the move depends on initialized values

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

ListNodePtr convertBSTtoLinkedList(TreeNodePtr root)
{
    ListNodePtr newNode;
    ListNodePtr leftLinkedList;
    ListNodePtr rightLinkedList;
    ListNodePtr head;

    if (root == NULL)
    {
        return NULL;
    }

    newNode = malloc(sizeof(struct ListNode));
    newNode->key = root->key;
    head = newNode;

    if(root->left != NULL)
    {
        leftLinkedList = convertBSTtoLinkedList(root->left);
        head = leftLinkedList;

        ListNodePtr conductor;
        conductor = leftLinkedList;
        while (conductor->next != NULL)
        {
            conductor = conductor->next;
        }

        conductor->next = newNode;

    }

    if(root->right != NULL)
    {
        rightLinkedList= convertBSTtoLinkedList(root->right);
        newNode->next = rightLinkedList;
    }

    return head;
    }
</code>```

valgrind the problem is somewhere in the while loop and i am assuming it is because i havent initialized that conductor->next is NULL, but i dont know how to do that since it it checking if it is NULL

答:
Here what you can do is when you create a node in some place in your code initialize next with a NULL. That will most likely close this message of valgrind.

So add this line in your code

newNode->next = NULL;

The problem arises because the value that you are checking to be NULL is not initialized with NULL. As a result this checking is as if it is with some uninitialized value.

The solution I mentioned is just intializing every node with a proper next and key value.

Few points:

Check if the return value of malloc whether it failed or succeeded.

```<code>if ( newNode == NULL)
{
   fprintf(stderr,"Error");
   exit(1);
}
</code>```

Body:
I am having an issue where valgrind is saying that i have a conditional jump or the move depends on initialized values

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

ListNodePtr convertBSTtoLinkedList(TreeNodePtr root)
{
    ListNodePtr newNode;
    ListNodePtr leftLinkedList;
    ListNodePtr rightLinkedList;
    ListNodePtr head;

    if (root == NULL)
    {
        return NULL;
    }

    newNode = malloc(sizeof(struct ListNode));
    newNode->key = root->key;
    head = newNode;

    if(root->left != NULL)
    {
        leftLinkedList = convertBSTtoLinkedList(root->left);
        head = leftLinkedList;

        ListNodePtr conductor;
        conductor = leftLinkedList;
        while (conductor->next != NULL)
        {
            conductor = conductor->next;
        }

        conductor->next = newNode;

    }

    if(root->right != NULL)
    {
        rightLinkedList= convertBSTtoLinkedList(root->right);
        newNode->next = rightLinkedList;
    }

    return head;
    }

valgrind the problem is somewhere in the while loop and i am assuming it is because i havent initialized that conductor->next is NULL, but i dont know how to do that since it it checking if it is NULL

Body:
Here what you can do is when you create a node in some place in your code initialize next with a NULL. That will most likely close this message of valgrind.

So add this line in your code

newNode->next = NULL;

The problem arises because the value that you are checking to be NULL is not initialized with NULL. As a result this checking is as if it is with some uninitialized value.

The solution I mentioned is just intializing every node with a proper next and key value.

Few points:

Check if the return value of malloc whether it failed or succeeded.

if ( newNode == NULL)
{
   fprintf(stderr,"Error");
   exit(1);
}


来源: stackexchange

问:
How I calculate the total distance of points in postgres in a table?
```<code>long,lat,time
10,11,0
11,12,1
12,13,2
</code>```

I have a simple table with longitudine, latitude and time and i want know a function that calculate the total distance of points in postgres.

答:
If you want to calculate the distance you can use the extention earthdistance and do something like :

```<code>SELECT earth_distance(lat, long)
  FROM your_table;
</code>```

The earthdistance module provides two different approaches to calculating great circle distances on the surface of the Earth. The one described first depends on the cube package (which must be installed before earthdistance can be installed). The second one is based on the built-in point datatype, using longitude and latitude for the coordinates.

In this module, the Earth is assumed to be perfectly spherical. (If that's too inaccurate for you, you might want to look at the PostGIS project.)

ContentLicense: CC BY-SA 3.0

Body:
long,lat,time
10,11,0
11,12,1
12,13,2

I have a simple table with longitudine, latitude and time and i want know a function that calculate the total distance of points in postgres.

Body:
If you want to calculate the distance you can use the extention earthdistance and do something like :

SELECT earth_distance(lat, long)
  FROM your_table;

The earthdistance module provides two different approaches to calculating great circle distances on the surface of the Earth. The one described first depends on the cube package (which must be installed before earthdistance can be installed). The second one is based on the built-in point datatype, using longitude and latitude for the coordinates.

In this module, the Earth is assumed to be perfectly spherical. (If that's too inaccurate for you, you might want to look at the PostGIS project.)


问:
ReSharper (or something like it) for SQL Server / T-SQL?
Are there any IDEs or extensions to IDEs that allow editing stored procedures as if they were programs so that if I were to place my cursor on a call to a stored procedure when editing a stored procedure, I could hit F12 and it would load the stored procedure under the cursor into the IDE?

Being able to refactor out a block of code into a new stored procedure would also be a welcome improvement.

答: SSMS Tools has a lot of useful features.  I'm not sure if it will do exactly what Refactor does, but worth a shot.</p>

ContentLicense: CC BY-SA 2.5


问:
Is it possible to prevent Google Assistant from taking over RCU mic button signal in an Android TV app?
The Android TV (ATV) app I'm working on has voice control capabilities. Basically, when the user presses the microphone button on a remote controller, the key event (identified by KeyEvent.KEYCODE_SEARCH) is handled by the app, speech recognition starts (using android.speech.SpeechRecognizer), the results (parsed speech) are obtained and parsed further by the app logic (e.g. showing the user search results or performing some in-app action).

Everything has been working as intended and described above, until, quite recently, Google Assistant (GA) was introduced to ATV platforms (the first one being Nvidia Shield box). Now, when the RCU mic button is pressed, the GA overlay appears and the mic key event doesn't even reach the app.

For the last few days I've done some extensive research (documentation, internet, forums, stackoverflow etc.) and experimented with some potential workarounds, but nothing's worked so far and I haven't been able to find any definite information on the topic (probably due to the ATV+GA combination being rather new on the scene, and the ATV ecosystem not being as large as the Android one).

The best hint I got so far is what's been done with the Spotify app for Android TV. When it's run on an ATV device with no GA, it basically behaves as I described above; but when GA is present, the GA overlay appears, receives the parsed speech and shows the search results, with results from Spotify in the first line - so, the Spotify app is integrated with GA, and this integration replaces the in-app voice control mechanism. This suggests that either there is no way to ignore/disable GA inside your app in order to receive the mic key event and proceed with voice control as usual, or at least this is the preferred way of handling voice commands now. It also shows that there are apps for ATV that approach voice control the way I described, so maybe someone here has already encountered similar problem.

My question(s):

is it possible to prevent Google Assistant from taking over RCU mic button signal?

is it ok to do so? (by "not ok" I would mean - are there any official guidelines that discourage such behavior - or at least are there valid reasons not to do so?)

if so, can it be done?

if not, is there a resource documenting how to integrate with GA (the way Spotify for ATV app does)?

答:
Starting with your last question:

if not, is there a resource documenting how to integrate with GA (the way Spotify for ATV app does)?

I wrote about how to integrate on the Android Developer's Blog. Spotify has onboarded their content catalog to Google's services which is why the Google Assistant is able to work so well. You can achieve similar results if you make your app searchable (covered in the blog).

is it possible to prevent Google Assistant from taking over RCU mic button signal?

No, not at this time. The Google Assistant is a system app that takes control over the mic to give a uniform experience across all apps.

is it ok to do so? (by "not ok" I would mean - are there any official guidelines that discourage such behavior - or at least are there valid reasons not to do so?)

if so, can it be done?

You can still have an in-app search experience. There is an example in the leanback sample. You will need to set a listener on a BrowseFragment and implement a SearchFragment. We know this can be confusing, have in-app search and Google Assistant search competing, but we are working on how to improve this.


问:
Angular auth guard Can't resolve all parameters
im tryin to create an auth.guard.service but for some reason i get error Can't resolve all parameters for AuthGuard: (?, [object Object])., here is the services.

```<code>import { Observable } from 'rxjs/Observable';
// import { AuthService } from './auth.service';
import { Injectable } from '@angular/core';
import { CanActivate, Router, RouterStateSnapshot, ActivatedRouteSnapshot } from '@angular/router';

@Injectable()
export class AuthGuard implements CanActivate {
  user = true;
  constructor(private auth: any, private router: Router) { }

  canActivate(
    next: ActivatedRouteSnapshot,
    state: RouterStateSnapshot): Observable<boolean> | boolean {
    if (this.user) {
      return true;
    }
    this.router.navigate(['']);
    return false;
  }
}
</code>```

and here is the app.module

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

import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { NavComponent } from './components/nav/nav.component';
import { HomeComponent } from './components/home/home.component';
import { GalleryComponent } from './components/gallery/gallery.component';
import { FooterComponent } from './components/footer/footer.component';

import { NgbModule } from '@ng-bootstrap/ng-bootstrap';
import { ScrollToModule } from 'ng2-scroll-to';
import { NgxCarouselModule } from 'ngx-carousel';
import { AnimateOnScrollModule } from 'ng2-animate-on-scroll';

import { AuthGuard } from './services/auth.guard.service';

import { HttpClientModule, HttpClient } from '@angular/common/http';
import { TranslateModule, TranslateLoader } from '@ngx-translate/core';
import { TranslateHttpLoader } from '@ngx-translate/http-loader';

const routes: Routes = [
  { path: '', component: HomeComponent },
  { path: 'gallery', component: GalleryComponent, canActivate: [AuthGuard] }
];

export function HttpLoaderFactory(http: HttpClient) {
  return new TranslateHttpLoader(http);
}

@NgModule({
  declarations: [
    AppComponent,
    NavComponent,
    HomeComponent,
    GalleryComponent,
    FooterComponent
  ],
  imports: [
    BrowserModule,
    AppRoutingModule,
    NgxCarouselModule,
    NgbModule.forRoot(),
    ScrollToModule.forRoot(),
    RouterModule.forRoot(routes),
    AnimateOnScrollModule.forRoot(),
    HttpClientModule,
    TranslateModule.forRoot({
      loader: {
        provide: TranslateLoader,
        useFactory: HttpLoaderFactory,
        deps: [HttpClient]
      }
    })
  ],
  exports: [
    TranslateModule
  ],
  providers: [AuthGuard],
  bootstrap: [AppComponent]
})
export class AppModule { }
</code>```

i dont know where could be error is, the services that im importin on the auth.guard.services is commented because i not using it yet, just in case, for some reason i can resolve all the parameters if somebody have an idea.

答: The error you are getting is a run-time error related to Angular Dependency Injection. It can't determine how to create the dependency represented by the first constructor parameter because its type is any. You can change the type from any to some type that is provided or use @Inject on a type or token that is provided. Angular DI shouldn't have a problem with the second parameter (Router).

Body:
im tryin to create an auth.guard.service but for some reason i get error Can't resolve all parameters for AuthGuard: (?, [object Object])., here is the services.

import { Observable } from 'rxjs/Observable';
// import { AuthService } from './auth.service';
import { Injectable } from '@angular/core';
import { CanActivate, Router, RouterStateSnapshot, ActivatedRouteSnapshot } from '@angular/router';

@Injectable()
export class AuthGuard implements CanActivate {
  user = true;
  constructor(private auth: any, private router: Router) { }

  canActivate(
    next: ActivatedRouteSnapshot,
    state: RouterStateSnapshot): Observable<boolean> | boolean {
    if (this.user) {
      return true;
    }
    this.router.navigate(['']);
    return false;
  }
}

and here is the app.module

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';

import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { NavComponent } from './components/nav/nav.component';
import { HomeComponent } from './components/home/home.component';
import { GalleryComponent } from './components/gallery/gallery.component';
import { FooterComponent } from './components/footer/footer.component';

import { NgbModule } from '@ng-bootstrap/ng-bootstrap';
import { ScrollToModule } from 'ng2-scroll-to';
import { NgxCarouselModule } from 'ngx-carousel';
import { AnimateOnScrollModule } from 'ng2-animate-on-scroll';

import { AuthGuard } from './services/auth.guard.service';

import { HttpClientModule, HttpClient } from '@angular/common/http';
import { TranslateModule, TranslateLoader } from '@ngx-translate/core';
import { TranslateHttpLoader } from '@ngx-translate/http-loader';

const routes: Routes = [
  { path: '', component: HomeComponent },
  { path: 'gallery', component: GalleryComponent, canActivate: [AuthGuard] }
];

export function HttpLoaderFactory(http: HttpClient) {
  return new TranslateHttpLoader(http);
}

@NgModule({
  declarations: [
    AppComponent,
    NavComponent,
    HomeComponent,
    GalleryComponent,
    FooterComponent
  ],
  imports: [
    BrowserModule,
    AppRoutingModule,
    NgxCarouselModule,
    NgbModule.forRoot(),
    ScrollToModule.forRoot(),
    RouterModule.forRoot(routes),
    AnimateOnScrollModule.forRoot(),
    HttpClientModule,
    TranslateModule.forRoot({
      loader: {
        provide: TranslateLoader,
        useFactory: HttpLoaderFactory,
        deps: [HttpClient]
      }
    })
  ],
  exports: [
    TranslateModule
  ],
  providers: [AuthGuard],
  bootstrap: [AppComponent]
})
export class AppModule { }

i dont know where could be error is, the services that im importin on the auth.guard.services is commented because i not using it yet, just in case, for some reason i can resolve all the parameters if somebody have an idea.


问:
thread issue using post
i am new to android and threading in general. I am currently making a game where the rendering and logic happens on a separate thread from the UI.
My issue is that i cant seem to update the ui using post from the worker thread.

This is my mainActivity:

```<code>private GameScene gameScene;
private Handler uiHandler;

@Override
protected void onCreate(Bundle savedInstanceState) {
    requestWindowFeature(Window.FEATURE_NO_TITLE);
    super.onCreate(savedInstanceState);
    getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,WindowManager.LayoutParams.FLAG_FULLSCREEN);
    setContentView(R.layout.game);
    uiHandler = new Handler(Looper.getMainLooper());

    gameScene = new GameScene(getApplicationContext(), uiHandler);
    LinearLayout gameHolder = (LinearLayout)findViewById(R.id.game_view);
    gameHolder.addView(gameScene);
    gameScene.resume();
}
</code>```

This is the class which implements runnable:

```<code>public abstract class Scene extends SurfaceView implements Runnable {

    Handler uiHandler;
    Thread thread = null;
    public Scene(Context context, Handler uiHandler) {
        super(context);
        this.uiHandler = uiHandler;
    }

    @Override
    public void run() {
        uiHandler.post(() -> {
            TextView textView = findViewById(R.id.fps_counter);
            textView.setText("hello");
        });
    }

    public void resume() {
        thread = new Thread(this);
        thread.start();
    }
</code>```

xml:

```<code><?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <LinearLayout
        android:id="@+id/game_view"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="horizontal"
        android:visibility="visible">

        <TextView
            android:id="@+id/fps_counter"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_weight="1"
            android:text="0"
            android:textColor="@color/colorAccent"
            android:textSize="24sp" />
    </LinearLayout>

</FrameLayout>
</code>```

The code inside post should run on the ui thread right? But i am getting a null object reference when trying to set the text. And yes the text with id fps_counter exists.

答:
You are calling findViewById inside your SurfaceView effectively looking for a view with given id inside your SurfaceView.

But your view with R.id.fps_counter id is inside the activity, so you should look for it in the activity.

I suggest you to find it before creating the GameScene class and provide it in the constructor.

See https://developer.android.com/reference/android/view/View.html#findViewById(int) and https://developer.android.com/reference/android/app/Activity.html#findViewById(int)

Use the code by petey in the later answer.

Another solution would be to pass the activity to your GameScene, then you would be able to do it without a handler.

```<code>private GameScene gameScene;
private TextView fpsCounter;

@Override
protected void onCreate(Bundle savedInstanceState) {
    requestWindowFeature(Window.FEATURE_NO_TITLE);
    super.onCreate(savedInstanceState);
    getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,WindowManager.LayoutParams.FLAG_FULLSCREEN);
    setContentView(R.layout.game);

    fpsCounter = findViewById(R.id.fps_counter);
    gameScene = new GameScene(this);
    LinearLayout gameHolder = (LinearLayout)findViewById(R.id.game_view);
    gameHolder.addView(gameScene);
    gameScene.resume();
}

public void setFps(String fps) {
    fpsCounter.setText(fps);
}
</code>```

and

```<code>public abstract class Scene extends SurfaceView implements Runnable {

    Thread thread;
    Activity activity;

    public Scene(Activity activity) {
        super(activity);
        this.activity = activity;
    }

    @Override
    public void run() {
        activity.runOnUiThread(() -> {
            activity.setFps("Hello");
        });
    }

    public void resume() {
        thread = new Thread(this);
        thread.start();
    }
</code>```

Even better will be to use constructor expected by the framework and set activity in the init method, like here

Title: thread issue using post

Body:
i am new to android and threading in general. I am currently making a game where the rendering and logic happens on a separate thread from the UI.
My issue is that i cant seem to update the ui using post from the worker thread.

This is my mainActivity:

private GameScene gameScene;
private Handler uiHandler;

@Override
protected void onCreate(Bundle savedInstanceState) {
    requestWindowFeature(Window.FEATURE_NO_TITLE);
    super.onCreate(savedInstanceState);
    getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,WindowManager.LayoutParams.FLAG_FULLSCREEN);
    setContentView(R.layout.game);
    uiHandler = new Handler(Looper.getMainLooper());

    gameScene = new GameScene(getApplicationContext(), uiHandler);
    LinearLayout gameHolder = (LinearLayout)findViewById(R.id.game_view);
    gameHolder.addView(gameScene);
    gameScene.resume();
}

This is the class which implements runnable:

public abstract class Scene extends SurfaceView implements Runnable {

    Handler uiHandler;
    Thread thread = null;
    public Scene(Context context, Handler uiHandler) {
        super(context);
        this.uiHandler = uiHandler;
    }

    @Override
    public void run() {
        uiHandler.post(() -> {
            TextView textView = findViewById(R.id.fps_counter);
            textView.setText("hello");
        });
    }

    public void resume() {
        thread = new Thread(this);
        thread.start();
    }

xml:

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <LinearLayout
        android:id="@+id/game_view"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="horizontal"
        android:visibility="visible">

        <TextView
            android:id="@+id/fps_counter"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_weight="1"
            android:text="0"
            android:textColor="@color/colorAccent"
            android:textSize="24sp" />
    </LinearLayout>

</FrameLayout>

The code inside post should run on the ui thread right? But i am getting a null object reference when trying to set the text. And yes the text with id fps_counter exists.

Body:
You are calling findViewById inside your SurfaceView effectively looking for a view with given id inside your SurfaceView.

But your view with R.id.fps_counter id is inside the activity, so you should look for it in the activity.

I suggest you to find it before creating the GameScene class and provide it in the constructor.

See https://developer.android.com/reference/android/view/View.html#findViewById(int) and https://developer.android.com/reference/android/app/Activity.html#findViewById(int)

Use the code by petey in the later answer.

Another solution would be to pass the activity to your GameScene, then you would be able to do it without a handler.

private GameScene gameScene;
private TextView fpsCounter;

@Override
protected void onCreate(Bundle savedInstanceState) {
    requestWindowFeature(Window.FEATURE_NO_TITLE);
    super.onCreate(savedInstanceState);
    getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,WindowManager.LayoutParams.FLAG_FULLSCREEN);
    setContentView(R.layout.game);

    fpsCounter = findViewById(R.id.fps_counter);
    gameScene = new GameScene(this);
    LinearLayout gameHolder = (LinearLayout)findViewById(R.id.game_view);
    gameHolder.addView(gameScene);
    gameScene.resume();
}

public void setFps(String fps) {
    fpsCounter.setText(fps);
}

and

public abstract class Scene extends SurfaceView implements Runnable {

    Thread thread;
    Activity activity;

    public Scene(Activity activity) {
        super(activity);
        this.activity = activity;
    }

    @Override
    public void run() {
        activity.runOnUiThread(() -> {
            activity.setFps("Hello");
        });
    }

    public void resume() {
        thread = new Thread(this);
        thread.start();
    }

Even better will be to use constructor expected by the framework and set activity in the init method, like here


问:
How to make a dictionary from this data?
So the part of my data.dat looks like this:

carine        mite, tick
accipitrine   bird: hawk, falcon, or bird of prey
acipenserine  sturgeon
aedine        mosquito (genus Aedes)
alaudine      bird: skylark
alcelaphine   antelopes
alcidine      bird: auk, puffin, or murre
alectorine    crane
anatine       duck, mallard
anguilline    snake
```

<p>How could I create a dictionary that would map multiple values (e.g bird: hawk, falcon, or bird of prey maps to accipitrine) to single keys?</p>

<p>This is my code so far:</p>

```with open ('collateralAdjectives.dat', 'r') as a:
    adjectives = a.read().splitlines()

d = dict()
for item in collateralAdjectives:
    (s, c) = item.split(' ')
    d[s] = c
```

<p>This is the error that I get:</p>

```(s, c) = item.split(' ')

ValueError: too many values to unpack (expected 2)
```

答:
These two lines does the job on this example; must be tuned for biggest set.
I use pandas for its excellent readers. Then re to fine string manipulations.

```<code>df0=pd.read_fwf('dic.dat',colspecs=[(0,14),(14,50)],index_col=0, header=None)
df = df0.applymap(lambda s : re.split(', or |, ',s.split(': ')[-1]))

carine                        [mite, tick]
accipitrine   [hawk, falcon, bird of prey]
acipenserine                    [sturgeon]
aedine            [mosquito (genus Aedes)]
alaudine                         [skylark]
alcelaphine                    [antelopes]
alcidine              [auk, puffin, murre]
alectorine                         [crane]
anatine                    [duck, mallard]
anguilline                         [snake]
</code>```

You can then make a dict by d=df[1].to_dict() :

```<code>{'accipitrine': ['hawk', 'falcon', 'bird of prey'],
 'acipenserine': ['sturgeon'],
 'aedine': ['mosquito (genus Aedes)'],
 'alaudine': ['skylark'],
 'alcelaphine': ['antelopes'],
 'alcidine': ['auk', 'puffin', 'murre'],
 'alectorine': ['crane'],
 'anatine': ['duck', 'mallard'],
 'anguilline': ['snake'],
 'carine': ['mite', 'tick']}
</code>```

or use the df as is : df.loc['carine'] is ['mite', 'tick']

Body:
So the part of my data.dat looks like this:

carine        mite, tick
accipitrine   bird: hawk, falcon, or bird of prey
acipenserine  sturgeon
aedine        mosquito (genus Aedes)
alaudine      bird: skylark
alcelaphine   antelopes
alcidine      bird: auk, puffin, or murre
alectorine    crane
anatine       duck, mallard
anguilline    snake

How could I create a dictionary that would map multiple values (e.g bird: hawk, falcon, or bird of prey maps to accipitrine) to single keys?

This is my code so far:

with open ('collateralAdjectives.dat', 'r') as a:
    adjectives = a.read().splitlines()

d = dict()
for item in collateralAdjectives:
    (s, c) = item.split(' ')
    d[s] = c

This is the error that I get:

(s, c) = item.split(' ')

ValueError: too many values to unpack (expected 2)

Body:
These two lines does the job on this example; must be tuned for biggest set.
I use pandas for its excellent readers. Then re to fine string manipulations.

df0=pd.read_fwf('dic.dat',colspecs=[(0,14),(14,50)],index_col=0, header=None)
df = df0.applymap(lambda s : re.split(', or |, ',s.split(': ')[-1]))

carine                        [mite, tick]
accipitrine   [hawk, falcon, bird of prey]
acipenserine                    [sturgeon]
aedine            [mosquito (genus Aedes)]
alaudine                         [skylark]
alcelaphine                    [antelopes]
alcidine              [auk, puffin, murre]
alectorine                         [crane]
anatine                    [duck, mallard]
anguilline                         [snake]

You can then make a dict by d=df[1].to_dict() :

{'accipitrine': ['hawk', 'falcon', 'bird of prey'],
 'acipenserine': ['sturgeon'],
 'aedine': ['mosquito (genus Aedes)'],
 'alaudine': ['skylark'],
 'alcelaphine': ['antelopes'],
 'alcidine': ['auk', 'puffin', 'murre'],
 'alectorine': ['crane'],
 'anatine': ['duck', 'mallard'],
 'anguilline': ['snake'],
 'carine': ['mite', 'tick']}

or use the df as is : df.loc['carine'] is ['mite', 'tick']


问:
Trying to merge into a dataframe but it keeps creating new columns
I am trying to open files and derive 2 columns(1 row for each) from multiple spreadsheets and then merging them to a base spreadsheet.So, the base dataframe (derived from a spreadsheet, from which I only needed 3 columns)  is like this :

```<code>Model |  Roadmap | Family
a       08/12/17  ROW
b       08/14/17  MACRO
c       08/15/17  CONN
d       08/27/17  MACRO
</code>```

The dataframes from the multiple spreadsheets(the model names are the spreadsheet names and they have multiple dates for each gate which i am deriving in multiple dataframes) and have this format :

```<code>    df1 (part1 -  the dataframe derived from the spreadsheet with model a for gate 0 ):
    Model   |  Gate 0
    a         02/01/18

df1 (Dataframe derived from the spreadsheet with model a for gate1):
        Model   |  Gate 1
        a         03/01/18

   df2 (part1):
    Model  |  Gate 0
    b       04/23/18

df2 (part1):
        Model  |  Gate 1
        b       05/23/18
</code>```

The output it produces is :

```<code>Model |  Roadmap | Family | Gate 0_x  | Gate 1_x   | gate 0_y | Gate 1_y
a       08/12/17  ROW      02/01/18   03/01/18
b       08/14/17  MACRO                              04/23/18  05/23/18
c       08/15/17  CONN
d       08/27/17  MACRO
</code>```

the output i want :

```<code>  Model |  Roadmap | Family | Gate 0   | Gate 1
   a       08/12/17  ROW     02/01/18   03/01/18
   b       08/14/17  MACRO    04/23/18  05/23/18
   ..
</code>```

The following is the code i am using:

```<code>import glob
import pandas as pd
import re
import ntpath

extension = 'xlsx'
d='Final.xlsx'
c = 'Roadmap.xlsx'
dflist = []
z=[]
result = [i for i in glob.glob('*.{}'.format(extension))]

for b in result:
    if b==c:
        base_file = pd.read_excel(b, sheet_name='Antennas', header=7)
        ind1 = base_file.set_index('Model')
        ind1 = base_file[['Model', 'Roadmap', 'Family']]
        #print(ind1)
        ind1.to_excel('Final.xlsx')
        file3 = pd.read_excel('Final.xlsx')
        file3= file3.replace(r'[,\"\']','', regex=True).replace(r'\s*([^\s]+)\s*', r'\1', regex=True)

for a in result:

        if a == c:
            base_file = pd.read_excel(a, sheet_name='Antennas', header=7)
            ind1 = base_file.set_index('Model')
            ind1 = base_file[['Model', 'Roadmap', 'Family']]
            ind1.to_excel('Final.xlsx')
        elif a != d:
            gates = ['Gate 0 Complete','Gate 1 Complete']
            file1 = pd.read_excel('Final.xlsx')
            file1= file1.replace(r'[,\"\']','', regex=True).replace(r'\s*([^\s]+)\s*', r'\1', regex=True)
            #print(file1)
            file = pd.read_excel(a, sheet_name='Timeline')
            #print(file)
            models = pd.DataFrame([['','']], columns=['Model', gates])
            for g in gates:
                z = file.loc[file['Task'] == g, 'Complete'].iloc[0]
                v=ntpath.basename(a)
                v = v[5:-5]
                models = pd.DataFrame([[v,z]], columns =['Model',g])
                file1 = pd.merge(file1, models, how='left', on='Model')
            file3 = pd.merge(file3, file1, how='left' ,['Model','Roadmap','Family'])
            file3.to_excel('new.xlsx')
</code>```

file3 is the file i have opened as the dataframe for the base file before the for loop. Let me know if anything is not clear.

答:
I assumed the following about your raw data:

STEP 0 - Part 1. You load df_base

STEP 0 - Part 2. You load df1, df2, etc. - one df for each sheet

Then my approach would be to perform the following steps (in order):

Vertically concatenate df for all sheets together into single DataFrame named df_sheets

merge df_base with df_sheets to get the desired output

Based on this,my approach would be:

```<code>import pandas as pd

# STEP 0.
cv = ['a','b','c','d']
nr = 4

# STEP 0 - Part 1. Load Base DF
cv = cv[:nr]
df_base = pd.DataFrame(zip(*[cv,['some_date']*nr,['some']*nr]),
                  columns=['Model','Roadmap','Family'])

# STEP 0 - Part 2. Load Sheets DataFrames
df_sheets = []
for alph in cv:
    df_sheet = pd.DataFrame(zip(*[[alph]*nr,['some_date_'+alph]*nr,['some_'+alph]*nr]),
                            columns=['Model','Gate0','Gate1'])
    df_sheets.append(df_sheet)
print('Base DF:\n{}' .format(df_base))

# STEP 1. Vertically conctenate all sheets DataFrames together
df_sheets = pd.concat(df_sheets, axis=0).reset_index(drop=True)
print('\nDataFrames for all sheets (vertically concatenated into single DataFrame):\n{}'
    .format(df_sheets))

# STEP 2. base INNER JOIN sheets USING ('Model')
ndf = df_base.merge(df_sheets, on='Model', how='inner')
print('\nOutput DataFrame:\n{}' .format(ndf))
</code>```

Output is:

```<code>Base DF:
  Model    Roadmap Family
0     a  some_date   some
1     b  some_date   some
2     c  some_date   some
3     d  some_date   some

DataFrames for all sheets (vertically concatenated into single DataFrame):
   Model        Gate0   Gate1
0      a  some_date_a  some_a
1      a  some_date_a  some_a
2      a  some_date_a  some_a
3      a  some_date_a  some_a
4      b  some_date_b  some_b
5      b  some_date_b  some_b
6      b  some_date_b  some_b
7      b  some_date_b  some_b
8      c  some_date_c  some_c
9      c  some_date_c  some_c
10     c  some_date_c  some_c
11     c  some_date_c  some_c
12     d  some_date_d  some_d
13     d  some_date_d  some_d
14     d  some_date_d  some_d
15     d  some_date_d  some_d

Output DataFrame:
   Model    Roadmap Family        Gate0   Gate1
0      a  some_date   some  some_date_a  some_a
1      a  some_date   some  some_date_a  some_a
2      a  some_date   some  some_date_a  some_a
3      a  some_date   some  some_date_a  some_a
4      b  some_date   some  some_date_b  some_b
5      b  some_date   some  some_date_b  some_b
6      b  some_date   some  some_date_b  some_b
7      b  some_date   some  some_date_b  some_b
8      c  some_date   some  some_date_c  some_c
9      c  some_date   some  some_date_c  some_c
10     c  some_date   some  some_date_c  some_c
11     c  some_date   some  some_date_c  some_c
12     d  some_date   some  some_date_d  some_d
13     d  some_date   some  some_date_d  some_d
14     d  some_date   some  some_date_d  some_d
15     d  some_date   some  some_date_d  some_d
</code>```

Is this what you are after?

Body:
I am trying to open files and derive 2 columns(1 row for each) from multiple spreadsheets and then merging them to a base spreadsheet.So, the base dataframe (derived from a spreadsheet, from which I only needed 3 columns)  is like this :

Model |  Roadmap | Family
a       08/12/17  ROW
b       08/14/17  MACRO
c       08/15/17  CONN
d       08/27/17  MACRO

The dataframes from the multiple spreadsheets(the model names are the spreadsheet names and they have multiple dates for each gate which i am deriving in multiple dataframes) and have this format :

    df1 (part1 -  the dataframe derived from the spreadsheet with model a for gate 0 ):
    Model   |  Gate 0
    a         02/01/18

df1 (Dataframe derived from the spreadsheet with model a for gate1):
        Model   |  Gate 1
        a         03/01/18

   df2 (part1):
    Model  |  Gate 0
    b       04/23/18

df2 (part1):
        Model  |  Gate 1
        b       05/23/18

The output it produces is :

Model |  Roadmap | Family | Gate 0_x  | Gate 1_x   | gate 0_y | Gate 1_y
a       08/12/17  ROW      02/01/18   03/01/18
b       08/14/17  MACRO                              04/23/18  05/23/18
c       08/15/17  CONN
d       08/27/17  MACRO

the output i want :

  Model |  Roadmap | Family | Gate 0   | Gate 1
   a       08/12/17  ROW     02/01/18   03/01/18
   b       08/14/17  MACRO    04/23/18  05/23/18
   ..

The following is the code i am using:

import glob
import pandas as pd
import re
import ntpath

extension = 'xlsx'
d='Final.xlsx'
c = 'Roadmap.xlsx'
dflist = []
z=[]
result = [i for i in glob.glob('*.{}'.format(extension))]

for b in result:
    if b==c:
        base_file = pd.read_excel(b, sheet_name='Antennas', header=7)
        ind1 = base_file.set_index('Model')
        ind1 = base_file[['Model', 'Roadmap', 'Family']]
        #print(ind1)
        ind1.to_excel('Final.xlsx')
        file3 = pd.read_excel('Final.xlsx')
        file3= file3.replace(r'[,\"\']','', regex=True).replace(r'\s*([^\s]+)\s*', r'\1', regex=True)

for a in result:

        if a == c:
            base_file = pd.read_excel(a, sheet_name='Antennas', header=7)
            ind1 = base_file.set_index('Model')
            ind1 = base_file[['Model', 'Roadmap', 'Family']]
            ind1.to_excel('Final.xlsx')
        elif a != d:
            gates = ['Gate 0 Complete','Gate 1 Complete']
            file1 = pd.read_excel('Final.xlsx')
            file1= file1.replace(r'[,\"\']','', regex=True).replace(r'\s*([^\s]+)\s*', r'\1', regex=True)
            #print(file1)
            file = pd.read_excel(a, sheet_name='Timeline')
            #print(file)
            models = pd.DataFrame([['','']], columns=['Model', gates])
            for g in gates:
                z = file.loc[file['Task'] == g, 'Complete'].iloc[0]
                v=ntpath.basename(a)
                v = v[5:-5]
                models = pd.DataFrame([[v,z]], columns =['Model',g])
                file1 = pd.merge(file1, models, how='left', on='Model')
            file3 = pd.merge(file3, file1, how='left' ,['Model','Roadmap','Family'])
            file3.to_excel('new.xlsx')

file3 is the file i have opened as the dataframe for the base file before the for loop. Let me know if anything is not clear.

Body:
I assumed the following about your raw data:

STEP 0 - Part 1. You load df_base

STEP 0 - Part 2. You load df1, df2, etc. - one df for each sheet

Then my approach would be to perform the following steps (in order):

Vertically concatenate df for all sheets together into single DataFrame named df_sheets

merge df_base with df_sheets to get the desired output

Based on this,my approach would be:

import pandas as pd

# STEP 0.
cv = ['a','b','c','d']
nr = 4

# STEP 0 - Part 1. Load Base DF
cv = cv[:nr]
df_base = pd.DataFrame(zip(*[cv,['some_date']*nr,['some']*nr]),
                  columns=['Model','Roadmap','Family'])

# STEP 0 - Part 2. Load Sheets DataFrames
df_sheets = []
for alph in cv:
    df_sheet = pd.DataFrame(zip(*[[alph]*nr,['some_date_'+alph]*nr,['some_'+alph]*nr]),
                            columns=['Model','Gate0','Gate1'])
    df_sheets.append(df_sheet)
print('Base DF:\n{}' .format(df_base))

# STEP 1. Vertically conctenate all sheets DataFrames together
df_sheets = pd.concat(df_sheets, axis=0).reset_index(drop=True)
print('\nDataFrames for all sheets (vertically concatenated into single DataFrame):\n{}'
    .format(df_sheets))

# STEP 2. base INNER JOIN sheets USING ('Model')
ndf = df_base.merge(df_sheets, on='Model', how='inner')
print('\nOutput DataFrame:\n{}' .format(ndf))

Output is:

Base DF:
  Model    Roadmap Family
0     a  some_date   some
1     b  some_date   some
2     c  some_date   some
3     d  some_date   some

DataFrames for all sheets (vertically concatenated into single DataFrame):
   Model        Gate0   Gate1
0      a  some_date_a  some_a
1      a  some_date_a  some_a
2      a  some_date_a  some_a
3      a  some_date_a  some_a
4      b  some_date_b  some_b
5      b  some_date_b  some_b
6      b  some_date_b  some_b
7      b  some_date_b  some_b
8      c  some_date_c  some_c
9      c  some_date_c  some_c
10     c  some_date_c  some_c
11     c  some_date_c  some_c
12     d  some_date_d  some_d
13     d  some_date_d  some_d
14     d  some_date_d  some_d
15     d  some_date_d  some_d

Output DataFrame:
   Model    Roadmap Family        Gate0   Gate1
0      a  some_date   some  some_date_a  some_a
1      a  some_date   some  some_date_a  some_a
2      a  some_date   some  some_date_a  some_a
3      a  some_date   some  some_date_a  some_a
4      b  some_date   some  some_date_b  some_b
5      b  some_date   some  some_date_b  some_b
6      b  some_date   some  some_date_b  some_b
7      b  some_date   some  some_date_b  some_b
8      c  some_date   some  some_date_c  some_c
9      c  some_date   some  some_date_c  some_c
10     c  some_date   some  some_date_c  some_c
11     c  some_date   some  some_date_c  some_c
12     d  some_date   some  some_date_d  some_d
13     d  some_date   some  some_date_d  some_d
14     d  some_date   some  some_date_d  some_d
15     d  some_date   some  some_date_d  some_d

Is this what you are after?


问:
Publishing policy through Wso2 EntitlementPolicyAdminService
So i am trying to add some policies to the PDP of wso2. I did manage to add policies using this code

```<code> public function addPolicy($policy, $policyId = '')
    {
        $this->soapClient->__soapCall(
            'addPolicy',
            [
                'parameters' => [
                    'policyDTO' => [
                        'policyId' => $policyId,
                        'policy' => $policy
                        ]
                    ]
            ]
        );
    }
</code>```

Then i want to publish the policy i just added to the PDP using this code

```<code>public function publishPolicy($policyId)
    {
        $this->soapClient->__soapCall(
            'publishToPDP',
            [
                'parameters' => [
                    'verificationCode' => $policyId,
                    'enabled' => true,
                    'order' => 1
                ]
            ]
        );
    }
</code>```

However the policy is not published to PDP. The server seems to receive the request but do nothing. Am i doing something wrong? How should this request be formed?

I have also tried the publishPolicies SoapCall but no luck...

答:
Its seems that the publishToPDP is not really active. What actually worked is using the addPolicy with some additional attributes like promote.

Here is an example of how it worked for me

```<code>$this->soapClient->__soapCall(
            'addPolicy',
            [
                'parameters' => [
                    'policyDTO' => [
                        'policyId' => $policyId,
                        'policy' => $policy,
                        'version' => $version,
                        'policyOrder' => $policyOrder,
                        'active' =>  true,
                        'promote' => true
                        ]
                    ]
            ]
        );
</code>```

Using these attributes the policy is added and is published to PDP.

Body:
So i am trying to add some policies to the PDP of wso2. I did manage to add policies using this code

 public function addPolicy($policy, $policyId = '')
    {
        $this->soapClient->__soapCall(
            'addPolicy',
            [
                'parameters' => [
                    'policyDTO' => [
                        'policyId' => $policyId,
                        'policy' => $policy
                        ]
                    ]
            ]
        );
    }

Then i want to publish the policy i just added to the PDP using this code

public function publishPolicy($policyId)
    {
        $this->soapClient->__soapCall(
            'publishToPDP',
            [
                'parameters' => [
                    'verificationCode' => $policyId,
                    'enabled' => true,
                    'order' => 1
                ]
            ]
        );
    }

However the policy is not published to PDP. The server seems to receive the request but do nothing. Am i doing something wrong? How should this request be formed?

I have also tried the publishPolicies SoapCall but no luck...

Body:
Its seems that the publishToPDP is not really active. What actually worked is using the addPolicy with some additional attributes like promote.

Here is an example of how it worked for me

$this->soapClient->__soapCall(
            'addPolicy',
            [
                'parameters' => [
                    'policyDTO' => [
                        'policyId' => $policyId,
                        'policy' => $policy,
                        'version' => $version,
                        'policyOrder' => $policyOrder,
                        'active' =>  true,
                        'promote' => true
                        ]
                    ]
            ]
        );

Using these attributes the policy is added and is published to PDP.


问:
What is the recommended way to show a badge (a number) on the Application Icon?
I am creating a messaging mobile app using Xamarin. The app is expected to run on both Android and IOS. I need to implement notifications for this app in order to to show total number of unread messages over the application icon.

I am thinking of the following options:

Should I create a Background Service to do long pooling and call the
server to get the total number of unread messages and show over the
app icon?

Or create a Push Notification Service which pushes the total number of unread
messages to the clients?

Please advise if there is any other recommended approach to accomplish this.

Thanks,

Arfan

答:
iOS won't allow and encourage background services except in few scenarios like health kit data sync etc., So the clear option to go for this by push notifications. Please go with the second approach.

When you are sending a push notification data in JSON format like below, it will update:

```<code>{
    "aps": {
        "alert": "Test Push Notification",
        "sound": "yourSound.aiff",
        "Badge": "desiredNumber"
    }
}
</code>```

Body:
iOS won't allow and encourage background services except in few scenarios like health kit data sync etc., So the clear option to go for this by push notifications. Please go with the second approach.

When you are sending a push notification data in JSON format like below, it will update:

{
    "aps": {
        "alert": "Test Push Notification",
        "sound": "yourSound.aiff",
        "Badge": "desiredNumber"
    }
}


答:
Since the Gamescene doesn't contain the fps_counter textview, modify your abstract Scene and class extensions so that you can pass a reference to textview.

```<code>public abstract class Scene extends SurfaceView implements Runnable {

    Handler uiHandler;
    Thread thread = null;
    TextView textView;
    public Scene(Context context, Handler uiHandler, TextView textView) {
        super(context);
        this.uiHandler = uiHandler;
        this.textView = textView;
    }

    @Override
    public void run() {
        uiHandler.post(() -> {
            textView.setText("hello");
        });
    }

    public void resume() {
        thread = new Thread(this);
        thread.start();
    }
</code>```

Then create the GameScene with that 3rd parameter of the textview :

```<code>TextView textView = findViewById(R.id.fps_counter);
// no need to use getApplicationContext(), you may use this (a reference to "mainActivity")
gameScene = new GameScene(this, uiHandler, textView);
</code>```

Title: thread issue using post

Body:
Since the Gamescene doesn't contain the fps_counter textview, modify your abstract Scene and class extensions so that you can pass a reference to textview.

public abstract class Scene extends SurfaceView implements Runnable {

    Handler uiHandler;
    Thread thread = null;
    TextView textView;
    public Scene(Context context, Handler uiHandler, TextView textView) {
        super(context);
        this.uiHandler = uiHandler;
        this.textView = textView;
    }

    @Override
    public void run() {
        uiHandler.post(() -> {
            textView.setText("hello");
        });
    }

    public void resume() {
        thread = new Thread(this);
        thread.start();
    }

Then create the GameScene with that 3rd parameter of the textview :

TextView textView = findViewById(R.id.fps_counter);
// no need to use getApplicationContext(), you may use this (a reference to "mainActivity")
gameScene = new GameScene(this, uiHandler, textView);


问:
Resolve promise in abstract parent before $stateChangeStart fires
I'm attempting to resolve some server-side data in an abstract parent state before the Home child state is loaded. I want to make sure I have the user's full name for examination in the state's data.rule function. However, using console.log statements, I can see the userFullName prints as an empty string to the console before the "done" statement in the factory.privilegeData method.

EDIT

The data in the parent resolve is security data from the server that needs to be available globally before any controllers are initialized. Only one child state is listed here (for the sake of readability), but all states, outside of login are children of the abstract parent. Once the parent's resolves are complete the data is stored in the $rootScope and used to determine access rights via the data.rule function in each state.

config.js

UPDATE: per answer below I've updated the parent/child states as such, howeve I'm still running into the same issue:

```<code>        .state('app', {
            url:'',
            abstract: true,
            template: '<div ui-view class="slide-animation"></div>',
            resolve:{
                privileges: ['$q', 'privilegesService', function($q, privilegesService){
                    console.log('from parent resolve');
                    return privilegesService.getPrivileges()
                                            .then(privilegesService.privilegesData)
                                            .catch(privilegesService.getPrivilegesError);
                }]
            }
        })
        .state('app.home', {
            url: '/home',
            templateUrl: 'app/components/home/home.html',
            controller: 'HomeController',
            controllerAs: 'vm',
            parent: 'app',
            resolvePolicy: {when:'LAZY', async: 'WAIT'},
            authenticate: true,
            data:{
                rule: function($rootScope){
                    console.log("from home state data rule");
                    return true;
                }
            }
        })
</code>```

privilegesService.js

```<code>factory.getPrivileges = function () {
    console.log('from server call');
    var queryString = "&cmd=privilege&action=user";
    return $http.get(config.serviceBaseUri + queryString);
};

factory.privilegesData = function(priv){
    console.log('from privilege data');
    if(priv && priv.data) {
        $rootScope.userFullName = priv.data.firstName + ' ' + priv.data.lastName;
    }
        console.log('done');
};
</code>```

Based on the console statments above I'm getting the following output. I need the from home state data rule to occur last...

...since I'm using the the results of the data.rule function for authorization for each state. Below is the $stateChangeStart from my .run method

app.route.js

```<code>    $rootScope.$on("$stateChangeStart", function (event, toState, toParams, fromState, fromParams) {
        if(toState.authenticate){
            if(authService.authKeyExists()){
                if(toState.data.rule($rootScope)){
                    navigationService.addNavObject("activity", {
                        summary : "Page navigation",
                        page : $location.absUrl().replace("#/", "")
                    });
                } else {
                    $state.go('app.home');
                }
            } else {
                event.preventDefault();
                $state.go('login');
            }
        }
    });
</code>```

答:
The child states need the parent state as a dependency in order for it to wait to load, even if its not used directly. Source

you have to try something like the following instead :

```<code>.state('app.home', {
    url: '/home',
    templateUrl: 'app/components/home/home.html',
    controller: 'HomeController',
    controllerAs: 'vm',
    parent: 'app',
    authenticate: true,
    data:{
        rule: function($rootScope){
            console.log($rootScope.userFullName);
            return true;
        }
    }
})
</code>```

You can use the property resolvepolicy and set it to LAZY as well, a state's LAZY resolves will wait for the parent state's resolves to finish before beginning to load.

Body:
I'm attempting to resolve some server-side data in an abstract parent state before the Home child state is loaded. I want to make sure I have the user's full name for examination in the state's data.rule function. However, using console.log statements, I can see the userFullName prints as an empty string to the console before the "done" statement in the factory.privilegeData method.

EDIT

The data in the parent resolve is security data from the server that needs to be available globally before any controllers are initialized. Only one child state is listed here (for the sake of readability), but all states, outside of login are children of the abstract parent. Once the parent's resolves are complete the data is stored in the $rootScope and used to determine access rights via the data.rule function in each state.

config.js

UPDATE: per answer below I've updated the parent/child states as such, howeve I'm still running into the same issue:

        .state('app', {
            url:'',
            abstract: true,
            template: '

',
            resolve:{
                privileges: ['$q', 'privilegesService', function($q, privilegesService){
                    console.log('from parent resolve');
                    return privilegesService.getPrivileges()
                                            .then(privilegesService.privilegesData)
                                            .catch(privilegesService.getPrivilegesError);
                }]
            }
        })
        .state('app.home', {
            url: '/home',
            templateUrl: 'app/components/home/home.html',
            controller: 'HomeController',
            controllerAs: 'vm',
            parent: 'app',
            resolvePolicy: {when:'LAZY', async: 'WAIT'},
            authenticate: true,
            data:{
                rule: function($rootScope){
                    console.log("from home state data rule");
                    return true;
                }
            }
        })

privilegesService.js

factory.getPrivileges = function () {
    console.log('from server call');
    var queryString = "&cmd=privilege&action=user";
    return $http.get(config.serviceBaseUri + queryString);
};

factory.privilegesData = function(priv){
    console.log('from privilege data');
    if(priv && priv.data) {
        $rootScope.userFullName = priv.data.firstName + ' ' + priv.data.lastName;
    }
        console.log('done');
};

Based on the console statments above I'm getting the following output. I need the from home state data rule to occur last...

...since I'm using the the results of the data.rule function for authorization for each state. Below is the $stateChangeStart from my .run method

app.route.js

    $rootScope.$on("$stateChangeStart", function (event, toState, toParams, fromState, fromParams) {
        if(toState.authenticate){
            if(authService.authKeyExists()){
                if(toState.data.rule($rootScope)){
                    navigationService.addNavObject("activity", {
                        summary : "Page navigation",
                        page : $location.absUrl().replace("#/", "")
                    });
                } else {
                    $state.go('app.home');
                }
            } else {
                event.preventDefault();
                $state.go('login');
            }
        }
    });

Body:
The child states need the parent state as a dependency in order for it to wait to load, even if its not used directly. Source

you have to try something like the following instead :

.state('app.home', {
    url: '/home',
    templateUrl: 'app/components/home/home.html',
    controller: 'HomeController',
    controllerAs: 'vm',
    parent: 'app',
    authenticate: true,
    data:{
        rule: function($rootScope){
            console.log($rootScope.userFullName);
            return true;
        }
    }
})

You can use the property resolvepolicy and set it to LAZY as well, a state's LAZY resolves will wait for the parent state's resolves to finish before beginning to load.


问:
Joining a string with input fields = one value
how can I get this result as a value of LUC-1701-000005 field I made ..

I get the current value from one field ($value = $_POST['wpuef_options']['c26'];), but I want to make it easier for customers to not enter those LUCs ... than just numbers..

current code looks like this ..

```<code>for($I=0; $I<= 5; $I++){
if($I == 0){
    $value = $_POST['wpuef_options']['c26'];
}
else if($I == 1){
    $value = $_POST['wpuef_options']['c30'];
}
else if($I == 2){
    $value = $_POST['wpuef_options']['c34'];
}
else if($I == 3){
    $value = $_POST['wpuef_options']['c44'];
}
else if($I == 4){
    $value = $_POST['wpuef_options']['c50'];
}
</code>```

this is something I need ..but this is not correct ..

```<code>$value = "LUC-" + $_POST['wpuef_options']['c26'] + "-" + $_POST['wpuef_options']['c23'];
</code>```

答:
Try this:

```<code>$value = "LUC-" . $_POST['wpuef_options']['c26'] . "-" . $_POST['wpuef_options']['c23'];
</code>```

You are using + for concatenation, which is wrong, in PHP it is just . .

Body:
how can I get this result as a value of LUC-1701-000005 field I made ..

I get the current value from one field ($value = $_POST['wpuef_options']['c26'];), but I want to make it easier for customers to not enter those LUCs ... than just numbers..

current code looks like this ..

for($I=0; $I<= 5; $I++){
if($I == 0){
    $value = $_POST['wpuef_options']['c26'];
}
else if($I == 1){
    $value = $_POST['wpuef_options']['c30'];
}
else if($I == 2){
    $value = $_POST['wpuef_options']['c34'];
}
else if($I == 3){
    $value = $_POST['wpuef_options']['c44'];
}
else if($I == 4){
    $value = $_POST['wpuef_options']['c50'];
}

this is something I need ..but this is not correct ..

$value = "LUC-" + $_POST['wpuef_options']['c26'] + "-" + $_POST['wpuef_options']['c23'];

Body:
Try this:

$value = "LUC-" . $_POST['wpuef_options']['c26'] . "-" . $_POST['wpuef_options']['c23'];

You are using + for concatenation, which is wrong, in PHP it is just . .


问:
crystal report parameters
I use the following code to pass parameters into a CR

```<code>    //  Reuse myDiscreteValue, and assign second country
    myParam = new ParameterField();
    myDiscreteValue = new ParameterDiscreteValue();
    myParam.Name = "@toDate";
    myDiscreteValue.Value = RmtUtility.Utility.DisplayDate(toDate);
    myParam.CurrentValues.Add(myDiscreteValue);
    myParams.Add(myParam);
</code>```

I get an error message "Missing Parameter Value" when I tried to export the document using CR Option.

:(

答:
Try clearing and then setting the values of the parameters within the Report object.

Something like this:

```<code>ParameterDiscreteValue paramDV = new ParameterDiscreteValue();
paramDV.Value = RmtUtility.Utility.DisplayDate(toDate);
report.ParameterFields["@toDate"].CurrentValues.Clear();
report.ParameterFields["@toDate"].DefaultValues.Clear();
report.ParameterFields["@toDate"].CurrentValues.Add(paramDV);
</code>```

Note: report being your Crystal Report Document

Title: crystal report parameters

Body:
I use the following code to pass parameters into a CR

    //  Reuse myDiscreteValue, and assign second country
    myParam = new ParameterField();
    myDiscreteValue = new ParameterDiscreteValue();
    myParam.Name = "@toDate";
    myDiscreteValue.Value = RmtUtility.Utility.DisplayDate(toDate);
    myParam.CurrentValues.Add(myDiscreteValue);
    myParams.Add(myParam);

I get an error message "Missing Parameter Value" when I tried to export the document using CR Option.

:(

Body:
Try clearing and then setting the values of the parameters within the Report object.

Something like this:

ParameterDiscreteValue paramDV = new ParameterDiscreteValue();
paramDV.Value = RmtUtility.Utility.DisplayDate(toDate);
report.ParameterFields["@toDate"].CurrentValues.Clear();
report.ParameterFields["@toDate"].DefaultValues.Clear();
report.ParameterFields["@toDate"].CurrentValues.Add(paramDV);

Note: report being your Crystal Report Document


问:
sql-query, find and replace with this particular code
I need to understand the following SQL query and would like to ask if anybody could explain it to me a bit more in detail (like the xml path) as well as update it with a replace element?
So I want to find all values with BlaBlaBlaBla and replace them with HaHaHaHa instead. At the moment the query is finding all values of BlaBlaBlaBla only. </p>

```<code>DECLARE @searchstring  NVARCHAR(255)
SET @searchstring = '%BlaBlaBlaBla%'

DECLARE @sql NVARCHAR(max)

SELECT @sql = STUFF((
  SELECT
    ' UNION ALL SELECT ''' + TABLE_SCHEMA + '.' + TABLE_NAME + ''' AS tbl, ''' + COLUMN_NAME + ''' AS col, [' + COLUMN_NAME + '] AS val' +
    ' FROM [' + TABLE_SCHEMA + '].[' + TABLE_NAME + '] WHERE [' + COLUMN_NAME + '] LIKE ''' + @searchstring + ''''
    FROM INFORMATION_SCHEMA.COLUMNS
    WHERE DATA_TYPE in ('nvarchar', 'varchar', 'char', 'ntext') FOR XML PATH('')) ,1, 11, '')

Exec (@sql)
</code>```

答:
I believe that the XML PATH is a trick to get the strings to all concatenate together.

You could change it to REPLACE with something like this:

```<code>SELECT @sql =
SELECT
    ' UPDATE ' + QUOTENAME(TABLE_SCHEMA) + '.' + QUOTENAME(TABLE_NAME) + '
      SET ' + QUOTENAME(COLUMN_NAME) + ' = REPLACE(' + QUOTENAME(COLUMN_NAME) + ', ''' + @search_string + ''', ' + ', ''' + @replace_string + '''
      WHERE ' + QUOTENAME(COLUMN_NAME) + ' LIKE ''' + @searchstring + ''''
FROM INFORMATION_SCHEMA.COLUMNS
WHERE
    DATA_TYPE in ('nvarchar', 'varchar', 'char', 'ntext') FOR XML PATH('')

EXEC(@sql)
</code>```

Some caveats:

I haven't tested this. When you're generating code like this it's very easy to make minor errors with all of the start and end quotes, etc. I would print out the SQL and check it, repeating as necessary until you get the output SQL correct.

Also, this is generally not a good idea. If your database is large and/or has a large number of tables then performance is going to be miserable. You should usually do the analysis of where you think this sort of data is going to appear and write code that will correct it as necessary. The fact that data elements are buried in strings throughout your data is concerning.

Finally, be aware that this might easily update additional data that you didn't intend to update. If you try to update "123" with "456" and there's a string out there that is "My ID is 1234" it's going to become "My ID is 4564".

BTW, the QUOTENAME function is a way of enclosing your table and column names in [ and ], but if the quote character is changed in a DB implementation it should still work.

Body:
I need to understand the following SQL query and would like to ask if anybody could explain it to me a bit more in detail (like the xml path) as well as update it with a replace element?
So I want to find all values with BlaBlaBlaBla and replace them with HaHaHaHa instead. At the moment the query is finding all values of BlaBlaBlaBla only.

DECLARE @searchstring  NVARCHAR(255)
SET @searchstring = '%BlaBlaBlaBla%'

DECLARE @sql NVARCHAR(max)

SELECT @sql = STUFF((
  SELECT
    ' UNION ALL SELECT ''' + TABLE_SCHEMA + '.' + TABLE_NAME + ''' AS tbl, ''' + COLUMN_NAME + ''' AS col, [' + COLUMN_NAME + '] AS val' +
    ' FROM [' + TABLE_SCHEMA + '].[' + TABLE_NAME + '] WHERE [' + COLUMN_NAME + '] LIKE ''' + @searchstring + ''''
    FROM INFORMATION_SCHEMA.COLUMNS
    WHERE DATA_TYPE in ('nvarchar', 'varchar', 'char', 'ntext') FOR XML PATH('')) ,1, 11, '')

Exec (@sql)

Body:
I believe that the XML PATH is a trick to get the strings to all concatenate together.

You could change it to REPLACE with something like this:

SELECT @sql =
SELECT
    ' UPDATE ' + QUOTENAME(TABLE_SCHEMA) + '.' + QUOTENAME(TABLE_NAME) + '
      SET ' + QUOTENAME(COLUMN_NAME) + ' = REPLACE(' + QUOTENAME(COLUMN_NAME) + ', ''' + @search_string + ''', ' + ', ''' + @replace_string + '''
      WHERE ' + QUOTENAME(COLUMN_NAME) + ' LIKE ''' + @searchstring + ''''
FROM INFORMATION_SCHEMA.COLUMNS
WHERE
    DATA_TYPE in ('nvarchar', 'varchar', 'char', 'ntext') FOR XML PATH('')

EXEC(@sql)

Some caveats:

I haven't tested this. When you're generating code like this it's very easy to make minor errors with all of the start and end quotes, etc. I would print out the SQL and check it, repeating as necessary until you get the output SQL correct.

Also, this is generally not a good idea. If your database is large and/or has a large number of tables then performance is going to be miserable. You should usually do the analysis of where you think this sort of data is going to appear and write code that will correct it as necessary. The fact that data elements are buried in strings throughout your data is concerning.

Finally, be aware that this might easily update additional data that you didn't intend to update. If you try to update "123" with "456" and there's a string out there that is "My ID is 1234" it's going to become "My ID is 4564".

BTW, the QUOTENAME function is a way of enclosing your table and column names in [ and ], but if the quote character is changed in a DB implementation it should still work.


问:
How to Execute AfterMehtod for only one Test method
I have to Test methods in my code and I wan to execute AfterMehtod for only one. Anybody have any idea how do this?

Here is My code:

```<code>package Demo;

import java.util.concurrent.TimeUnit;

import library.Utility;

import org.openqa.selenium.By;
import org.testng.ITestResult;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.Test;

import Pages.custom_actions_page;

import com.relevantcodes.extentreports.ExtentReports;
import com.relevantcodes.extentreports.ExtentTest;
import com.relevantcodes.extentreports.LogStatus;

public class Custom_Actions extends start {

    ExtentReports report;
    ExtentTest logger;
    String driverPath = "D:\\geckodriver-v0.16.1-win64\\geckodriver.exe";

    @Test()
    public void signin() throws Exception {

        // To Locate the Username field
        driver.manage().timeouts().implicitlyWait(3, TimeUnit.SECONDS);
        driver.findElement(By.id("username")).sendKeys("admin");

        // To locate the Password field
        driver.manage().timeouts().implicitlyWait(3, TimeUnit.SECONDS);
        driver.findElement(By.id("password")).sendKeys("admin123");

        // Click on Login button
        driver.manage().timeouts().implicitlyWait(3, TimeUnit.SECONDS);
        driver.findElement(By.id("submit")).click();

    }

    @Test(dependsOnMethods = { "signin" })
    public void create_custom_action() {
        report = new ExtentReports("D:/Reports/Report.html");

        logger = report.startTest("Create Custom Action");

        new custom_actions_page(driver).submit();

        new custom_actions_page(driver).admin();

        new custom_actions_page(driver).custom_ac();

        new custom_actions_page(driver).createnew();

        new custom_actions_page(driver).nameAs("fortesting").descriptionAs(
                "description");

        new custom_actions_page(driver).category();

        new custom_actions_page(driver).assetsubtype();

        new custom_actions_page(driver).assettype();

        new custom_actions_page(driver).flintnameAs("hello:example.rb");

        new custom_actions_page(driver).submit_butto();

        new custom_actions_page(driver).Save_Button();

        logger.log(LogStatus.PASS, "Custom Action Created Successfully");
    }

    @AfterMethod()
    public void tearDown(ITestResult result) {

        // Here will compare if test is failing then only it will enter into if
        // condition
        if (ITestResult.FAILURE == result.getStatus()) {
            try {

                Utility.captureScreenshot(driver, "CustomActionFail.png");

            } catch (Exception e) {
                System.out.println("Exception while taking screenshot "
                        + e.getMessage());
            }
        }

        report.endTest(logger);
        report.flush();
        driver.close();
    }}
</code>```

答: @AfterMethod is designed to make your life easier when you need to execute a the same block of code after each test without having to duplicate it in each test. So if you need it to execute only after one test, just embed it into that @Test method and remove the @AfterMethod annotated method.

Body:
I have to Test methods in my code and I wan to execute AfterMehtod for only one. Anybody have any idea how do this?

Here is My code:

package Demo;

import java.util.concurrent.TimeUnit;

import library.Utility;

import org.openqa.selenium.By;
import org.testng.ITestResult;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.Test;

import Pages.custom_actions_page;

import com.relevantcodes.extentreports.ExtentReports;
import com.relevantcodes.extentreports.ExtentTest;
import com.relevantcodes.extentreports.LogStatus;

public class Custom_Actions extends start {

    ExtentReports report;
    ExtentTest logger;
    String driverPath = "D:\\geckodriver-v0.16.1-win64\\geckodriver.exe";

    @Test()
    public void signin() throws Exception {

        // To Locate the Username field
        driver.manage().timeouts().implicitlyWait(3, TimeUnit.SECONDS);
        driver.findElement(By.id("username")).sendKeys("admin");

        // To locate the Password field
        driver.manage().timeouts().implicitlyWait(3, TimeUnit.SECONDS);
        driver.findElement(By.id("password")).sendKeys("admin123");

        // Click on Login button
        driver.manage().timeouts().implicitlyWait(3, TimeUnit.SECONDS);
        driver.findElement(By.id("submit")).click();

    }

    @Test(dependsOnMethods = { "signin" })
    public void create_custom_action() {
        report = new ExtentReports("D:/Reports/Report.html");

        logger = report.startTest("Create Custom Action");

        new custom_actions_page(driver).submit();

        new custom_actions_page(driver).admin();

        new custom_actions_page(driver).custom_ac();

        new custom_actions_page(driver).createnew();

        new custom_actions_page(driver).nameAs("fortesting").descriptionAs(
                "description");

        new custom_actions_page(driver).category();

        new custom_actions_page(driver).assetsubtype();

        new custom_actions_page(driver).assettype();

        new custom_actions_page(driver).flintnameAs("hello:example.rb");

        new custom_actions_page(driver).submit_butto();

        new custom_actions_page(driver).Save_Button();

        logger.log(LogStatus.PASS, "Custom Action Created Successfully");
    }

    @AfterMethod()
    public void tearDown(ITestResult result) {

        // Here will compare if test is failing then only it will enter into if
        // condition
        if (ITestResult.FAILURE == result.getStatus()) {
            try {

                Utility.captureScreenshot(driver, "CustomActionFail.png");

            } catch (Exception e) {
                System.out.println("Exception while taking screenshot "
                        + e.getMessage());
            }
        }

        report.endTest(logger);
        report.flush();
        driver.close();
    }}


问:
Simple way to measure cell execution time in ipython notebook
I would like to get the time spent on the cell execution in addition to the original output from cell.

To this end, I tried %%timeit -r1 -n1 but it doesn't expose the variable defined within cell.

%%time works for cell which only contains 1 statement.

```<code>In[1]: %%time
       1
CPU times: user 4 µs, sys: 0 ns, total: 4 µs
Wall time: 5.96 µs
Out[1]: 1

In[2]: %%time
       # Notice there is no out result in this case.
       x = 1
       x
CPU times: user 3 µs, sys: 0 ns, total: 3 µs
Wall time: 5.96 µs
</code>```

What's the best way to do it?

Update

I have been using Execute Time in Nbextension for quite some time now. It is great.

Update 2021-03

As of now, this is the correct answer. Essentially, %%time and %%timeit both now work as one would expect.

答:
I simply added %%time at the beginning of the cell and got the time.  You may use the same on Jupyter Spark cluster/ Virtual environment using the same. Just add %%time at the top of the cell and you will get the output. On spark cluster using Jupyter, I added to the top of the cell and I got output like below:-

```<code>[1]  %%time
     import pandas as pd
     from pyspark.ml import Pipeline
     from pyspark.ml.classification import LogisticRegression
     import numpy as np
     .... code ....

Output :-

CPU times: user 59.8 s, sys: 4.97 s, total: 1min 4s
Wall time: 1min 18s
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I would like to get the time spent on the cell execution in addition to the original output from cell.

To this end, I tried %%timeit -r1 -n1 but it doesn't expose the variable defined within cell.

%%time works for cell which only contains 1 statement.

In[1]: %%time
       1
CPU times: user 4 µs, sys: 0 ns, total: 4 µs
Wall time: 5.96 µs
Out[1]: 1

In[2]: %%time
       # Notice there is no out result in this case.
       x = 1
       x
CPU times: user 3 µs, sys: 0 ns, total: 3 µs
Wall time: 5.96 µs

What's the best way to do it?

Update

I have been using Execute Time in Nbextension for quite some time now. It is great.

Update 2021-03

As of now, this is the correct answer. Essentially, %%time and %%timeit both now work as one would expect.

Body:
I simply added %%time at the beginning of the cell and got the time.  You may use the same on Jupyter Spark cluster/ Virtual environment using the same. Just add %%time at the top of the cell and you will get the output. On spark cluster using Jupyter, I added to the top of the cell and I got output like below:-

[1]  %%time
     import pandas as pd
     from pyspark.ml import Pipeline
     from pyspark.ml.classification import LogisticRegression
     import numpy as np
     .... code ....

Output :-

CPU times: user 59.8 s, sys: 4.97 s, total: 1min 4s
Wall time: 1min 18s


问:
Triggering Fancybox in dynamic content
My  tag which has the call for the Fancybox function will load after calling from ajax. Upon clicking on the link, the modal window wont show up. I tried using the  in a static way and it works, but not through dynamic code. I also noticed that upon viewing "Source" in my ie browser, the tag is not present. Any help? Thanks!!

this code will be created dynamically after calling ajax from the server side (I'm using java). Im using class as my link to the jquery function because the tags can be several instances with the same class name:

```<code> <a class="link" href="#task" title="Details">View details</a>
    <div style="display: none;">
        <div id="task" style="width:400px;height:100px;overflow:auto;">
            some data from the server.
        </div>
    </div>
</code>```

This is my fancybox function:

```<code>$("a.link").fancybox({
        'titlePosition' : 'inside',
        'transitionIn'  : 'none',
        'transitionOut' : 'none'
});
</code>```

答: You might have to use livequery in this situation

Title: Triggering Fancybox in dynamic content

Body:
My  tag which has the call for the Fancybox function will load after calling from ajax. Upon clicking on the link, the modal window wont show up. I tried using the  in a static way and it works, but not through dynamic code. I also noticed that upon viewing "Source" in my ie browser, the tag is not present. Any help? Thanks!!

this code will be created dynamically after calling ajax from the server side (I'm using java). Im using class as my link to the jquery function because the tags can be several instances with the same class name:

 View details

            some data from the server.

This is my fancybox function:

$("a.link").fancybox({
        'titlePosition' : 'inside',
        'transitionIn'  : 'none',
        'transitionOut' : 'none'
});


问:
Flow typing reducer produces no errors
I'm new to flowtypes and want to ask for help typing this reducer.

```<code>// @flow

type State = {
  [id: string]: boolean
};

type Action = { type: 'SET_ID', id: number, someValue: string };

function reducer(state: State, action: Action): State {
  switch (action.type) {
    case 'SET_ID':
      const { id, someValue } = action;
      return { [id]: someValue };
    default:
      (action: empty);
      return state;
  }
}
</code>```

I'm passing action with id as a number and someValue as a string, but state id should be string and someValue should be boolean. Flow produces 0 errors. Any ideas ?

Thanks!

答:
I've been using flow for a little while, not a pro at it yet, but I think I might be able to help out. What I'm doing below is while ID is a variable, I don't think it needs to be assigned a key - its just a string. Its only assigned a variable because you are passing it into a function and using it - so all it ever needs to be is a string. This way if you pass it a number, it should now hopefully throw an error so you can decide if you want to convert the number into a string first, or change the initial item to be a number first instead of a string in the state type.

Then someValue is the value of the key(string), and it should also be a string and not a boolean.

```<code>type State = {
  [string]: string
};

type Action = { type: 'SET_ID', id: number, someValue: string };

function reducer(state: State, action: Action): State {
  switch (action.type) {
    case 'SET_ID':
      const { id, someValue } = action;
      return { [id.toString()]: someValue };
    default:
      (action: empty);
      return state;
  }
}
</code>```

And an example of the returned data from the reducer might be this:

```<code>{'1231413413324': 'my new value from the reducer'}
</code>```

Title: Flow typing reducer produces no errors

Body:
I'm new to flowtypes and want to ask for help typing this reducer.

// @flow

type State = {
  [id: string]: boolean
};

type Action = { type: 'SET_ID', id: number, someValue: string };

function reducer(state: State, action: Action): State {
  switch (action.type) {
    case 'SET_ID':
      const { id, someValue } = action;
      return { [id]: someValue };
    default:
      (action: empty);
      return state;
  }
}

I'm passing action with id as a number and someValue as a string, but state id should be string and someValue should be boolean. Flow produces 0 errors. Any ideas ?

Thanks!

Body:
I've been using flow for a little while, not a pro at it yet, but I think I might be able to help out. What I'm doing below is while ID is a variable, I don't think it needs to be assigned a key - its just a string. Its only assigned a variable because you are passing it into a function and using it - so all it ever needs to be is a string. This way if you pass it a number, it should now hopefully throw an error so you can decide if you want to convert the number into a string first, or change the initial item to be a number first instead of a string in the state type.

Then someValue is the value of the key(string), and it should also be a string and not a boolean.

type State = {
  [string]: string
};

type Action = { type: 'SET_ID', id: number, someValue: string };

function reducer(state: State, action: Action): State {
  switch (action.type) {
    case 'SET_ID':
      const { id, someValue } = action;
      return { [id.toString()]: someValue };
    default:
      (action: empty);
      return state;
  }
}

And an example of the returned data from the reducer might be this:

{'1231413413324': 'my new value from the reducer'}