问:
Optimizing renderscript summation of row and column cells
Any advise in optimizing the following code? The code first grayscales, inverts and then thresholds the image (code not included, because it is trivial). It then sums the elements of each row and column (all elements are either 1 or 0). It then finds the row and column index of the row and column with the highest value.

The code is supposed to find the centroid of the image and it works, but I want to make it faster

I'm developing for API 23, so a reduction kernel can not be used.

Java snippet:

```<code>private int[] sumValueY = new int[640];
private int[] sumValueX = new int[480];

rows_indices_alloc = Allocation.createSized( rs, Element.I32(rs), height, Allocation.USAGE_SCRIPT);
col_indices_alloc = Allocation.createSized( rs, Element.I32(rs), width, Allocation.USAGE_SCRIPT);

public RenderscriptProcessor(RenderScript rs, int width, int height)
{
   mScript.set_gIn(mIntermAllocation);

   mScript.forEach_detectX(rows_indices_alloc);
   mScript.forEach_detectY(col_indices_alloc);

   rows_indices_alloc.copyTo(sumValueX);
   col_indices_alloc.copyTo(sumValueY);
 }
</code>```

Renderscript.rs snippet:

```<code>#pragma version(1)
#pragma rs java_package_name(org.gearvrf.renderscript)
#include "rs_debug.rsh"
#pragma rs_fp_relaxed

const int mImageWidth=640;
const int mImageHeight=480;

int32_t maxsX=-1;
int32_t maxIndexX;

int32_t maxsY=-1;
int32_t maxIndexY;

rs_allocation gIn;

void detectX(int32_t v_in, int32_t x, int32_t y) {

    int32_t sum=0;

    for ( int i = 0; i < (mImageWidth); i++) {

       float4 f4 = rsUnpackColor8888(rsGetElementAt_uchar4(gIn, i, x));
       sum+=(int)f4.r;
    }

    if((sum>maxsX)){

        maxsX=sum;
        maxIndexX = x;
    }
}

void detectY(int32_t v_in, int32_t x, int32_t y) {

     int32_t sum=0;

     for ( int i = 0; i < (mImageHeight); i++) {

        float4 f4 = rsUnpackColor8888(rsGetElementAt_uchar4(gIn, x, i));
        sum+=(int)f4.r;
     }

     if((sum>maxsY)){
         maxsY=sum;
         maxIndexY = x;
     }

}
</code>```

Any help would be appreciated

答:
```<code>float4 f4 = rsUnpackColor8888(rsGetElementAt_uchar4(gIn, x, i));
sum+=(int)f4.r;
</code>```

This converts from int to float and then back to int again. I think you can simplify by just doing this:

```<code>sum += rsGetElementAt_uchar4(gIn, x, i).r;
</code>```

I don't know exactly how your previous stages work because you haven't posted them, but you should try generating packed values to read here. So either put your grayscale channels in .rgba or use a single channel format and then use rsAllocationVLoad_uchar4 to fetch 4 values at once.

Also, try combining previous stages with this one, if you don't need the intermediate results of those calculations it may be cheaper to do the memory load once and then do those transformations in registers.

You might also play with how many values your threads operate on. You could try having each kernel processing width/2, width/4, width/8 elements and see how they perform. This will give GPUs more threads to play with especially on lower-resolution images but with the trade off of having more reduction steps.

You also have a multiple-writers race condition on the maxsX/maxsY and maxIndexX/maxIndexY variables. All those writes need to use atomics if you care about the exact right answer. I think maybe you posted the wrong code because you don't store to the *_indices_alloc but you copy from them at the end. So, actually you should store all the sums to those and then use either a single threaded function or a kernel with atomics to get the absolute max and max index.

Body:
Any advise in optimizing the following code? The code first grayscales, inverts and then thresholds the image (code not included, because it is trivial). It then sums the elements of each row and column (all elements are either 1 or 0). It then finds the row and column index of the row and column with the highest value.

The code is supposed to find the centroid of the image and it works, but I want to make it faster

I'm developing for API 23, so a reduction kernel can not be used.

Java snippet:

private int[] sumValueY = new int[640];
private int[] sumValueX = new int[480];

rows_indices_alloc = Allocation.createSized( rs, Element.I32(rs), height, Allocation.USAGE_SCRIPT);
col_indices_alloc = Allocation.createSized( rs, Element.I32(rs), width, Allocation.USAGE_SCRIPT);

public RenderscriptProcessor(RenderScript rs, int width, int height)
{
   mScript.set_gIn(mIntermAllocation);

   mScript.forEach_detectX(rows_indices_alloc);
   mScript.forEach_detectY(col_indices_alloc);

   rows_indices_alloc.copyTo(sumValueX);
   col_indices_alloc.copyTo(sumValueY);
 }

Renderscript.rs snippet:

#pragma version(1)
#pragma rs java_package_name(org.gearvrf.renderscript)
#include "rs_debug.rsh"
#pragma rs_fp_relaxed

const int mImageWidth=640;
const int mImageHeight=480;

int32_t maxsX=-1;
int32_t maxIndexX;

int32_t maxsY=-1;
int32_t maxIndexY;

rs_allocation gIn;

void detectX(int32_t v_in, int32_t x, int32_t y) {

    int32_t sum=0;

    for ( int i = 0; i < (mImageWidth); i++) {

       float4 f4 = rsUnpackColor8888(rsGetElementAt_uchar4(gIn, i, x));
       sum+=(int)f4.r;
    }

    if((sum>maxsX)){

        maxsX=sum;
        maxIndexX = x;
    }
}

void detectY(int32_t v_in, int32_t x, int32_t y) {

     int32_t sum=0;

     for ( int i = 0; i < (mImageHeight); i++) {

        float4 f4 = rsUnpackColor8888(rsGetElementAt_uchar4(gIn, x, i));
        sum+=(int)f4.r;
     }

     if((sum>maxsY)){
         maxsY=sum;
         maxIndexY = x;
     }

}

Any help would be appreciated

Body:
float4 f4 = rsUnpackColor8888(rsGetElementAt_uchar4(gIn, x, i));
sum+=(int)f4.r;

This converts from int to float and then back to int again. I think you can simplify by just doing this:

sum += rsGetElementAt_uchar4(gIn, x, i).r;

I don't know exactly how your previous stages work because you haven't posted them, but you should try generating packed values to read here. So either put your grayscale channels in .rgba or use a single channel format and then use rsAllocationVLoad_uchar4 to fetch 4 values at once.

Also, try combining previous stages with this one, if you don't need the intermediate results of those calculations it may be cheaper to do the memory load once and then do those transformations in registers.

You might also play with how many values your threads operate on. You could try having each kernel processing width/2, width/4, width/8 elements and see how they perform. This will give GPUs more threads to play with especially on lower-resolution images but with the trade off of having more reduction steps.

You also have a multiple-writers race condition on the maxsX/maxsY and maxIndexX/maxIndexY variables. All those writes need to use atomics if you care about the exact right answer. I think maybe you posted the wrong code because you don't store to the *_indices_alloc but you copy from them at the end. So, actually you should store all the sums to those and then use either a single threaded function or a kernel with atomics to get the absolute max and max index.


来源: stackexchange

问:
Ionic 2 Facebook Login - 'App Not Setup' & 'Not Logged in' & 'Given URL is not allowed' Errors
I am trying to implement the Facebook Login API from the Ionic Native library, and have a button in my application that opens up the Facebook login window. However, when that window opens on my iOS device, the following error first appeared.

Then, I began receiving a new error after executing the following commands in terminal:

```<code>$ ionic plugin add cordova-plugin-facebook4 --variable APP_ID="123456789" --variable APP_NAME="myApplication"
$ npm install --save @ionic-native/facebook
</code>```

This issue finally resolved itself after 1 day of inactivity, and then I made my app public by clicking on this in the App Review tab of the Facebook Developers site.

Now, I am receiving yet another error, which should have been fixed by making the app public. Here is the error:

App Not Setup: The developers of this app have not set up this app properly for Facebook Login.

Here is the relevant code for this implementation. I have made sure to include the correct APP ID in all relevant variables, and the code, itself, is not causing any errors. It is simply the case that the login is not communicating with my app.

In package.json:

```<code> {
  "name": "twine-app",
  "author": "Anthony Krivonos",
  "homepage": "http://ionicframework.com/",
  "private": true,
  "scripts": {
    "clean": "ionic-app-scripts clean",
    "build": "ionic-app-scripts build",
    "ionic:build": "ionic-app-scripts build",
    "ionic:serve": "ionic-app-scripts serve"
  },
  "dependencies": {
    "@angular/animations": "^4.0.1",
    "@angular/common": "^4.0.1",
    "@angular/compiler": "^4.0.1",
    "@angular/compiler-cli": "^4.0.1",
    "@angular/core": "^4.0.1",
    "@angular/forms": "^4.0.1",
    "@angular/http": "^4.0.1",
    "@angular/platform-browser": "^4.0.1",
    "@angular/platform-browser-dynamic": "^4.0.1",
    "@angular/platform-server": "^4.0.1",
    "@angular/router": "^4.0.1",
    "@ionic-native/core": "^3.4.4",
    "@ionic-native/facebook": "^3.4.4",
    "@ionic/cloud-angular": "^0.11.0",
    "@ionic/storage": "1.1.7",
    "angular2-elastic": "^0.13.0",
    "firebase": "^3.7.5",
    "ionic-angular": "2.2.0",
    "ionic-native": "^2.9.0",
    "ionicons": "3.0.0",
    "reflect-metadata": "^0.1.10",
    "rxjs": "^5.2.0",
    "sw-toolbox": "3.4.0",
    "typescript": "^2.2.2",
    "zone.js": "0.7.2"
  },
  "devDependencies": {
    "@ionic/app-scripts": "1.1.4",
    "typescript": "2.0.9"
  },
  "cordovaPlugins": [
    "cordova-plugin-whitelist",
    "cordova-plugin-statusbar",
    "cordova-plugin-console",
    "cordova-plugin-device",
    "cordova-plugin-splashscreen",
    "ionic-plugin-keyboard"
  ],
  "cordovaPlatforms": [],
  "description": "Twine: An Ionic project",
  "version": "0.0.1",
  "main": "index.js",
  "repository": {
    "type": "git",
    "url": "git+https://twineme@bitbucket.org/twine-app/twine-app.git"
  },
  "license": "ISC"
}
</code>```

In app.component.ts:

```<code>platform.ready().then(() => {
        let env = this;
        NativeStorage.getItem('user')
        .then(function (data) {
              env.nav.push(FeedPage);
              Splashscreen.hide();
        }, function (error) {
              env.nav.push(OnboardingPage);
              Splashscreen.hide();
        });
              StatusBar.styleDefault();
              StatusBar.overlaysWebView(false);
              Splashscreen.hide();
  });
</code>```

In onboarding.ts (Code by Sampath):

```<code>import { Component } from '@angular/core';
import { NavController } from 'ionic-angular';
import { Facebook, FacebookLoginResponse } from '@ionic-native/facebook';

@Component({
  selector: 'page-home',
  templateUrl: 'home.html'
})
export class HomePage {

  constructor(public fb: Facebook) {

  }

  fbLogin(): void {
    this.fb.login(['public_profile', 'user_friends', 'email'])
      .then((res: FacebookLoginResponse) => console.log('Logged into Facebook!', res))
      .catch(e => console.log('Error logging into Facebook', e));
  }

}
</code>```

I have scoured several different websites and forums for solutions, and seemed to have come up with no way of fixing this error. Most answers suggest to add a new platform in the Facebook developer portal with the app's Site URL, but my app runs off localhost. Additionally, I have installed all necessary plugins. Does anyone understand what may be causing this issue? Thank you so much in advance.

Edit: DO NOT suggest that I should make the app public via the Facebook Developer portal, because my question clearly outlines that I have done so already. Thanks.

Edit 2: I have tried Sampath's solution, and login works perfectly. This reaffirms that there is an issue with the above code. However, I cannot seem to pinpoint it after days of work. Here's a screenshot.

答:
Update:

It is working fine for me.It seems your issue with facebook's app settings section.Please let me know if you need any help on that section too.

Play with Git Repo.

home.ts

```<code>import { Facebook, FacebookLoginResponse } from '@ionic-native/facebook';

@Component({
  selector: 'page-home',
  templateUrl: 'home.html'
})
export class HomePage {

  constructor(public fb: Facebook) {

  }

  fbLogin(): void {
    this.fb.login(['public_profile', 'user_friends', 'email'])
      .then((res: FacebookLoginResponse) => console.log('Logged into Facebook!', res))
      .catch(e => console.log('Error logging into Facebook', e));
  }

}
</code>```

app.module.ts

```<code>import { HomePage } from '../pages/home/home';
import { Facebook } from '@ionic-native/facebook';

@NgModule({
  declarations: [
    MyApp,
    HomePage
  ],
  imports: [
    IonicModule.forRoot(MyApp)
  ],
  bootstrap: [IonicApp],
  entryComponents: [
    MyApp,
    HomePage
  ],
  providers: [
    Facebook
  ]
})
export class AppModule { }
</code>```

home.html

```<code><button ion-button block type="button" (click)="fbLogin()">Fb Login</button>
</code>```

Old Answer

I can see 3 issues on your package.json file.

Issue 1:

You have to remove "ionic-native": "2.4.1", module from it.

Issue 2:

You have to use "@ionic/app-scripts": "1.1.4", instead of  "@ionic/app-scripts": "1.0.0",

Issue 3:

You have to use "ionic-angular": "2.2.0", instead of "ionic-angular": "2.0.1",

After all above changes run npm i

ContentLicense: CC BY-SA 3.0

Body:
I am trying to implement the Facebook Login API from the Ionic Native library, and have a button in my application that opens up the Facebook login window. However, when that window opens on my iOS device, the following error first appeared.

Then, I began receiving a new error after executing the following commands in terminal:

$ ionic plugin add cordova-plugin-facebook4 --variable APP_ID="123456789" --variable APP_NAME="myApplication"
$ npm install --save @ionic-native/facebook

This issue finally resolved itself after 1 day of inactivity, and then I made my app public by clicking on this in the App Review tab of the Facebook Developers site.

Now, I am receiving yet another error, which should have been fixed by making the app public. Here is the error:

App Not Setup: The developers of this app have not set up this app properly for Facebook Login.

Here is the relevant code for this implementation. I have made sure to include the correct APP ID in all relevant variables, and the code, itself, is not causing any errors. It is simply the case that the login is not communicating with my app.

In package.json:

 {
  "name": "twine-app",
  "author": "Anthony Krivonos",
  "homepage": "http://ionicframework.com/",
  "private": true,
  "scripts": {
    "clean": "ionic-app-scripts clean",
    "build": "ionic-app-scripts build",
    "ionic:build": "ionic-app-scripts build",
    "ionic:serve": "ionic-app-scripts serve"
  },
  "dependencies": {
    "@angular/animations": "^4.0.1",
    "@angular/common": "^4.0.1",
    "@angular/compiler": "^4.0.1",
    "@angular/compiler-cli": "^4.0.1",
    "@angular/core": "^4.0.1",
    "@angular/forms": "^4.0.1",
    "@angular/http": "^4.0.1",
    "@angular/platform-browser": "^4.0.1",
    "@angular/platform-browser-dynamic": "^4.0.1",
    "@angular/platform-server": "^4.0.1",
    "@angular/router": "^4.0.1",
    "@ionic-native/core": "^3.4.4",
    "@ionic-native/facebook": "^3.4.4",
    "@ionic/cloud-angular": "^0.11.0",
    "@ionic/storage": "1.1.7",
    "angular2-elastic": "^0.13.0",
    "firebase": "^3.7.5",
    "ionic-angular": "2.2.0",
    "ionic-native": "^2.9.0",
    "ionicons": "3.0.0",
    "reflect-metadata": "^0.1.10",
    "rxjs": "^5.2.0",
    "sw-toolbox": "3.4.0",
    "typescript": "^2.2.2",
    "zone.js": "0.7.2"
  },
  "devDependencies": {
    "@ionic/app-scripts": "1.1.4",
    "typescript": "2.0.9"
  },
  "cordovaPlugins": [
    "cordova-plugin-whitelist",
    "cordova-plugin-statusbar",
    "cordova-plugin-console",
    "cordova-plugin-device",
    "cordova-plugin-splashscreen",
    "ionic-plugin-keyboard"
  ],
  "cordovaPlatforms": [],
  "description": "Twine: An Ionic project",
  "version": "0.0.1",
  "main": "index.js",
  "repository": {
    "type": "git",
    "url": "git+https://twineme@bitbucket.org/twine-app/twine-app.git"
  },
  "license": "ISC"
}

In app.component.ts:

platform.ready().then(() => {
        let env = this;
        NativeStorage.getItem('user')
        .then(function (data) {
              env.nav.push(FeedPage);
              Splashscreen.hide();
        }, function (error) {
              env.nav.push(OnboardingPage);
              Splashscreen.hide();
        });
              StatusBar.styleDefault();
              StatusBar.overlaysWebView(false);
              Splashscreen.hide();
  });

In onboarding.ts (Code by Sampath):

import { Component } from '@angular/core';
import { NavController } from 'ionic-angular';
import { Facebook, FacebookLoginResponse } from '@ionic-native/facebook';

@Component({
  selector: 'page-home',
  templateUrl: 'home.html'
})
export class HomePage {

  constructor(public fb: Facebook) {

  }

  fbLogin(): void {
    this.fb.login(['public_profile', 'user_friends', 'email'])
      .then((res: FacebookLoginResponse) => console.log('Logged into Facebook!', res))
      .catch(e => console.log('Error logging into Facebook', e));
  }

}

I have scoured several different websites and forums for solutions, and seemed to have come up with no way of fixing this error. Most answers suggest to add a new platform in the Facebook developer portal with the app's Site URL, but my app runs off localhost. Additionally, I have installed all necessary plugins. Does anyone understand what may be causing this issue? Thank you so much in advance.

Edit: DO NOT suggest that I should make the app public via the Facebook Developer portal, because my question clearly outlines that I have done so already. Thanks.

Edit 2: I have tried Sampath's solution, and login works perfectly. This reaffirms that there is an issue with the above code. However, I cannot seem to pinpoint it after days of work. Here's a screenshot.

Body:
Update:

It is working fine for me.It seems your issue with facebook's app settings section.Please let me know if you need any help on that section too.

Play with Git Repo.

home.ts

import { Facebook, FacebookLoginResponse } from '@ionic-native/facebook';

@Component({
  selector: 'page-home',
  templateUrl: 'home.html'
})
export class HomePage {

  constructor(public fb: Facebook) {

  }

  fbLogin(): void {
    this.fb.login(['public_profile', 'user_friends', 'email'])
      .then((res: FacebookLoginResponse) => console.log('Logged into Facebook!', res))
      .catch(e => console.log('Error logging into Facebook', e));
  }

}

app.module.ts

import { HomePage } from '../pages/home/home';
import { Facebook } from '@ionic-native/facebook';

@NgModule({
  declarations: [
    MyApp,
    HomePage
  ],
  imports: [
    IonicModule.forRoot(MyApp)
  ],
  bootstrap: [IonicApp],
  entryComponents: [
    MyApp,
    HomePage
  ],
  providers: [
    Facebook
  ]
})
export class AppModule { }

home.html

<button ion-button block type="button" (click)="fbLogin()">Fb Login</button>

Old Answer

I can see 3 issues on your package.json file.

Issue 1:

You have to remove "ionic-native": "2.4.1", module from it.

Issue 2:

You have to use "@ionic/app-scripts": "1.1.4", instead of  "@ionic/app-scripts": "1.0.0",

Issue 3:

You have to use "ionic-angular": "2.2.0", instead of "ionic-angular": "2.0.1",

After all above changes run npm i


问:
Do you need to use Bootstrap's "container" and "row" if your content is to span the whole width?
I think the standard of Bootstrap 3 and 4 is

```<code><div class="container">
    <div class="row">
        <div class="col-md-4"> ... </div>
        <div class="col-md-8"> ... </div>   <!-- just add up to 12 -->
    </div>
</div>
</code>```

But what if you have a div, table, form, or any element, that you plan to just let it span the whole width?  Then do you need the container or row or col-md-12 at all, for the whole page to display well under the styling rules of Bootstrap 3 and 4?

P.S. if possible, please point to or quote the official Bootstrap docs related to this.

答:
You should add .container-fluid to your wrapping div. You should wrap the table, div, or form within a div add the class .container-fluid to it.

The official bootstrap documentation on grid system

Body:
I think the standard of Bootstrap 3 and 4 is

 ...

 ...

But what if you have a div, table, form, or any element, that you plan to just let it span the whole width?  Then do you need the container or row or col-md-12 at all, for the whole page to display well under the styling rules of Bootstrap 3 and 4?

P.S. if possible, please point to or quote the official Bootstrap docs related to this.


问:
can anyone tell me about the model (skipgram/ CBOW ) used by Gensim?
word2vec uses either of the model for distributed representation of words. I was checking out the codes of gensim but it is not defined about the model used by gensim .</p>

答:
From the gensim documentation:

sg defines the training algorithm. By default (sg=0), CBOW is used. Otherwise (sg=1), skip-gram is employed.


问:
Avoid rewriting common function for multiple classes
I have the following situation: I have a class Application that wraps data given to it in header and footer and adds checksum to make a packet. TCP inherits from Application and does the exact same procedure with the packet obtained from Application(i.e, it calls super to make_packet and then makes it's own).

Since the make_packet code is the same for both the classes, except for header and footer values, I tried to to use closures, like below.
The important line below is the self.packet = cls_name.header + self.packet + cls_name.footer in the cmake_packet:

```<code>def make_make_packet(cls_name):
    def cmake_packet(self):
       self.packet = cls_name.header + self.packet + cls_name.footer
       checksum = self.packet[::-1]
       self.packet += checksum
       return self.packet

    return cmake_packet()

class Application:
    header = footer = "001101"

    def __init__(self, data):
        self.packet = data

    make_packet = make_make_packet(Application)

class TCP(Application):
    header = footer = "110011"

    def __init__(self, data):
        super().__init__(data)
        self.packet = super().make_packet()

    make_packet = make_make_packet(TCP)
</code>```

and to send a packet of data across a network, I just call:

```<code># data is something like "010"
tlayer = TCP(data)
# or send()
print(tlayer.make_packet())
</code>```

The problem is that the above definition gives an error because when make_make_packet(Application) is called, Application is not yet defined.

Is there a way to solve this problem without repeating the function for several classes, and without using self.header (which doesn't work here anyway)

Note: make_packet() needs to be called twice for each TCP packet that is made, not once(OSI seven layer model). First Application wraps the raw data in a packet, which is then further wrapped in a bigger packet by TCP by adding it's own headers.

答:
Class attributes are also accessible by self..

```<code>class Application:
    header = footer = "001101"

    def __init__(self, data):
        self.packet = data

    def make_packet(self):
       self.packet = self.header + self.packet + self.footer
       checksum = self.packet[::-1]
       self.packet += checksum
       return self.packet

class TCP(Application):
    header = footer = "110011"

    def __init__(self, data):
        data = Application(data).make_packet()
        super().__init__(data)
</code>```

Body:
I have the following situation: I have a class Application that wraps data given to it in header and footer and adds checksum to make a packet. TCP inherits from Application and does the exact same procedure with the packet obtained from Application(i.e, it calls super to make_packet and then makes it's own).

Since the make_packet code is the same for both the classes, except for header and footer values, I tried to to use closures, like below.
The important line below is the self.packet = cls_name.header + self.packet + cls_name.footer in the cmake_packet:

def make_make_packet(cls_name):
    def cmake_packet(self):
       self.packet = cls_name.header + self.packet + cls_name.footer
       checksum = self.packet[::-1]
       self.packet += checksum
       return self.packet

    return cmake_packet()

class Application:
    header = footer = "001101"

    def __init__(self, data):
        self.packet = data

    make_packet = make_make_packet(Application)

class TCP(Application):
    header = footer = "110011"

    def __init__(self, data):
        super().__init__(data)
        self.packet = super().make_packet()

    make_packet = make_make_packet(TCP)

and to send a packet of data across a network, I just call:

# data is something like "010"
tlayer = TCP(data)
# or send()
print(tlayer.make_packet())

The problem is that the above definition gives an error because when make_make_packet(Application) is called, Application is not yet defined.

Is there a way to solve this problem without repeating the function for several classes, and without using self.header (which doesn't work here anyway)

Note: make_packet() needs to be called twice for each TCP packet that is made, not once(OSI seven layer model). First Application wraps the raw data in a packet, which is then further wrapped in a bigger packet by TCP by adding it's own headers.

Body:
Class attributes are also accessible by self..

class Application:
    header = footer = "001101"

    def __init__(self, data):
        self.packet = data

    def make_packet(self):
       self.packet = self.header + self.packet + self.footer
       checksum = self.packet[::-1]
       self.packet += checksum
       return self.packet

class TCP(Application):
    header = footer = "110011"

    def __init__(self, data):
        data = Application(data).make_packet()
        super().__init__(data)


问:
How to allow list append() method to return the new list
I want to do something like this:

```<code>myList = [10, 20, 30]
yourList = myList.append(40)
</code>```

Unfortunately, list append does not return the modified list.

So, how can I allow append to return the new list?

See also: Why do these list operations (methods) return None, rather than the resulting list?

答:
Just to expand on Storstamp's answer

You only need to do
myList.append(40)

It will append it to the original list,now you can return the variable containing the original list.

If you are working with very large lists this is the way to go.

ContentLicense: CC BY-SA 4.0

Body:
I want to do something like this:

myList = [10, 20, 30]
yourList = myList.append(40)

Unfortunately, list append does not return the modified list.

So, how can I allow append to return the new list?

See also: Why do these list operations (methods) return None, rather than the resulting list?


问:
AWS EC2 terminate command giving "Service ec2 not available" error from Ansible
I am running this command aws ec2 terminate-instances --instance-ids $(ec2metadata --instance-id) in Ubuntu via Ansible as root.

And I'm getting this error:

"stderr": "Service ec2 not available in region aws-east-1"

What does this mean?  Does it mean that I can't terminate instances in the region aws-east-1?

But, when I run that command manually in the cmd, it terminates well! How do I solve this?

答: In the credentials/config file on your ubuntu instance, do you have the region set to aws-east-1 instead of us-east-1? aws-east-1 is not a valid region.</p>


问:
MongoDB and mongoose schema
This is model in models.js

```<code>var PatientSchema = new mongoose.Schema({
     _id : String,
     LastName : String,
     MiddleName : String,
     PatientIntId : String,
     Sex : String,
     Address1 : String,
     City : String,
     State : String,
     ZipCode : String,
     AccountNumber : String,
     Ssn : String
 });

var PatientInfoMdl = mongoose.model('PatientInfo',PatientSchema);
exports.PatientInfoMdl = PatientInfoMdl;
</code>```

and my code for accessing data is :

```<code>var dbObj = require('../dataBase');
var config = require('../config');<
var moment = require('moment');
var models = require('../models/models');
var orm = require('orm');
var xml2js = require('xml2js');
var fs = require('fs');
var user = models.user;
var PatientInfoMdl = models.PatientInfoMdl;
exports.DisplayUsers = function (req, res) {
    var name = '';
    dbObj.connect(config.get('mongo'), function () {
        PatientInfoMdl.find()({}, function (err, docs) {
            if (err)
                res.json(err);
            else res.render('index', { Patients : docs });
        });
    });
}
</code>```

and I am not getting data and what is my mistake?

答:
For example:

Controller.js

```<code>var mongoose = require('mongoose');

var User = mongoose.model('User');

module.exports = {

  show: function(req, res) {

     User.find({}, function(err, users) {

      res.render('main', {users: users});

    })
  }
}
</code>```

Models:User.js

```<code>// require mongoose
var mongoose = require('mongoose');

// create the UserSchema

var UserSchema = new mongoose.Schema({
  name: String
})

// register the schema as a model

var User = mongoose.model('User', UserSchema);

module.exports = {User}
</code>```

routes.js

```<code>// here we load the Quote model that we created on the server.js page

var mongoose = require('mongoose');

var User = mongoose.model('User');

// import users

var users = require('../controllers/users.js');

module.exports = function(app) {

  app.get('/', function(req, res) {

    res.send("Hello");

  })

  app.get('/user',function(req,res){

      users.show(req,res);

  })
}
</code>```

Title: MongoDB and mongoose schema

Body:
This is model in models.js

var PatientSchema = new mongoose.Schema({
     _id : String,
     LastName : String,
     MiddleName : String,
     PatientIntId : String,
     Sex : String,
     Address1 : String,
     City : String,
     State : String,
     ZipCode : String,
     AccountNumber : String,
     Ssn : String
 });

var PatientInfoMdl = mongoose.model('PatientInfo',PatientSchema);
exports.PatientInfoMdl = PatientInfoMdl;

and my code for accessing data is :

var dbObj = require('../dataBase');
var config = require('../config');<
var moment = require('moment');
var models = require('../models/models');
var orm = require('orm');
var xml2js = require('xml2js');
var fs = require('fs');
var user = models.user;
var PatientInfoMdl = models.PatientInfoMdl;
exports.DisplayUsers = function (req, res) {
    var name = '';
    dbObj.connect(config.get('mongo'), function () {
        PatientInfoMdl.find()({}, function (err, docs) {
            if (err)
                res.json(err);
            else res.render('index', { Patients : docs });
        });
    });
}

and I am not getting data and what is my mistake?

Body:
For example:

Controller.js

var mongoose = require('mongoose');

var User = mongoose.model('User');

module.exports = {

  show: function(req, res) {

     User.find({}, function(err, users) {

      res.render('main', {users: users});

    })
  }
}

Models:User.js

// require mongoose
var mongoose = require('mongoose');

// create the UserSchema

var UserSchema = new mongoose.Schema({
  name: String
})

// register the schema as a model

var User = mongoose.model('User', UserSchema);

module.exports = {User}

routes.js

// here we load the Quote model that we created on the server.js page

var mongoose = require('mongoose');

var User = mongoose.model('User');

// import users

var users = require('../controllers/users.js');

module.exports = function(app) {

  app.get('/', function(req, res) {

    res.send("Hello");

  })

  app.get('/user',function(req,res){

      users.show(req,res);

  })
}


问:
Mouseover event triggered by Child Elements - how to stop this?
I have this interface I want to build using Effect.Move from scriptaculous (with Prototype, of course).

When the top div is triggered on a mouseover, a span tag is to move 50 pixels to the left - and reset without movement to the original location on mouseout. The problem is, any time this div element is entered from a child element, the element I want moved moves an additional 50 pixels. I've tried using relatedTarget and toElement to stop this event from propogating, but to no avail. Here is the code, as of yet incomplete:

```<code>e.observe('mouseover', function(evt) {
   var block = e.down('span');

   if(evt.target == block && !evt.relatedTarget.descendantOf(block)){
    new Effect.Move(block, { x: -50, duration: 0.4,

    });
   } else {

   }

  });
</code>```

HTML Sample:

```<code><div class='trigger'>
  <span class='to-be-moved'>...</span>
  <p>Child Element</p>
  <h2>Another Child Element</h2>
  <a>Link</a>
</div>
</code>```

I'm totally lost here - any suggestions?

答:
Look here.

If you're looking for a specific element that triggered the onmouseover event, use Prototype's Event.findElement(...) method in order to sift through unwanted children.

Serkan's answer is a hoky way of completing the task but won't work in all browsers.

ContentLicense: CC BY-SA 2.5

Body:
I have this interface I want to build using Effect.Move from scriptaculous (with Prototype, of course).

When the top div is triggered on a mouseover, a span tag is to move 50 pixels to the left - and reset without movement to the original location on mouseout. The problem is, any time this div element is entered from a child element, the element I want moved moves an additional 50 pixels. I've tried using relatedTarget and toElement to stop this event from propogating, but to no avail. Here is the code, as of yet incomplete:

e.observe('mouseover', function(evt) {
   var block = e.down('span');

   if(evt.target == block && !evt.relatedTarget.descendantOf(block)){
    new Effect.Move(block, { x: -50, duration: 0.4,

    });
   } else {

   }

  });

HTML Sample:

  ...

Child Element

Another Child Element

  Link

I'm totally lost here - any suggestions?


问:
How do I fix this error when trying to use the Watson SDK for Unity?
thanks for taking a look at this. I'm new to Unity and struggling to understand how to fix this error.

Assets/Watson/Scripts/Logging/Logger.cs(115,53): error CS0311: The type IBM.Watson.DeveloperCloud.Logging.LogSystem' cannot be used as type parameter T in the generic type or method Singleton. There is no implicit reference conversion from IBM.Watson.DeveloperCloud.Logging.LogSystem' to `UnityEngine.MonoBehaviour

This is the line causing the error:

```<code>public static LogSystem Instance { get { return Singleton<LogSystem>.Instance; } }
</code>```

And this is it in context:

```<code> /// <summary>
  /// This singleton class maintains the of list of installed reactors and handles all LogRecord
  /// objects. See the static class Log for functions the end user of this system should actually
  /// be calling. This class is thread safe.
  /// </summary>
  public class LogSystem
  {
    #region Public Properties
    /// <summary>
    /// Returns the singleton instance of the Logger object.
    /// </summary>
    **public static LogSystem Instance { get { return Singleton<LogSystem>.Instance; } }**
    #endregion

    #region Private Data
    private static bool sm_bInstalledDefaultReactors = false;
    List<ILogReactor> m_Reactors = new List<ILogReactor>();
    #endregion

    #region Public Functions
    public static List<ILogReactor> ReactorsInstalled
    {
      get
      {
        return LogSystem.Instance.m_Reactors;
      }
    }

    /// <summary>
    /// Install a default debug and file reactor.
    /// </summary>
    public static void InstallDefaultReactors(int logHistory = 2, LogLevel logLevelFileReactor = LogLevel.STATUS)
    {
      if (!sm_bInstalledDefaultReactors)
      {
        // install the default reactors...
        sm_bInstalledDefaultReactors = true;
#if UNITY_EDITOR || UNITY_IOS || UNITY_ANDROID
        LogSystem.Instance.InstallReactor(new DebugReactor());
#endif

        if (!string.IsNullOrEmpty(Constants.Path.LOG_FOLDER) && !System.IO.Directory.Exists(Application.persistentDataPath + Constants.Path.LOG_FOLDER))
          System.IO.Directory.CreateDirectory(Application.persistentDataPath + Constants.Path.LOG_FOLDER);

        LogSystem.Instance.InstallReactor(new FileReactor(Application.persistentDataPath + Constants.Path.LOG_FOLDER + "/" + Application.productName + ".log", logLevelFileReactor, logHistory));

        Application.logMessageReceived += UnityLogCallback;
      }
    }

    static void UnityLogCallback(string condition, string stacktrace, LogType type)
    {
      if (type == LogType.Exception)
        Log.Critical("Unity", "Unity Exception {0} : {1}", condition, stacktrace);
    }

    /// <summary>
    /// Installs a reactor into this Logger.
    /// </summary>
    /// <param name="reactor">The reactor object.</param>
    public void InstallReactor(ILogReactor reactor)
    {
      lock (m_Reactors)
      {
        m_Reactors.Add(reactor);
      }
      // set our default reactor flag to true if the user installs their own reactors.
      sm_bInstalledDefaultReactors = true;
    }

    /// <summary>
    /// Removes a reactor from this Logger.
    /// </summary>
    /// <param name="reactor">The reactor to remove.</param>
    /// <returns>Returns true on success.</returns>
    public bool RemoveReactor(ILogReactor reactor)
    {
      lock (m_Reactors)
      {
        return m_Reactors.Remove(reactor);
      }
    }

    /// <summary>
    /// Send the given LogRecord to all installed reactors.
    /// </summary>
    /// <param name="log">The LogRecord to pass to all reactors.</param>
    public void ProcessLog(LogRecord log)
    {
      lock (m_Reactors)
      {
        foreach (var reactor in m_Reactors)
          reactor.ProcessLog(log);
      }
    }
    #endregion
  }
</code>```

答:
```<code>public static LogSystem Instance
{
     get
     {
          return instance;
     }
}
private static LogSystem instance;
// Ctor of the class
public LogSystem()
{
    if(instance == null) { instance = this;}
}
</code>```

This is a very basic singleton pattern implementation. You can find more advanced ones online.

Body:
thanks for taking a look at this. I'm new to Unity and struggling to understand how to fix this error.

Assets/Watson/Scripts/Logging/Logger.cs(115,53): error CS0311: The type IBM.Watson.DeveloperCloud.Logging.LogSystem' cannot be used as type parameter T in the generic type or method Singleton. There is no implicit reference conversion from IBM.Watson.DeveloperCloud.Logging.LogSystem' to `UnityEngine.MonoBehaviour

This is the line causing the error:

public static LogSystem Instance { get { return Singleton<LogSystem>.Instance; } }

And this is it in context:

 ///
  /// This singleton class maintains the of list of installed reactors and handles all LogRecord
  /// objects. See the static class Log for functions the end user of this system should actually
  /// be calling. This class is thread safe.
  ///
  public class LogSystem
  {
    #region Public Properties
    ///
    /// Returns the singleton instance of the Logger object.
    ///
    **public static LogSystem Instance { get { return Singleton<LogSystem>.Instance; } }**
    #endregion

    #region Private Data
    private static bool sm_bInstalledDefaultReactors = false;
    List<ILogReactor> m_Reactors = new List<ILogReactor>();
    #endregion

    #region Public Functions
    public static List<ILogReactor> ReactorsInstalled
    {
      get
      {
        return LogSystem.Instance.m_Reactors;
      }
    }

    ///
    /// Install a default debug and file reactor.
    ///
    public static void InstallDefaultReactors(int logHistory = 2, LogLevel logLevelFileReactor = LogLevel.STATUS)
    {
      if (!sm_bInstalledDefaultReactors)
      {
        // install the default reactors...
        sm_bInstalledDefaultReactors = true;
#if UNITY_EDITOR || UNITY_IOS || UNITY_ANDROID
        LogSystem.Instance.InstallReactor(new DebugReactor());
#endif

        if (!string.IsNullOrEmpty(Constants.Path.LOG_FOLDER) && !System.IO.Directory.Exists(Application.persistentDataPath + Constants.Path.LOG_FOLDER))
          System.IO.Directory.CreateDirectory(Application.persistentDataPath + Constants.Path.LOG_FOLDER);

        LogSystem.Instance.InstallReactor(new FileReactor(Application.persistentDataPath + Constants.Path.LOG_FOLDER + "/" + Application.productName + ".log", logLevelFileReactor, logHistory));

        Application.logMessageReceived += UnityLogCallback;
      }
    }

    static void UnityLogCallback(string condition, string stacktrace, LogType type)
    {
      if (type == LogType.Exception)
        Log.Critical("Unity", "Unity Exception {0} : {1}", condition, stacktrace);
    }

    ///
    /// Installs a reactor into this Logger.
    ///
    /// <param name="reactor">The reactor object.</param>
    public void InstallReactor(ILogReactor reactor)
    {
      lock (m_Reactors)
      {
        m_Reactors.Add(reactor);
      }
      // set our default reactor flag to true if the user installs their own reactors.
      sm_bInstalledDefaultReactors = true;
    }

    ///
    /// Removes a reactor from this Logger.
    ///
    /// <param name="reactor">The reactor to remove.</param>
    /// <returns>Returns true on success.</returns>
    public bool RemoveReactor(ILogReactor reactor)
    {
      lock (m_Reactors)
      {
        return m_Reactors.Remove(reactor);
      }
    }

    ///
    /// Send the given LogRecord to all installed reactors.
    ///
    /// <param name="log">The LogRecord to pass to all reactors.</param>
    public void ProcessLog(LogRecord log)
    {
      lock (m_Reactors)
      {
        foreach (var reactor in m_Reactors)
          reactor.ProcessLog(log);
      }
    }
    #endregion
  }

Body:
public static LogSystem Instance
{
     get
     {
          return instance;
     }
}
private static LogSystem instance;
// Ctor of the class
public LogSystem()
{
    if(instance == null) { instance = this;}
}

This is a very basic singleton pattern implementation. You can find more advanced ones online.


问:
Can't connect to php in Android Application
Now I'm working on RESTful API with php and try to connect to it from Android
But I can't connect because it's always catch IOException

here's my Android Code (OnReg is the method when clicked Register Button)

```<code>public void OnReg(View view)
{
    str_email = et_email.getText().toString();
    str_password = et_password.getText().toString();
    str_fname = et_fname.getText().toString();
    str_lname = et_lname.getText().toString();
    type = "register";
    BackgroundWorker backgroundWorker = new BackgroundWorker(this);
    backgroundWorker.execute(type, str_email, str_password, str_fname, str_lname);
}
</code>```

Here's the BackgroundWorker class

```<code>public class BackgroundWorker extends AsyncTask<String, Void, String>
{
   Context context;
   AlertDialog alertDialog;

   BackgroundWorker(Context ctx)
   {
       context = ctx;
   }

   @Override
   protected String doInBackground(String... params)
   {
      StringBuilder result = new StringBuilder();
      String type = params[0];
      BufferedWriter bufferedWriter = null;
      BufferedReader bufferedReader = null;
      String register_url = "http://192.168.1.9/register.php";
      if(type.equals("register"))
      {
          try
          {
              //Create data to send to server
              JSONObject dataToSend = new JSONObject();
              dataToSend.put("email", params[1]);
              dataToSend.put("password", params[2]);
              dataToSend.put("fname", params[3]);
              dataToSend.put("lname", params[4]);

              //Initialize and config request, then connect to server
              URL url = new URL(register_url);
              HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
              httpURLConnection.setRequestMethod("POST");
              httpURLConnection.setDoOutput(true); //enable output (body data)
              httpURLConnection.setRequestProperty("Content-Type", "application/json"); //set header
              httpURLConnection.connect();

              //Write data into server
              OutputStream outputStream = httpURLConnection.getOutputStream();
              bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream));
              bufferedWriter.write(dataToSend.toString());
              bufferedWriter.flush();
              bufferedWriter.close();
              outputStream.close();

              //Read data response from server
              InputStream inputStream = httpURLConnection.getInputStream();
              bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
              String line;
              while ((line = bufferedReader.readLine()) != null)
              {
                  result.append(line).append("\n");
              }
              bufferedReader.close();
              inputStream.close();
              httpURLConnection.disconnect();
          }
          catch (IOException e)
          {
              return "Network Error";
          }
          catch (JSONException e)
          {
              e.printStackTrace();
          }
      }
      return result.toString();
  }

  @Override
  protected void onPreExecute()
  {
      alertDialog = new AlertDialog.Builder(context).create();
      alertDialog.setTitle("Status");

  }

  @Override
  protected void onPostExecute(String result)
  {
      alertDialog.setMessage(result);
      alertDialog.show();
  }
</code>```

Here's my PHP Code

```<code><?php
  $m = new MongoClient();
  $db = $m -> ETESS;
  $collection = $db -> members;
  if($_SERVER['REQUEST_METHOD'] == 'POST')
  {
    $data = json_decode(file_get_contents("php://input"));
    $email = $data->email;
    $password = $data->password;
    $fname = $data->fname;
    $lname = $data->lname;
    $encrypted_password = md5($password);
    $document = array(
       "email" => $email,
       "password" => $encrypted_password,
       "fname" => $fname,
       "lname" => $lname
       );
    if($collection -> insert($document))
    {
       echo "Registered Successfully !";
       $response["result"] = "success";
       $response["message"] = "Registered Successfully !";
       return json_encode($response);
    }
    else
    {
       $response["result"] = "failure";
       $response["message"] = "Registered Failed";
       return json_encode($response);
    }
  }
?>
</code>```

I already added this in AndroidManifest.xml

```<code><uses-permission android:name="android.permission.INTERNET"></uses-permission>
</code>```

with all of these code I always get "Network Error" when I clicked Register Button (I assume that it's catch IOException) but when I tried to send POST request by Advanced REST client, everything work perfectly.

Please kindly check my code if there are any mistake.

Thanks

答:
Now I try to connect 192.168.1.9/register.php in browser in my mobile, and it's said

You don't have permission to access /register.php on this server.

I use wamp as web server

Thanks

Body:
Now I'm working on RESTful API with php and try to connect to it from Android
But I can't connect because it's always catch IOException

here's my Android Code (OnReg is the method when clicked Register Button)

public void OnReg(View view)
{
    str_email = et_email.getText().toString();
    str_password = et_password.getText().toString();
    str_fname = et_fname.getText().toString();
    str_lname = et_lname.getText().toString();
    type = "register";
    BackgroundWorker backgroundWorker = new BackgroundWorker(this);
    backgroundWorker.execute(type, str_email, str_password, str_fname, str_lname);
}

Here's the BackgroundWorker class

public class BackgroundWorker extends AsyncTask<String, Void, String>
{
   Context context;
   AlertDialog alertDialog;

   BackgroundWorker(Context ctx)
   {
       context = ctx;
   }

   @Override
   protected String doInBackground(String... params)
   {
      StringBuilder result = new StringBuilder();
      String type = params[0];
      BufferedWriter bufferedWriter = null;
      BufferedReader bufferedReader = null;
      String register_url = "http://192.168.1.9/register.php";
      if(type.equals("register"))
      {
          try
          {
              //Create data to send to server
              JSONObject dataToSend = new JSONObject();
              dataToSend.put("email", params[1]);
              dataToSend.put("password", params[2]);
              dataToSend.put("fname", params[3]);
              dataToSend.put("lname", params[4]);

              //Initialize and config request, then connect to server
              URL url = new URL(register_url);
              HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
              httpURLConnection.setRequestMethod("POST");
              httpURLConnection.setDoOutput(true); //enable output (body data)
              httpURLConnection.setRequestProperty("Content-Type", "application/json"); //set header
              httpURLConnection.connect();

              //Write data into server
              OutputStream outputStream = httpURLConnection.getOutputStream();
              bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream));
              bufferedWriter.write(dataToSend.toString());
              bufferedWriter.flush();
              bufferedWriter.close();
              outputStream.close();

              //Read data response from server
              InputStream inputStream = httpURLConnection.getInputStream();
              bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
              String line;
              while ((line = bufferedReader.readLine()) != null)
              {
                  result.append(line).append("\n");
              }
              bufferedReader.close();
              inputStream.close();
              httpURLConnection.disconnect();
          }
          catch (IOException e)
          {
              return "Network Error";
          }
          catch (JSONException e)
          {
              e.printStackTrace();
          }
      }
      return result.toString();
  }

  @Override
  protected void onPreExecute()
  {
      alertDialog = new AlertDialog.Builder(context).create();
      alertDialog.setTitle("Status");

  }

  @Override
  protected void onPostExecute(String result)
  {
      alertDialog.setMessage(result);
      alertDialog.show();
  }

Here's my PHP Code

<?php
  $m = new MongoClient();
  $db = $m -> ETESS;
  $collection = $db -> members;
  if($_SERVER['REQUEST_METHOD'] == 'POST')
  {
    $data = json_decode(file_get_contents("php://input"));
    $email = $data->email;
    $password = $data->password;
    $fname = $data->fname;
    $lname = $data->lname;
    $encrypted_password = md5($password);
    $document = array(
       "email" => $email,
       "password" => $encrypted_password,
       "fname" => $fname,
       "lname" => $lname
       );
    if($collection -> insert($document))
    {
       echo "Registered Successfully !";
       $response["result"] = "success";
       $response["message"] = "Registered Successfully !";
       return json_encode($response);
    }
    else
    {
       $response["result"] = "failure";
       $response["message"] = "Registered Failed";
       return json_encode($response);
    }
  }
?>

I already added this in AndroidManifest.xml

<uses-permission android:name="android.permission.INTERNET"></uses-permission>

with all of these code I always get "Network Error" when I clicked Register Button (I assume that it's catch IOException) but when I tried to send POST request by Advanced REST client, everything work perfectly.

Please kindly check my code if there are any mistake.

Thanks


问:
Use SQL (Like) when have Multiple (WHERE)
How Can i add (Like) to this Code When we have some WHERE item : </p>

```<code>$result = $this->db->query("SELECT * FROM test WHERE zone_id='$zone' and category_id='$category' ORDER BY id DESC");
</code>```

答:
Just add the like before the ORDER BY. I added x like y. It is no differnt from adding x=y similar to the two equivalent statements you already had.

```<code>"SELECT * FROM test WHERE zone_id='$zone' and category_id='$category' and x like y ORDER BY id DESC"
</code>```

Body:
How Can i add (Like) to this Code When we have some WHERE item :

$result = $this->db->query("SELECT * FROM test WHERE zone_id='$zone' and category_id='$category' ORDER BY id DESC");

Body:
Just add the like before the ORDER BY. I added x like y. It is no differnt from adding x=y similar to the two equivalent statements you already had.

"SELECT * FROM test WHERE zone_id='$zone' and category_id='$category' and x like y ORDER BY id DESC"


问:
Working with sql server metadata in c#
Are there any tools out there that encapsulate the retrieval of SQL Server metadata into a nice object model?

My immediate needs are to gather these things from SQL Server 2000-2008 R2:

Databases

Tables

Foreign key constraints

Triggers

So, maybe given a SqlConnection object, I could do things like this:

```<code>var dbs = conn.GetDatabases();
var db = dbs.Single(x => x.Name == "AdventureWorks");
var tables = db.GetTables();
var triggers = db.GetAllTriggers();
</code>```

Of course, those examples would be very convenient, but any sort of object model would be better than what I'm doing now. Before I build my own, is there anything out there?

答: Maybe I'm missing something, but pretty much every ORM out there does this.  </p>

Title: Working with sql server metadata in c#

Body:
Are there any tools out there that encapsulate the retrieval of SQL Server metadata into a nice object model?

My immediate needs are to gather these things from SQL Server 2000-2008 R2:

Databases

Tables

Foreign key constraints

Triggers

So, maybe given a SqlConnection object, I could do things like this:

var dbs = conn.GetDatabases();
var db = dbs.Single(x => x.Name == "AdventureWorks");
var tables = db.GetTables();
var triggers = db.GetAllTriggers();

Of course, those examples would be very convenient, but any sort of object model would be better than what I'm doing now. Before I build my own, is there anything out there?


问:
Firebase send email function
I have been playing around with firebase tutorials and the new functions, and trying to implement this specific example:
https://github.com/firebase/functions-samples/tree/master/quickstarts/email-users

When I fire the trigger the mail does not get sent, and I get the following error in the log console:

```<code>Error: Invalid login: 535-5.7.8 Username and Password not accepted. Learn more at
535 5.7.8  https://support.google.com/mail/?p=BadCredentials 141sm3120746ioe.47 - gsmtp
    at SMTPConnection._formatError (/user_code/node_modules/nodemailer/lib/smtp-connection/index.js:557:19)
    at SMTPConnection._actionAUTHComplete (/user_code/node_modules/nodemailer/lib/smtp-connection/index.js:1248:34)
    at SMTPConnection._responseActions.push.str (/user_code/node_modules/nodemailer/lib/smtp-connection/index.js:340:26)
    at SMTPConnection._processResponse (/user_code/node_modules/nodemailer/lib/smtp-connection/index.js:706:20)
    at SMTPConnection._onData (/user_code/node_modules/nodemailer/lib/smtp-connection/index.js:509:14)
    at TLSSocket._socket.on.chunk (/user_code/node_modules/nodemailer/lib/smtp-connection/index.js:461:47)
    at emitOne (events.js:96:13)
    at TLSSocket.emit (events.js:188:7)
    at readableAddChunk (_stream_readable.js:176:18)
    at TLSSocket.Readable.push (_stream_readable.js:134:10)
</code>```

What am I doing wrong? It does not say anthing about placing some authorizations on email account. Just the password. Should be simple.

答:
If you type: firebase functions:config:get in the Terminal, you would be able to see that the gmail and password is with double quotation marks.
Mine was like this:

```<code>{
  "gmail": {
    "password": ""pass"",
    "email": ""user@gmail.com""
  }
}
</code>```

So I typed in like this in the Terminal and it worked for me:
WITHOUT QUATATION MARKS

```<code>firebase functions:config:set gmail.email=user@gmail.com gmail.password=pass
</code>```

Title: Firebase send email function

Body:
I have been playing around with firebase tutorials and the new functions, and trying to implement this specific example:
https://github.com/firebase/functions-samples/tree/master/quickstarts/email-users

When I fire the trigger the mail does not get sent, and I get the following error in the log console:

Error: Invalid login: 535-5.7.8 Username and Password not accepted. Learn more at
535 5.7.8  https://support.google.com/mail/?p=BadCredentials 141sm3120746ioe.47 - gsmtp
    at SMTPConnection._formatError (/user_code/node_modules/nodemailer/lib/smtp-connection/index.js:557:19)
    at SMTPConnection._actionAUTHComplete (/user_code/node_modules/nodemailer/lib/smtp-connection/index.js:1248:34)
    at SMTPConnection._responseActions.push.str (/user_code/node_modules/nodemailer/lib/smtp-connection/index.js:340:26)
    at SMTPConnection._processResponse (/user_code/node_modules/nodemailer/lib/smtp-connection/index.js:706:20)
    at SMTPConnection._onData (/user_code/node_modules/nodemailer/lib/smtp-connection/index.js:509:14)
    at TLSSocket._socket.on.chunk (/user_code/node_modules/nodemailer/lib/smtp-connection/index.js:461:47)
    at emitOne (events.js:96:13)
    at TLSSocket.emit (events.js:188:7)
    at readableAddChunk (_stream_readable.js:176:18)
    at TLSSocket.Readable.push (_stream_readable.js:134:10)

What am I doing wrong? It does not say anthing about placing some authorizations on email account. Just the password. Should be simple.

Body:
If you type: firebase functions:config:get in the Terminal, you would be able to see that the gmail and password is with double quotation marks.
Mine was like this:

{
  "gmail": {
    "password": ""pass"",
    "email": ""user@gmail.com""
  }
}

So I typed in like this in the Terminal and it worked for me:
WITHOUT QUATATION MARKS

firebase functions:config:set gmail.email=user@gmail.com gmail.password=pass


问:
Temporarily Stop One Function Execution with setTimeOut() when a Button is Clicked
I have an animation triggered by a scroll event, which makes a menu slide out of view. There is also a button that when clicked brings the menu back into view.

Because the menu can be closed by scrolling, when the user clicks the button to bring the menu in, if they scroll during this period of the animation, the menu disappears again without the animation completing.

I have put together a simplified version of the animation here http://codepen.io/emilychews/pen/evbzMQ

I need to temporarily prevent the scroll function working after the button is clicked, which I'm assuming would be best done with the setTimeout() method on the click function?  I've tried a number of things but can't seem to solve it/ get it to work.

Any help would be awesome.  For quick reference as well the code is below

JQUERY

```<code>jQuery(document).ready(function($){

    // slide menu to left on scroll
    function hideOnScroll() {
      $(window).scroll(function() {
        if ( $(document).scrollTop() > 1) {

          $('.menubox').css('left', '-25%');

      }

    });

  }

  hideOnScroll(); // call hideOnScroll function

  // click handler to bring menu back in
  $('.mybutton').on('click', function() {

      $('.menubox').css('left', '0%');

      var scrollPause = setTimeout(hideOnScroll, 2000)  // temporarily pause hideOnScroll function

    });

}); //end of jQuery
</code>```

CSS

```<code>body {
 margin: 0;
 padding: 0;
 height: 200vh;}

.menubox {
  top: 100;
  position: fixed;
  width: 20%;
  height: 100%;
  background: red;
  padding: 10px;
  color: white;
  transition: all 2s;
}

.mybutton {
  position: fixed;
  left: 40%;
  top: 50px;
  padding: 5px 10px;
}
</code>```

HTML

```<code><div class="menubox">Menu Box</div>

<button class="mybutton">Click to bring back menu</button>
</code>```

** Also please note I've simplified the animation for the sake of the forum, the actual animation function contains Greensock code, but I didn't want to include this in case it confused the issue. I can't therefore just use the .addClass() and .removeClass() or have a workaround that changes the given CSS or scrollTop() values.  I need to disable the hideOnScroll() function when the button is clicked for the duration of the click invoked animation - which in the examples is 2s. Thus I think the only way to achieve this is with the setTimeOut() method (i may be wrong on this).  But I can't get it to work.

Many thanks

Emily

答:
you can simply check the offset is complete.

```<code>function hideOnScroll() {
  $(window).scroll(function() {
    if ( $(document).scrollTop() > 1) {
     if( $('.menubox').offset().left == 0 ){
        $('.menubox').css('left', '-25%');
      }
   });
 }
</code>```

http://codepen.io/anon/pen/aJXGbr

Body:
I have an animation triggered by a scroll event, which makes a menu slide out of view. There is also a button that when clicked brings the menu back into view.

Because the menu can be closed by scrolling, when the user clicks the button to bring the menu in, if they scroll during this period of the animation, the menu disappears again without the animation completing.

I have put together a simplified version of the animation here http://codepen.io/emilychews/pen/evbzMQ

I need to temporarily prevent the scroll function working after the button is clicked, which I'm assuming would be best done with the setTimeout() method on the click function?  I've tried a number of things but can't seem to solve it/ get it to work.

Any help would be awesome.  For quick reference as well the code is below

JQUERY

jQuery(document).ready(function($){

    // slide menu to left on scroll
    function hideOnScroll() {
      $(window).scroll(function() {
        if ( $(document).scrollTop() > 1) {

          $('.menubox').css('left', '-25%');

      }

    });

  }

  hideOnScroll(); // call hideOnScroll function

  // click handler to bring menu back in
  $('.mybutton').on('click', function() {

      $('.menubox').css('left', '0%');

      var scrollPause = setTimeout(hideOnScroll, 2000)  // temporarily pause hideOnScroll function

    });

}); //end of jQuery

CSS

body {
 margin: 0;
 padding: 0;
 height: 200vh;}

.menubox {
  top: 100;
  position: fixed;
  width: 20%;
  height: 100%;
  background: red;
  padding: 10px;
  color: white;
  transition: all 2s;
}

.mybutton {
  position: fixed;
  left: 40%;
  top: 50px;
  padding: 5px 10px;
}

HTML

Menu Box

<button class="mybutton">Click to bring back menu</button>

** Also please note I've simplified the animation for the sake of the forum, the actual animation function contains Greensock code, but I didn't want to include this in case it confused the issue. I can't therefore just use the .addClass() and .removeClass() or have a workaround that changes the given CSS or scrollTop() values.  I need to disable the hideOnScroll() function when the button is clicked for the duration of the click invoked animation - which in the examples is 2s. Thus I think the only way to achieve this is with the setTimeOut() method (i may be wrong on this).  But I can't get it to work.

Many thanks

Emily

Body:
you can simply check the offset is complete.

function hideOnScroll() {
  $(window).scroll(function() {
    if ( $(document).scrollTop() > 1) {
     if( $('.menubox').offset().left == 0 ){
        $('.menubox').css('left', '-25%');
      }
   });
 }

http://codepen.io/anon/pen/aJXGbr


问:
Modal window create from Partial View (ASP.NET MVC)
I have View where I display list of Emails

I need to create new record in table using modal window and Partial View.

Here is code of Partial View

```<code>    @model SmartSolutions.Models.Question

<div>
    <div class="form-group" style="text-align:center;padding-bottom: 40px; padding-top: 30px;">
         @Html.TextAreaFor(m => m.question, new { @class = "form-control", placeholder = "Вопрос", id = "question" })
    </div>
    <div class="form-group" style="text-align:center;padding-bottom: 40px; padding-top: 30px;">
        @Html.TextAreaFor(m => m.TimeForAnswer, new { @class = "form-control", placeholder = "Время на ответ", id = "answer" })
    </div>
    <div class="form-group" style="text-align:center;padding-bottom: 40px; padding-top: 30px;">
        @Html.TextAreaFor(m => m.TimeForReady, new { @class = "form-control", placeholder = "Время на подготовку" , id = "prepare" })
    </div>
    <div class="form-group" style="text-align:center;padding-bottom: 40px; padding-top: 30px;">
        @Html.TextAreaFor(m => m.Retries, new { @class = "form-control", placeholder = "Попытки", id = "retries" })
    </div>
    <div class="form-group" style="text-align:center">
        <input type="button" id="save" value="Создать" class="btn btn-default" style="margin-right: 40px;" />
    </div>
</div>
<script>
       $(document).ready(function () {
        $('#save').click(function () {
            save();
        });
    });
        function save() {
            $.ajax({
                type: 'Post',
                dataType: 'Json',
                data: {
                    Question_new: $('#question').val(),
                    Answer: $('#answer').val(),
                    Preparing: $('#prepare').val(),
                    Retries: $('#retries').val(),
                      },
                url: '@Url.Action("WelcomeWriter", "Interwier")',
                success: function (da) {
                    if (da.Result === "Success") {

                        window.location.href = da.RedirectUrl;

                    } else {

                        alert('Error' + da.Message);
                    }
                },
                error: function (da) {
                    alert('Error');
                }
            });
        }
</script>
</code>```

I make Partial View and AJAX call in Partial View

Here is code for post method

```<code>  public ActionResult CreateNewQuestion( string Question_new, string Answer, string Preparing, string Retries)
    {
        Question quest = new Question
        {

            question = Question_new,
            TimeForAnswer = Answer,
            TimeForReady = Preparing,
            Retries = Retries,
        };
        db.Questions.Add(quest);
        db.SaveChanges();

        return Json(new { Result = "Success", Message = "Saved Successfully"});

    }
</code>```

I have View where on button click I need to display modal with Partial View in it. And when in modal I click #save button it will close.

Here is how it looks now (it's just goes to new View)

```<code> <div style="height: 20%;">
            <button class="btn btn-default" style="margin-top: 15px; margin-left: 20px;">
                @Html.ActionLink("Добавить вопрос", "Create", "Questions", null, new { @style = "color:white;" })
            </button>
            <button class="btn btn-default" style="margin-top: 15px; margin-left: 200px;">
                @Html.ActionLink("Далее", "RoleForSending", "Questions", null, new { @style = "color:white;" })
            </button>
        </div>
</code>```

How I can realize this?

答:
you can use jQuery UI/bootstrap to show your modal.

I would do this with jQuery UI:

1 - Insert your partial_view in your primary view

```<code><div id="containerForPartialView">
    @Html.Partial("~/<pathOfYourPartial>", <yourModel>)
</div>
</code>```

2 - Initialize your modal in javascript (in your primary view)

```<code>var myFormDialog = $("containerForPartialView").dialog(
   {autoOpen : false, modal : true});
</code>```

3 - Make your button simple

```<code><button id="myButtonForShowDialog">Create new question</button>
</code>```

4 - Attach an event on your button to show your dialog (I mean the "button" tag in your primary view):

```<code>$("myButtonForShowDialog").button().on("click", function() {
    myFormDialog.dialog("open");
});
</code>```

For a complete jQuery UI reference look here: jQuery UI Modal dialog

For a reference to boostrap modal look here: Bootstrap modal

Body:
I have View where I display list of Emails

I need to create new record in table using modal window and Partial View.

Here is code of Partial View

    @model SmartSolutions.Models.Question

         @Html.TextAreaFor(m => m.question, new { @class = "form-control", placeholder = "Вопрос", id = "question" })

        @Html.TextAreaFor(m => m.TimeForAnswer, new { @class = "form-control", placeholder = "Время на ответ", id = "answer" })

        @Html.TextAreaFor(m => m.TimeForReady, new { @class = "form-control", placeholder = "Время на подготовку" , id = "prepare" })

        @Html.TextAreaFor(m => m.Retries, new { @class = "form-control", placeholder = "Попытки", id = "retries" })

        <input type="button" id="save" value="Создать" class="btn btn-default" style="margin-right: 40px;" />

I make Partial View and AJAX call in Partial View

Here is code for post method

  public ActionResult CreateNewQuestion( string Question_new, string Answer, string Preparing, string Retries)
    {
        Question quest = new Question
        {

            question = Question_new,
            TimeForAnswer = Answer,
            TimeForReady = Preparing,
            Retries = Retries,
        };
        db.Questions.Add(quest);
        db.SaveChanges();

        return Json(new { Result = "Success", Message = "Saved Successfully"});

    }

I have View where on button click I need to display modal with Partial View in it. And when in modal I click #save button it will close.

Here is how it looks now (it's just goes to new View)

            <button class="btn btn-default" style="margin-top: 15px; margin-left: 20px;">
                @Html.ActionLink("Добавить вопрос", "Create", "Questions", null, new { @style = "color:white;" })
            </button>
            <button class="btn btn-default" style="margin-top: 15px; margin-left: 200px;">
                @Html.ActionLink("Далее", "RoleForSending", "Questions", null, new { @style = "color:white;" })
            </button>

How I can realize this?

Body:
you can use jQuery UI/bootstrap to show your modal.

I would do this with jQuery UI:

1 - Insert your partial_view in your primary view

<div id="containerForPartialView">
    @Html.Partial("~/<pathOfYourPartial>", <yourModel>)
</div>

2 - Initialize your modal in javascript (in your primary view)

var myFormDialog = $("containerForPartialView").dialog(
   {autoOpen : false, modal : true});

3 - Make your button simple

<button id="myButtonForShowDialog">Create new question</button>

4 - Attach an event on your button to show your dialog (I mean the "button" tag in your primary view):

$("myButtonForShowDialog").button().on("click", function() {
    myFormDialog.dialog("open");
});

For a complete jQuery UI reference look here: jQuery UI Modal dialog

For a reference to boostrap modal look here: Bootstrap modal


问:
Variable substitution in PL/pgSQL
I have a select statement that is generated dynamically based on the supplied parameter. The problem is that postgresql always says:

argument of WHERE must be type boolean, not type character varying no matter what the parameter is. Did I miss anything?

```<code>CREATE OR REPLACE FUNCTION getuid(name character varying) RETURNS integer AS $$
    DECLARE
        statement varchar;
        uid integer;
    BEGIN
        IF ($1 = '') THEN
            statement := 'TRUE';
            statement := CAST(statement AS BOOLEAN);
        ELSE
            statement := 'users.keywords ILIKE''' || '%' || $1 || '%''';
        END IF;
        SELECT INTO uid id FROM users WHERE "statement";
        RETURN uid;
    END;
$$ LANGUAGE plpgsql
</code>```

答:
EXECUTE is a PL/pgSQL statement and not SQL statement. So you have to wrap your dynamic query into PL/pgSQL stored procedure.

Be careful about variable substitution and do not forget to use quote_literal() or quote_nullable() when building up you query.

Have look in documentation here: http://www.postgresql.org/docs/current/static/plpgsql-statements.html#PLPGSQL-STATEMENTS-EXECUTING-DYN

Title: Variable substitution in PL/pgSQL

Body:
I have a select statement that is generated dynamically based on the supplied parameter. The problem is that postgresql always says:

argument of WHERE must be type boolean, not type character varying no matter what the parameter is. Did I miss anything?

CREATE OR REPLACE FUNCTION getuid(name character varying) RETURNS integer AS $$
    DECLARE
        statement varchar;
        uid integer;
    BEGIN
        IF ($1 = '') THEN
            statement := 'TRUE';
            statement := CAST(statement AS BOOLEAN);
        ELSE
            statement := 'users.keywords ILIKE''' || '%' || $1 || '%''';
        END IF;
        SELECT INTO uid id FROM users WHERE "statement";
        RETURN uid;
    END;
$$ LANGUAGE plpgsql


问:
error: 'CLOCK_MONOTONIC' undeclared (first use in this function)
I tried to build the Pixel Intensity Comparison-based Object detection (pico) code in opencv 3.0, while building i got an error like   error: 'CLOCK_MONOTONIC' undeclared (first use in this function) . Can any tell how to overcome these issues?? The code is as follows along with the error i got

```<code>float getticks()
{
    struct timespec ts;

    if(clock_gettime(CLOCK_MONOTONIC, &ts) < 0)
    {
        printf("clock_gettime error\n");

        return -1.0f;
    }

    return ts.tv_sec + 1e-9f*ts.tv_nsec;
}
</code>```

and the error i got as

```<code>picolrn.c:94:18: error: storage size of 'ts' isn't known
  struct timespec ts;
                  ^
picolrn.c:96:19: error: 'CLOCK_MONOTONIC' undeclared (first use in this function)
  if(clock_gettime(CLOCK_MONOTONIC, &ts) < 0)
                   ^
picolrn.c:96:19: note: each undeclared identifier is reported only once for each function it appears in
make.exe[2]: *** [build/Debug/MinGW_1-Windows/picolrn.o] Error 1
</code>```

答:
Add a commandline switch: -D_POSIX_C_SOURCE=199309L when compiling.

Without it, time.h header will not define it.

Body:
I tried to build the Pixel Intensity Comparison-based Object detection (pico) code in opencv 3.0, while building i got an error like   error: 'CLOCK_MONOTONIC' undeclared (first use in this function) . Can any tell how to overcome these issues?? The code is as follows along with the error i got

float getticks()
{
    struct timespec ts;

    if(clock_gettime(CLOCK_MONOTONIC, &ts) < 0)
    {
        printf("clock_gettime error\n");

        return -1.0f;
    }

    return ts.tv_sec + 1e-9f*ts.tv_nsec;
}

and the error i got as

picolrn.c:94:18: error: storage size of 'ts' isn't known
  struct timespec ts;
                  ^
picolrn.c:96:19: error: 'CLOCK_MONOTONIC' undeclared (first use in this function)
  if(clock_gettime(CLOCK_MONOTONIC, &ts) < 0)
                   ^
picolrn.c:96:19: note: each undeclared identifier is reported only once for each function it appears in
make.exe[2]: *** [build/Debug/MinGW_1-Windows/picolrn.o] Error 1


问:
how to do a query to select some selected datas on group by
I have a table like below structure:

```<code>ID|PrcessorID|BatchNO|NoOfTransaction|BatchCreatedDate
1 |20        |2      |3              |2017-03-28
2 |21        |3      |3              |2017-04-01
3 |21        |4      |7              |2017-04-01
4 |20        |5      |3              |2017-04-01
5 |21        |6      |2              |2017-04-02
6 |20        |7      |4              |2017-04-02
</code>```

and another table is like

```<code>ProcessorID|ProcessorName
20         |Payme
21         |Payany
</code>```

I have to get the data total no of transaction and count of the batch on each specific date by each specific processor of 3 days ago group by the processor so that I can get data like:

```<code>PrcessorName|Batchcount|TotNoOfTransaction|BatchCreatedDate

     Payany |2         |10                |2017-04-01
     Payme  |1         |3                 |2017-04-01
     Payany |1         |2                 |2017-04-02
      Payme |1         |4                 |2017-04-02
</code>```

What i am doin right now is:

```<code>Select a.ProcessorId As ProcessorID,b.ProcessorName As ProcessorName,BatchCreatedDate,Sum(NoofTRansaction) As TotNoofTransaction,Count(BatchNo) As BatchCountfrom TableA a innerjoin TableB b on a.ProcessorID=b.ProcessorID where BatchcreatedDate<GetDate() and BatchCreatedDate>GetDate()-4 groupby ProcessorName,BatchCreatedDate
</code>```

but this query is giving me result like

```<code>PrcessorName|Batchcount|TotNoOfTransaction|BatchCreatedDate

     Payany |1         |3                 |2017-04-01
     Payany |1         |7                 |2017-04-01
     Payme  |1         |3                 |2017-04-01
     Payany |1         |2                 |2017-04-02
      Payme |1         |4                 |2017-04-02
</code>```

答:
My best guess is that BatchCreatedDate has a time component.  Does this do what you want?

```<code>Select a.ProcessorId As ProcessorID, b.ProcessorName As ProcessorName,
       cast(BatchCreatedDate as date) as bcd,
       Sum(NoofTRansaction) As TotNoofTransaction,
       Count(BatchNo) As BatchCount
from TableA a inner join
     TableB b
     on a.ProcessorID = b.ProcessorID
where BatchcreatedDate < GetDate() and BatchCreatedDate > GetDate()-4
group by a.ProcessorId, b.ProcessorName, cast(BatchCreatedDate as date);
</code>```

Body:
I have a table like below structure:

ID|PrcessorID|BatchNO|NoOfTransaction|BatchCreatedDate
1 |20        |2      |3              |2017-03-28
2 |21        |3      |3              |2017-04-01
3 |21        |4      |7              |2017-04-01
4 |20        |5      |3              |2017-04-01
5 |21        |6      |2              |2017-04-02
6 |20        |7      |4              |2017-04-02

and another table is like

ProcessorID|ProcessorName
20         |Payme
21         |Payany

I have to get the data total no of transaction and count of the batch on each specific date by each specific processor of 3 days ago group by the processor so that I can get data like:

PrcessorName|Batchcount|TotNoOfTransaction|BatchCreatedDate

     Payany |2         |10                |2017-04-01
     Payme  |1         |3                 |2017-04-01
     Payany |1         |2                 |2017-04-02
      Payme |1         |4                 |2017-04-02

What i am doin right now is:

Select a.ProcessorId As ProcessorID,b.ProcessorName As ProcessorName,BatchCreatedDate,Sum(NoofTRansaction) As TotNoofTransaction,Count(BatchNo) As BatchCountfrom TableA a innerjoin TableB b on a.ProcessorID=b.ProcessorID where BatchcreatedDate<GetDate() and BatchCreatedDate>GetDate()-4 groupby ProcessorName,BatchCreatedDate

but this query is giving me result like

PrcessorName|Batchcount|TotNoOfTransaction|BatchCreatedDate

     Payany |1         |3                 |2017-04-01
     Payany |1         |7                 |2017-04-01
     Payme  |1         |3                 |2017-04-01
     Payany |1         |2                 |2017-04-02
      Payme |1         |4                 |2017-04-02

Body:
My best guess is that BatchCreatedDate has a time component.  Does this do what you want?

Select a.ProcessorId As ProcessorID, b.ProcessorName As ProcessorName,
       cast(BatchCreatedDate as date) as bcd,
       Sum(NoofTRansaction) As TotNoofTransaction,
       Count(BatchNo) As BatchCount
from TableA a inner join
     TableB b
     on a.ProcessorID = b.ProcessorID
where BatchcreatedDate < GetDate() and BatchCreatedDate > GetDate()-4
group by a.ProcessorId, b.ProcessorName, cast(BatchCreatedDate as date);


问:
Sharing an audio file
I am trying to share an audio file with a button, but when I click on it, the application shows a message "The file format isn't supported". How can I solve this? Here is my code</p>

```<code>Button buonaseeera=(Button) findViewById(R.id.pulsantebuonaseeera);

    buonaseeera.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            audiobuonaseeera=MediaPlayer.create(getApplicationContext(), R.raw.buonaseeeraaudio);
            audiobuonaseeera.start();

    Button sharebutton=(Button) findViewById(R.id.sharebutton);
            sharebutton.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    String sharePath =
Environment.getExternalStorageDirectory().getPath()
                            + "raw2sd";
                    Uri uri = Uri.parse(sharePath);
                    Intent share = new Intent(Intent.ACTION_SEND);
                    share.setType("audio/*");
                    share.putExtra(Intent.EXTRA_STREAM, uri);
                    startActivity(Intent.createChooser(share, "Share Audio
File"));
</code>```

答:
Try this Example:</p>

```<code>public class MusicPlayerActivity extends AppCompatActivity {
Activity mactivity;
private Button btn_shareaudio;

@Override
protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_music_player);

        mactivity = this;

        btn_shareaudio = (Button) findViewById(R.id.btn_activity_music_player_shareaudio);

        btn_shareaudio.setOnClickListener(
            new View.OnClickListener() {
            @Override
            public void onClick(View v) {
            File f = new File(/*Path of the song*/);
            Uri uri = Uri.parse("file://" + f.getAbsolutePath());
            Intent share = new Intent(Intent.ACTION_SEND);
            share.putExtra(Intent.EXTRA_STREAM, uri);
            share.setType("audio/*");
            share.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            mactivity.startActivity(Intent.createChooser(share, "Share audio File"));

            Toast.makeText(getApplicationContext(), "Song Shared Successfully", Toast.LENGTH_SHORT).show();
            }
       });
}
</code>```

Title: Sharing an audio file

Body:
I am trying to share an audio file with a button, but when I click on it, the application shows a message "The file format isn't supported". How can I solve this? Here is my code

Button buonaseeera=(Button) findViewById(R.id.pulsantebuonaseeera);

    buonaseeera.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            audiobuonaseeera=MediaPlayer.create(getApplicationContext(), R.raw.buonaseeeraaudio);
            audiobuonaseeera.start();

    Button sharebutton=(Button) findViewById(R.id.sharebutton);
            sharebutton.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    String sharePath =
Environment.getExternalStorageDirectory().getPath()
                            + "raw2sd";
                    Uri uri = Uri.parse(sharePath);
                    Intent share = new Intent(Intent.ACTION_SEND);
                    share.setType("audio/*");
                    share.putExtra(Intent.EXTRA_STREAM, uri);
                    startActivity(Intent.createChooser(share, "Share Audio
File"));

Body:
Try this Example:

public class MusicPlayerActivity extends AppCompatActivity {
Activity mactivity;
private Button btn_shareaudio;

@Override
protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_music_player);

        mactivity = this;

        btn_shareaudio = (Button) findViewById(R.id.btn_activity_music_player_shareaudio);

        btn_shareaudio.setOnClickListener(
            new View.OnClickListener() {
            @Override
            public void onClick(View v) {
            File f = new File(/*Path of the song*/);
            Uri uri = Uri.parse("file://" + f.getAbsolutePath());
            Intent share = new Intent(Intent.ACTION_SEND);
            share.putExtra(Intent.EXTRA_STREAM, uri);
            share.setType("audio/*");
            share.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            mactivity.startActivity(Intent.createChooser(share, "Share audio File"));

            Toast.makeText(getApplicationContext(), "Song Shared Successfully", Toast.LENGTH_SHORT).show();
            }
       });
}


问:
In jenkins what will be my Playbook path ? how to set up Inventory there are 3 option for the same
I have installed the Jenkins and ansible on my AWS Instance centos
and am trying to call my ansible playbook  from jenkins ?
I dont know how to set up : what will be my Playbook path ?
how to set up Inventory there are 3 option for the same (
1. Do not specify Inventory
2. File or host list

3.Inline content)
Help me out so that i call my ansible to run from jenkins

答:
I am giving you the simple example, please ask in the comments if you need some specific help. Let's say, you job name is "stackoverflow" then you can put the ansible-scripts directory inside the /var/lib/jenkins/jobs/stackoverflow/workspace and use it in your jenkins job like this:

After that you can use the shell environment:

Once you will configure this job then you can use it as you are normally using the ansible from the command line:

Please adjust the settings as per your environment.Hope this will help you


问:
For React, if we used "create-react-app hello-world" to create the app, is there a command to lint all JS files?
If we used

```<code>create-react-app hello-world
</code>```

to create the React app, is there a command to lint all JS files that we added later, and possibly validate all HTML and CSS files?

答:
The documentation says that you should be getting console lint statements automatically while running the app in development mode with npm start

If you are looking for linting in your editor, you need to configure that. See the two sections:

Syntax Highlighting in the Editor

and right below that

Displaying Lint Output in the Editor

Body:
If we used

create-react-app hello-world

to create the React app, is there a command to lint all JS files that we added later, and possibly validate all HTML and CSS files?


问:
SQL Server 2014 dbCreator role not created
Installed SQL server 2014 using

```<code>en_sql_server_2014_management_studio_with_service_pack_2_x64_9009295.exe
</code>```

First, I am not getting the screen where you can create default instance and create sa login. So once it got installed, I go to SQL Server Express and logged in with Windows Authentication, but I see a Red downward arrow for sa login under Security\Logins. This makes me unable to create database giving error

CREATE DATABASE permission denied in database master. (Microsoft SQL Server, Error:262)

Please advise!

答: change the type of authentification from windows authentification to sql server authentification and give the dbowner to sa in master database</p>

Body:
Installed SQL server 2014 using

en_sql_server_2014_management_studio_with_service_pack_2_x64_9009295.exe

First, I am not getting the screen where you can create default instance and create sa login. So once it got installed, I go to SQL Server Express and logged in with Windows Authentication, but I see a Red downward arrow for sa login under Security\Logins. This makes me unable to create database giving error

CREATE DATABASE permission denied in database master. (Microsoft SQL Server, Error:262)

Please advise!


问:
Can I connect to remote DB server from inside docker container?
My app is running against a mssql server 2012 or above,

I tried to set up 2 containers - 1 for my app and one to be a DB server.

But I couldn't use the DB container due to mssql server version windows image is not supported by my app.

So I'm want to connect to a remote DB server that I have which is a different server than the Docker host.

How do I get the container to ping the remote DB server?

From the container-

```<code>C:\Installation>ping  my0134.company.net
Ping request could not find host my0134.company.net. Please check the name and try again.
</code>```

** NOTE - I am using Docker on windows

答: If IPV4 forwarding is enabled then container can connect to DB Server.There is no issue with that.</p>

Body:
My app is running against a mssql server 2012 or above,

I tried to set up 2 containers - 1 for my app and one to be a DB server.

But I couldn't use the DB container due to mssql server version windows image is not supported by my app.

So I'm want to connect to a remote DB server that I have which is a different server than the Docker host.

How do I get the container to ping the remote DB server?

From the container-

C:\Installation>ping  my0134.company.net
Ping request could not find host my0134.company.net. Please check the name and try again.

** NOTE - I am using Docker on windows


问:
What would be better architecture out of these, to scale a system?
Lets assume, I am running one machine which has nodejs, websocket service and redis services running on it. I want to distribute the system from scale perspective, which of these two approaches will be better :

Run each service on different machine. So two machines for Websocket service behind a load balancer, one machine for nodejs, three machines for Redis.

Keep running all services on same machine and now clone this machine to five other machines and run them all behind a load balancer.

I have always worked upon / seen first architecture. But an experienced dev ops person advised me to go for 2nd approach, he says it is easy to manage and scales better.

Also, this is not specific to nodejs, redis etc. I mentioned them to explain better. I want to know in general which is better architecture.

答:
The second approach is usually better, especially if you can configure the load balancer to route traffic to a node which has all the data required to process the request. This type of architecture is called Shared Nothing Architecture as the different nodes are completely isolated and a failure in one cannot affect another node. This type of architecture scales almost linearly (is not linearly, as you still need to replicate data for high availability, but this can also be done asynchronously if possible).

Alternatively you can have all the data in all nodes... but that might be expensive and replication might become an issue, in particular if you need synchronous replication.


问:
Modify CSS to hide
I need to hide the "Actions" menu from a document library's toolbar. I know in CSS I can use this "{display: none}" syntax to hide.

Can someone please help find me the right place where I need to put this? I found this .ms-actionbar but dont know if this guy belong to list toolbar or site toolbar.

For example:  http://www.xsolive.com/Shared%20Documents/Forms/AllItems.aspx

答:
This CSS rule will hide the elements from your toolbar :

```<code>.ms-menutoolbar td
{
    display:none;
}
</code>```

Note that this will hide all the menus from your toolbar though. If there are other buttons you want to show in the toolbar you'll have to modify it though. Using the id of that particular button will work.

For the URL you provided, the rule would be :

```<code>#zz8_ListActionsMenu_t
{
    display:none;
}
</code>```

For your question :

Not with css you can't. The "Actions" menu is generated dynamically by SharePoint and it's ID won't always be the same.
You can do it with javascript though.

Here is how you would do it with jQuery :

```<code>$(document).ready(function() {
    var link = $('a[id$="ListActionsMenu"]').filter(':contains("Actions")');
    link.parent().hide();
});
</code>```

A very simplified version of the HTML code looks like this for the menu :

```<code><div id="zz8_ListActionsMenu_t">
    <a id="zz8_ListActionsMenu">Actions</a>
</div>
</code>```

What the jQuery code does is that it first finds all the  with an ID that ends with ListActionsMenu (which should limit the selection to the content of the toolbar) and then finds the one with the text "Action".
It then removes the whole div.

Title: Modify CSS to hide

Body:
This CSS rule will hide the elements from your toolbar :

.ms-menutoolbar td
{
    display:none;
}

Note that this will hide all the menus from your toolbar though. If there are other buttons you want to show in the toolbar you'll have to modify it though. Using the id of that particular button will work.

For the URL you provided, the rule would be :

#zz8_ListActionsMenu_t
{
    display:none;
}

For your question :

Not with css you can't. The "Actions" menu is generated dynamically by SharePoint and it's ID won't always be the same.
You can do it with javascript though.

Here is how you would do it with jQuery :

$(document).ready(function() {
    var link = $('a[id$="ListActionsMenu"]').filter(':contains("Actions")');
    link.parent().hide();
});

A very simplified version of the HTML code looks like this for the menu :

<div id="zz8_ListActionsMenu_t">
    <a id="zz8_ListActionsMenu">Actions</a>
</div>

What the jQuery code does is that it first finds all the <a> with an ID that ends with ListActionsMenu (which should limit the selection to the content of the toolbar) and then finds the one with the text "Action".
It then removes the whole div.


问:
Can't setup Python environment on vanilla Ubuntu Server
I wrote a simple Python server which, among others things, uses tabula-py wrapper for the Java library Tabula. After testing it locally, using a corresponding client and determining everything works, I attempted to run it on a vanilla Ubuntu Server 16.04 VBox instance. As I was getting a runtime error (same as below), I attempted a simple test using Python CLI:

```<code>>>> import tabula
>>> df = tabula.read_pdf("https://www.autotrolej.hr/att/wp-content/uploads/2016/04/lin-2-vazi-od-16-01-2017.pdf")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/home/ubuntu/.local/lib/python2.7/site-packages/tabula/wrapper.py", line 54, in read_pdf_table
    output = subprocess.check_output(args)
  File "/usr/lib/python2.7/subprocess.py", line 567, in check_output
    process = Popen(stdout=PIPE, *popenargs, **kwargs)
  File "/usr/lib/python2.7/subprocess.py", line 711, in __init__
errread, errwrite)
  File "/usr/lib/python2.7/subprocess.py", line 1343, in _execute_child
    raise child_exception
OSError: [Errno 2] No such file or directory
</code>```

Server is started from the command line and the shebang used is:

```<code>#!/usr/bin/env python
</code>```

I tried exporting pip freeze requirements and installing the same libraries on the VBox server, only to get the same subprocess error during installation for many of those libraries. I'm guessing it's a Python environment problem as Ubuntu Server does not have Python preinstalled so I probably neglected installing an important core library or setting an environment variable. What am I missing?

答:
As the project description of tabula-py says:

Simple wrapper of tabula-java

Tabula-java requires Java. Make sure that you have Java installed on your computer. To make sure that java works, type java -version.

Body:
I wrote a simple Python server which, among others things, uses tabula-py wrapper for the Java library Tabula. After testing it locally, using a corresponding client and determining everything works, I attempted to run it on a vanilla Ubuntu Server 16.04 VBox instance. As I was getting a runtime error (same as below), I attempted a simple test using Python CLI:

>>> import tabula
>>> df = tabula.read_pdf("https://www.autotrolej.hr/att/wp-content/uploads/2016/04/lin-2-vazi-od-16-01-2017.pdf")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/home/ubuntu/.local/lib/python2.7/site-packages/tabula/wrapper.py", line 54, in read_pdf_table
    output = subprocess.check_output(args)
  File "/usr/lib/python2.7/subprocess.py", line 567, in check_output
    process = Popen(stdout=PIPE, *popenargs, **kwargs)
  File "/usr/lib/python2.7/subprocess.py", line 711, in __init__
errread, errwrite)
  File "/usr/lib/python2.7/subprocess.py", line 1343, in _execute_child
    raise child_exception
OSError: [Errno 2] No such file or directory

Server is started from the command line and the shebang used is:

#!/usr/bin/env python

I tried exporting pip freeze requirements and installing the same libraries on the VBox server, only to get the same subprocess error during installation for many of those libraries. I'm guessing it's a Python environment problem as Ubuntu Server does not have Python preinstalled so I probably neglected installing an important core library or setting an environment variable. What am I missing?


问:
Activiti BPM works with Eclipse neon?
I am new to Java development and working with Activiti BPM.
I am getting started with them.

Activiti BPM says its verified with Eclipse Kepler. However I am using Eclipse Neon currently. I am trying to install Activiti plugin. It says it has to uninstall some plugins like Hana Cloud Plugins to continue with installation.

However I need both the plugins. So thought of using Eclipse Kepler to use Activiti BPM. But it supports till Apache Server 7 only ( and I have Apache 9 with Eclipse Neon )

Please suggest me a possible solution
1) Use Different eclipses to work with Hana Cloud Platform tools, Activiti BPM (Is it possible to setup multiple Apache Servers in same pc like Apache7 and Apache 9)
2) Can be done in Same Eclipse

May be its a quite silly question, please guide me as i am beginner.

答:
Of Course it does!!

I have installed activiti with Eclipse Neon and Apache tomcat 8/9 and it works pretty well.

I have also written a super detailed blog post on this, which starting from the setup, shows how to create not one but two fully working (although, simple) workflows.

You can check it out here and see if it helps.

Title: Activiti BPM works with Eclipse neon?