问:
CarrierWave not work with Cloudinary

In user.rb

class User < ApplicationRecord
    mount_uploader :picture, PictureUploader
end

In picture_uploader.rb

class PictureUploader < CarrierWave::Uploader::Base

include Cloudinary::CarrierWave

storage :file

# This is a sensible default for uploaders that are meant to be mounted:

def store_dir
    "uploads/#{model.class.to_s.underscore}/#{mounted_as}/#{model.id}"
  end

end

In environement.rb

require_relative 'application'

initialize the Rails application

Rails.application.initialize!

require 'carrierwave/orm/activerecord'

In _form.html.erb

```<code><%= form.label :picture %>

<%= form.file_field :picture, id: :user_picture %>
</code>```

In migration

class CreateUsers < ActiveRecord::Migration[5.1]

def change

create_table :users do |t|

```<code>  t.string :email

  t.string :picture

  t.timestamps

end
</code>```

end

end

Finally User.picture_url is an url on Cloudinary but there isn't any image uploaded in this url.

And it works if I type in rails c
Cloudinary::Uploader.upload('/home/my_image.jpg')

答:
The Cloudinary's hot line anwser :

"please comment out lines 10 and 15-17" in /app/uploader/pictures_uploader.rb

# storage :file

# def store_dir
  #   "uploads/#{model.class.to_s.underscore}/#{mounted_as}/#{model.id}"
  # end

And it works.

Title: CarrierWave not work with Cloudinary

Body:
In user.rb

class User < ApplicationRecord
    mount_uploader :picture, PictureUploader
end

In picture_uploader.rb

class PictureUploader < CarrierWave::Uploader::Base

include Cloudinary::CarrierWave

storage :file

# This is a sensible default for uploaders that are meant to be mounted:

def store_dir
    "uploads/#{model.class.to_s.underscore}/#{mounted_as}/#{model.id}"
  end

end

In environement.rb

require_relative 'application'

initialize the Rails application

Rails.application.initialize!

require 'carrierwave/orm/activerecord'

In _form.html.erb

<%= form.label :picture %>

<%= form.file_field :picture, id: :user_picture %>

In migration

class CreateUsers < ActiveRecord::Migration[5.1]

def change

create_table :users do |t|

  t.string :email

  t.string :picture

  t.timestamps

end

end

end

Finally User.picture_url is an url on Cloudinary but there isn't any image uploaded in this url.

And it works if I type in rails c
Cloudinary::Uploader.upload('/home/my_image.jpg')


来源: stackexchange

问:
C++ conversion from unsigned char to std::string
Intro: Consider that I have no experience with C++, but can find my way around any language to do basic tasks.
Most of my experience is with .net languages (vn.net and C#), php and js, so please explain as if you were teaching a complete noob.

Here is the problem: I receive data in an unsigned char characters[12]; and I have to then append that data to a std::string

data is always 12 characters long, and is not null terminated, because it is gathered by selecting specific bytes received from serial port.

Long story short:

```<code>std::string stroutput = "some text ";
unsigned char characters[12];
characters[0]=64; //demo data to shorten the code
characters[1]=72;
stroutput.append(characters[0]);
stroutput.append(characters[1]);
....
</code>```

The result i want is to have the string value

```<code>some text @H...
</code>```

But what i get is an error while compiling

```<code>error: invalid conversion from ‘unsigned char’ to ‘const char*’ [-fpermissive]
stroutput.append(characters[0]);
                 ~~~~~~~~~~~~^
</code>```

Logic behind this thinking is that output of:

```<code>printf("%c%c",characters[0],characters[1]);
</code>```

and

```<code>std::cout << characters[0] << characters[0] << std::endl;
</code>```

results in

```<code>@H
</code>```

So: How do I convert unsigned char something[12] to std::string?

Thanks

Edit: Sorry for the duplicate, search didn't return that question.
Thanks everyone - too bad I can't mark multiple answers!

答:
std::string has a constructorr that takes two iterators:

```<code>stroutput += std::string(characters, characters + 12);
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Intro: Consider that I have no experience with C++, but can find my way around any language to do basic tasks.
Most of my experience is with .net languages (vn.net and C#), php and js, so please explain as if you were teaching a complete noob.

Here is the problem: I receive data in an unsigned char characters[12]; and I have to then append that data to a std::string

data is always 12 characters long, and is not null terminated, because it is gathered by selecting specific bytes received from serial port.

Long story short:

std::string stroutput = "some text ";
unsigned char characters[12];
characters[0]=64; //demo data to shorten the code
characters[1]=72;
stroutput.append(characters[0]);
stroutput.append(characters[1]);
....

The result i want is to have the string value

some text @H...

But what i get is an error while compiling

error: invalid conversion from ‘unsigned char’ to ‘const char*’ [-fpermissive]
stroutput.append(characters[0]);
                 ~~~~~~~~~~~~^

Logic behind this thinking is that output of:

printf("%c%c",characters[0],characters[1]);

and

std::cout << characters[0] << characters[0] << std::endl;

results in

@H

So: How do I convert unsigned char something[12] to std::string?

Thanks

Edit: Sorry for the duplicate, search didn't return that question.
Thanks everyone - too bad I can't mark multiple answers!

Body:
std::string has a constructorr that takes two iterators:

stroutput += std::string(characters, characters + 12);


问:
Element having a class only and I am unable to click on "OK"
How do I click on the following button "OK" using XPath:

```<code>driver.findElement (By.xpath ("//button[@class='btn btn-primary crtBtn btn btn-default']");
</code>```

Screenshot:

答:
Hello you can try this xpath :

```<code>.//button[@type='button']
</code>```

Also put wait as  Thread.sleep before clicking this element.

Body:
How do I click on the following button "OK" using XPath:

driver.findElement (By.xpath ("//button[@class='btn btn-primary crtBtn btn btn-default']");

Screenshot:

Body:
Hello you can try this xpath :

.//button[@type='button']

Also put wait as  Thread.sleep before clicking this element.


问:
how to convert HH:MM representation to minutes in oracle sql
how to convert varchar(hh:mm) to minutes in oracle sql.

For example:

```<code>HH:MM    Minutes
08:00    480
08:45    525
07:57    477
</code>```

答:
This will work even if the duration is 24 hours or greater:

SQL Fiddle

Oracle 11g R2 Schema Setup:

```<code>CREATE TABLE durations ( duration ) AS
SELECT '00:30' FROM DUAL UNION ALL
SELECT '07:57' FROM DUAL UNION ALL
SELECT '08:00' FROM DUAL UNION ALL
SELECT '12:00' FROM DUAL UNION ALL
SELECT '20:01' FROM DUAL UNION ALL
SELECT '23:59' FROM DUAL UNION ALL
SELECT '24:00' FROM DUAL UNION ALL
SELECT '24:59' FROM DUAL;
</code>```

Query 1:

```<code>SELECT duration,
       ( (
         DATE '1970-01-01'
         + NUMTODSINTERVAL( SUBSTR( duration, 1, INSTR( duration, ':' ) - 1 ), 'HOUR' )
         + NUMTODSINTERVAL( SUBSTR( duration, INSTR( duration, ':' ) + 1 ), 'MINUTE' )
         )
         - DATE '1970-01-01'
       ) * 24 * 60 AS Minutes
FROM   durations
</code>```

Results:

```<code>| DURATION | MINUTES |
|----------|---------|
|    00:30 |      30 |
|    07:57 |     477 |
|    08:00 |     480 |
|    12:00 |     720 |
|    20:01 |    1201 |
|    23:59 |    1439 |
|    24:00 |    1440 |
|    24:59 |    1499 |
</code>```

However, there is an INTERVAL DAY TO SECOND data type that would be better suited to your data:

```<code>CREATE TABLE your_table (
  duration INTERVAL DAY TO SECOND
);
</code>```

Then you can just do:

```<code>INSERT INTO your_table ( duration ) VALUES ( INTERVAL '08:00' HOUR TO MINUTE );
</code>```

To get the number of minutes you can then simply do:

```<code>SELECT ( ( DATE '1970-01-01' + duration ) - DATE '1970-01-01' ) *24*60 AS minutes
FROM   your_table
</code>```

Body:
how to convert varchar(hh:mm) to minutes in oracle sql.

For example:

HH:MM    Minutes
08:00    480
08:45    525
07:57    477

Body:
This will work even if the duration is 24 hours or greater:

SQL Fiddle

Oracle 11g R2 Schema Setup:

CREATE TABLE durations ( duration ) AS
SELECT '00:30' FROM DUAL UNION ALL
SELECT '07:57' FROM DUAL UNION ALL
SELECT '08:00' FROM DUAL UNION ALL
SELECT '12:00' FROM DUAL UNION ALL
SELECT '20:01' FROM DUAL UNION ALL
SELECT '23:59' FROM DUAL UNION ALL
SELECT '24:00' FROM DUAL UNION ALL
SELECT '24:59' FROM DUAL;

Query 1:

SELECT duration,
       ( (
         DATE '1970-01-01'
         + NUMTODSINTERVAL( SUBSTR( duration, 1, INSTR( duration, ':' ) - 1 ), 'HOUR' )
         + NUMTODSINTERVAL( SUBSTR( duration, INSTR( duration, ':' ) + 1 ), 'MINUTE' )
         )
         - DATE '1970-01-01'
       ) * 24 * 60 AS Minutes
FROM   durations

Results:

| DURATION | MINUTES |
|----------|---------|
|    00:30 |      30 |
|    07:57 |     477 |
|    08:00 |     480 |
|    12:00 |     720 |
|    20:01 |    1201 |
|    23:59 |    1439 |
|    24:00 |    1440 |
|    24:59 |    1499 |

However, there is an INTERVAL DAY TO SECOND data type that would be better suited to your data:

CREATE TABLE your_table (
  duration INTERVAL DAY TO SECOND
);

Then you can just do:

INSERT INTO your_table ( duration ) VALUES ( INTERVAL '08:00' HOUR TO MINUTE );

To get the number of minutes you can then simply do:

SELECT ( ( DATE '1970-01-01' + duration ) - DATE '1970-01-01' ) *24*60 AS minutes
FROM   your_table


问:
destructure parameters with default value in typescript
If I have the following module src/mod.ts in typescript:

```<code>export interface Foo {
  foo?: number
}
export function bar({foo = 1}: Foo = {}) {
 ...
}
</code>```

It compiles fine, and I can use it within the package. However, when I compile to dist/mod.js and dist/mod.d.ts, the dist/mod.d.ts contains:

```<code>declare export function bar({foo}?: Foo)
</code>```

which causes an error when consumed in another typescript package: Type 'Foo | undefined' has no property 'foo' and no string index signature.

I haven't been able to find complaints about this w/ google (though I may be mischaracterizing the problem), so I assume I am doing something wrong. How should I be destructuring an object with default values in typescript?

答:
Try defining public properties in a class instead.</p>

```<code>export interface Foo {
  foo?: number
}

 /** @class */
export class bar {
     public foo?: number;

     constructor(obj: Foo = {} as Foo) {
         let {
              /** Set defaults for the destructured object here */
             foo = 1
         } = obj;

         /** Hint: put jsdoc comments here for inline ide auto-documentation */
         this.foo = foo;
     }
}

// Usage
const myBar = new bar({foo:1})
</code>```

Body:
If I have the following module src/mod.ts in typescript:

export interface Foo {
  foo?: number
}
export function bar({foo = 1}: Foo = {}) {
 ...
}

It compiles fine, and I can use it within the package. However, when I compile to dist/mod.js and dist/mod.d.ts, the dist/mod.d.ts contains:

declare export function bar({foo}?: Foo)

which causes an error when consumed in another typescript package: Type 'Foo | undefined' has no property 'foo' and no string index signature.

I haven't been able to find complaints about this w/ google (though I may be mischaracterizing the problem), so I assume I am doing something wrong. How should I be destructuring an object with default values in typescript?

Body:
Try defining public properties in a class instead.

export interface Foo {
  foo?: number
}

 /** @class */
export class bar {
     public foo?: number;

     constructor(obj: Foo = {} as Foo) {
         let {
              /** Set defaults for the destructured object here */
             foo = 1
         } = obj;

         /** Hint: put jsdoc comments here for inline ide auto-documentation */
         this.foo = foo;
     }
}

// Usage
const myBar = new bar({foo:1})


问:
How can I fix in Pascal: Incompatible types ("complex type" to "simple type")
I'm working on a project at school and I have to do some calculations using Pascal and show it on an LC Display.
My calculations are the following:

```<code>adc_rd := ADC_read(2);
   textlong := adc_rd*5;
   adc_rd := textlong/1023;
   decim_i := 0.4*adc_rd;
   decim_ii := pow(2.71828,decim_i);
   decim_i := 8.9116*decim_ii;
   FloatToStr_FixLen(decim_i, text4, 6);
   Lcd_Chr(2,6,text4);
</code>```

decim_i and decim_ii are reals.
I get the following error on the last line Lcd_Chr(2,6,text4);:

Incompatible types ("complex type" to "simple type")

Does anyone know how to fix it?

答:
Text4 is a string, but Lcd_Chr() expects a single character.

To solve the problem, loop through all characters in the string:

```<code>for i := 1 to Length(text4) do Lcd_Chr(1+i,6,text4[i]);
</code>```

Body:
I'm working on a project at school and I have to do some calculations using Pascal and show it on an LC Display.
My calculations are the following:

adc_rd := ADC_read(2);
   textlong := adc_rd*5;
   adc_rd := textlong/1023;
   decim_i := 0.4*adc_rd;
   decim_ii := pow(2.71828,decim_i);
   decim_i := 8.9116*decim_ii;
   FloatToStr_FixLen(decim_i, text4, 6);
   Lcd_Chr(2,6,text4);

decim_i and decim_ii are reals.
I get the following error on the last line Lcd_Chr(2,6,text4);:

Incompatible types ("complex type" to "simple type")

Does anyone know how to fix it?

Body:
Text4 is a string, but Lcd_Chr() expects a single character.

To solve the problem, loop through all characters in the string:

for i := 1 to Length(text4) do Lcd_Chr(1+i,6,text4[i]);


问:
Issues with Python while loop
I am currently having issues with a while loop in python

```<code>! curl https://raw.githubusercontent.com/MicrosoftLearning/intropython/master/world_temp_mean.csv -o mean_temp.txt

mean_temp = open("mean_temp.txt", "a+")
mean_temp.write("Rio de Janeiro,Brazil,30.0,18.0\n")
mean_temp.seek(0)
headings = mean_temp.readline().split(",")

while mean_temp.readline():
    city_temp = mean_temp.readline().split(",")
    print(headings[0].title(), "of",  city_temp[0], headings[2], "is",
    city_temp[2], "Celcius")
</code>```

This code currently skips the first and every other line when printing

Current output:

City of Cairo month ave: highest high is 34.7 Celcius

City of Nairobi month ave: highest high is 26.3 Celcius

City of Sydney month ave: highest high is 26.5 Celcius

City of Rio de Janeiro month ave: highest high is 30.0 Celcius

Required output:

City of Beijing month ave: highest high is 30.9 Celsius

City of Cairo month ave: highest high is 34.7 Celsius

City of London month ave: highest high is 23.5 Celsius

City of Nairobi month ave: highest high is 26.3 Celsius

City of New York City month ave: highest high is 28.9 Celsius

City of Sydney month ave: highest high is 26.5 Celsius

City of Tokyo month ave: highest high is 30.8 Celsius

City of Rio De Janeiro month ave: highest high is 30.0 Celsius

Thanks for your help

答:
A while loop is not the appropriate thing to use here. Instead, use a for loop; in Python, a file can be iterated over directly.</p>

```<code>for line in mean_temp:
    city_temp = line.split(",")
</code>```

Title: Issues with Python while loop

Body:
I am currently having issues with a while loop in python

! curl https://raw.githubusercontent.com/MicrosoftLearning/intropython/master/world_temp_mean.csv -o mean_temp.txt

mean_temp = open("mean_temp.txt", "a+")
mean_temp.write("Rio de Janeiro,Brazil,30.0,18.0\n")
mean_temp.seek(0)
headings = mean_temp.readline().split(",")

while mean_temp.readline():
    city_temp = mean_temp.readline().split(",")
    print(headings[0].title(), "of",  city_temp[0], headings[2], "is",
    city_temp[2], "Celcius")

This code currently skips the first and every other line when printing

Current output:

City of Cairo month ave: highest high is 34.7 Celcius

City of Nairobi month ave: highest high is 26.3 Celcius

City of Sydney month ave: highest high is 26.5 Celcius

City of Rio de Janeiro month ave: highest high is 30.0 Celcius

Required output:

City of Beijing month ave: highest high is 30.9 Celsius

City of Cairo month ave: highest high is 34.7 Celsius

City of London month ave: highest high is 23.5 Celsius

City of Nairobi month ave: highest high is 26.3 Celsius

City of New York City month ave: highest high is 28.9 Celsius

City of Sydney month ave: highest high is 26.5 Celsius

City of Tokyo month ave: highest high is 30.8 Celsius

City of Rio De Janeiro month ave: highest high is 30.0 Celsius

Thanks for your help

Body:
A while loop is not the appropriate thing to use here. Instead, use a for loop; in Python, a file can be iterated over directly.

for line in mean_temp:
    city_temp = line.split(",")


问:
IntelliJ/PhpStorm inline @var with magic fields
I am trying to define with a PHPDoc inline @var a magic field variable to set the correct type but the IDE is not auto-completing anything.

It is showing "Field accessed via magic method". I tried to remove it from the Inspections settings but then the warning is not showed and still it is not auto-completing.

I have tried different ways without success:

/** @var \NameSpace\SomeClass $this->field */
$this->field->someMethod(); // Not auto-completing

/** @var \NameSpace\SomeClass $this::field */
$this->field->someMethod(); // Not auto-completing
```

<p>For other hand if I define a new variable it will work:</p>

<pre class="lang-php prettyprint-override"><code>$field = $this->field;

/** @var \NameSpace\SomeClass $field */
$field->someMethod(); // Auto-completing correctly
</code>```

Somebody knows how to do it to work the auto-completing feature without define a new variable? Is it possible?

UPDATE: I cannot use the @property attribute because $field is not always the same class in the main class.

答:
It has to be done via @property tag at class-level PHPDoc comment.

```<code>/**
 * My special class
 *
 * @property \NameSpace\SomeClass $field Optional my magical variable description
 */
class MySpecialClass {
....
</code>```

https://docs.phpdoc.org/references/phpdoc/tags/property.html

```<code>/** @var \NameSpace\SomeClass $this->field */
</code>```

This will never work -- you cannot provide typehint for 2nd level variable/element ($this->field) using inline @var. If anything: only first level entities can be typehinted.

Body:
I am trying to define with a PHPDoc inline @var a magic field variable to set the correct type but the IDE is not auto-completing anything.

It is showing "Field accessed via magic method". I tried to remove it from the Inspections settings but then the warning is not showed and still it is not auto-completing.

I have tried different ways without success:

/** @var \NameSpace\SomeClass $this->field */
$this->field->someMethod(); // Not auto-completing

/** @var \NameSpace\SomeClass $this::field */
$this->field->someMethod(); // Not auto-completing

For other hand if I define a new variable it will work:

$field = $this->field;

/** @var \NameSpace\SomeClass $field */
$field->someMethod(); // Auto-completing correctly

Somebody knows how to do it to work the auto-completing feature without define a new variable? Is it possible?

UPDATE: I cannot use the @property attribute because $field is not always the same class in the main class.

Body:
It has to be done via @property tag at class-level PHPDoc comment.

/**
 * My special class
 *
 * @property \NameSpace\SomeClass $field Optional my magical variable description
 */
class MySpecialClass {
....

https://docs.phpdoc.org/references/phpdoc/tags/property.html

/** @var \NameSpace\SomeClass $this->field */

This will never work -- you cannot provide typehint for 2nd level variable/element ($this->field) using inline @var. If anything: only first level entities can be typehinted.


问:
unable to dismiss Progress dialog using dismiss method in android
```<code>class CShowProgress(context: Context) {
    var s_m_oCShowProgress: CShowProgress? = null
    lateinit var m_Dialog: Dialog
    private var m_ProgressBar: ProgressBar? = null
    private var progressText: TextView? = null

    fun getInstance(): CShowProgress {
        if (s_m_oCShowProgress == null) {
            s_m_oCShowProgress = CShowProgress(context!!)
        }
        return s_m_oCShowProgress as CShowProgress
    }

    fun show(m_Context: Context, message: String) {
        m_Dialog = Dialog(m_Context)
        m_Dialog.requestWindowFeature(Window.FEATURE_NO_TITLE)
        m_Dialog.setContentView(R.layout.progress_bar)
        m_ProgressBar = m_Dialog.findViewById(R.id.progressBar_cyclic)
        m_ProgressBar!!.visibility = View.VISIBLE
        m_ProgressBar!!.isIndeterminate = true
        m_Dialog.setCancelable(false)
        m_Dialog.setCanceledOnTouchOutside(false)
        m_Dialog.show()
    }

    fun dismiss(m_Context: Context) {
        m_Dialog = Dialog(m_Context)
        m_Dialog.dismiss()
    }
}
</code>```

This is my singlton class for custom Progress dialog for show dialog we have show method and for dismiss we have dismiss method  i am calling this class

```<code>    CShowProgress(this).getInstance().show(this, "Please wait..")
     and for dismiss i am calling

    CShowProgress(this).getInstance().dismiss(this)
</code>```

using show i am able to show Progress dialog but using dimiss i am not able to dismiss can any one please tell me what i am doing wrong i am using kotlin language .

答:
When you call your dismiss fun you create a new unshown dialog and trying to dismiss it.

Here i modified your dismiss func. I think this'll help you.g

```<code>fun dismiss() {
    if(m_Dialog.isShowing){
        m_Dialog.dismiss()
    }
}
</code>```

Edit:

Oh sorry i did not check your singleton pattern. When you call CShowProgress(this) you create a new instance of your class so you cannot dismiss previous ones dialogs.

You can create a Singleton like below:

```<code>companion object {
    lateinit var instance: CShowProgress
        private set
}
</code>```

And init like this:

```<code>instance = CShowProgress(context)
</code>```

And use show dialog like this:

```<code>CShowProgress.instance.show(context,message)
</code>```

And dimiss it like this:

```<code>CShowProgress.instance.dismiss()
</code>```

But i think if you refactor code like this, you'll still face another issue i explained below.

Also when you show a new dialog you loose reference to your old dialog so you cannot dismiss it. Basicly you're creating n dialog but only hold reference to your last created dialog. So you cannot dismiss previous ones. So if you go on like this you can dismiss your previous dialog if exists before showing a new one. But this pattern is hard to manage multiple alert dialogs so i suggest you to change it.

```<code>fun show(m_Context: Context, message: String) {
        if(m_Dialog.isShowing){
            m_Dialog.dismiss()
        }
        m_Dialog = Dialog(m_Context)
        m_Dialog.requestWindowFeature(Window.FEATURE_NO_TITLE)
        m_Dialog.setContentView(R.layout.progress_bar)
        m_ProgressBar = m_Dialog.findViewById(R.id.progressBar_cyclic)
        m_ProgressBar!!.visibility = View.VISIBLE
        m_ProgressBar!!.isIndeterminate = true
        m_Dialog.setCancelable(false)
        m_Dialog.setCanceledOnTouchOutside(false)
        m_Dialog.show()
    }
</code>```

Finally passing Activity context to a singleton object and do not clear when activity onDestroy will cause memory leaks.

Body:
class CShowProgress(context: Context) {
    var s_m_oCShowProgress: CShowProgress? = null
    lateinit var m_Dialog: Dialog
    private var m_ProgressBar: ProgressBar? = null
    private var progressText: TextView? = null

    fun getInstance(): CShowProgress {
        if (s_m_oCShowProgress == null) {
            s_m_oCShowProgress = CShowProgress(context!!)
        }
        return s_m_oCShowProgress as CShowProgress
    }

    fun show(m_Context: Context, message: String) {
        m_Dialog = Dialog(m_Context)
        m_Dialog.requestWindowFeature(Window.FEATURE_NO_TITLE)
        m_Dialog.setContentView(R.layout.progress_bar)
        m_ProgressBar = m_Dialog.findViewById(R.id.progressBar_cyclic)
        m_ProgressBar!!.visibility = View.VISIBLE
        m_ProgressBar!!.isIndeterminate = true
        m_Dialog.setCancelable(false)
        m_Dialog.setCanceledOnTouchOutside(false)
        m_Dialog.show()
    }

    fun dismiss(m_Context: Context) {
        m_Dialog = Dialog(m_Context)
        m_Dialog.dismiss()
    }
}

This is my singlton class for custom Progress dialog for show dialog we have show method and for dismiss we have dismiss method  i am calling this class

    CShowProgress(this).getInstance().show(this, "Please wait..")
     and for dismiss i am calling

    CShowProgress(this).getInstance().dismiss(this)

using show i am able to show Progress dialog but using dimiss i am not able to dismiss can any one please tell me what i am doing wrong i am using kotlin language .

Body:
When you call your dismiss fun you create a new unshown dialog and trying to dismiss it.

Here i modified your dismiss func. I think this'll help you.g

fun dismiss() {
    if(m_Dialog.isShowing){
        m_Dialog.dismiss()
    }
}

Edit:

Oh sorry i did not check your singleton pattern. When you call CShowProgress(this) you create a new instance of your class so you cannot dismiss previous ones dialogs.

You can create a Singleton like below:

companion object {
    lateinit var instance: CShowProgress
        private set
}

And init like this:

instance = CShowProgress(context)

And use show dialog like this:

CShowProgress.instance.show(context,message)

And dimiss it like this:

CShowProgress.instance.dismiss()

But i think if you refactor code like this, you'll still face another issue i explained below.

Also when you show a new dialog you loose reference to your old dialog so you cannot dismiss it. Basicly you're creating n dialog but only hold reference to your last created dialog. So you cannot dismiss previous ones. So if you go on like this you can dismiss your previous dialog if exists before showing a new one. But this pattern is hard to manage multiple alert dialogs so i suggest you to change it.

fun show(m_Context: Context, message: String) {
        if(m_Dialog.isShowing){
            m_Dialog.dismiss()
        }
        m_Dialog = Dialog(m_Context)
        m_Dialog.requestWindowFeature(Window.FEATURE_NO_TITLE)
        m_Dialog.setContentView(R.layout.progress_bar)
        m_ProgressBar = m_Dialog.findViewById(R.id.progressBar_cyclic)
        m_ProgressBar!!.visibility = View.VISIBLE
        m_ProgressBar!!.isIndeterminate = true
        m_Dialog.setCancelable(false)
        m_Dialog.setCanceledOnTouchOutside(false)
        m_Dialog.show()
    }

Finally passing Activity context to a singleton object and do not clear when activity onDestroy will cause memory leaks.


问:
Python read CSV to string conversion
I have a CSV with following values

```<code>ID, Value
1, a
2, b
3, c
</code>```

How can I convert this csv to following string using Python

```<code>[('ID', 'Value'), (1, 'a'), (2, 'b'), (3, 'c')]
</code>```

I was trying with the following code

```<code>with open('sample.csv', 'rb') as csvfile:
    reader = csv.reader(csvfile, delimiter=' ', quotechar='|')
    for row in reader:
        data = ', '.join(row)
        rows.append(data)
print rows
</code>```

Am getting following output only

```<code>["'ID','Value'", "1,'a'", "2,'b'", "3,'c'"]
</code>```

答:
Do not read with rb but just r:

```<code>with open('sample.csv', 'r') as csvfile:
    csvtext = csvfile.readlines()

mylist = []
for line in csvtext:
    mylist.append(tuple(line.strip().split(', ')))
print(mylist)
</code>```

Title: Python read CSV to string conversion

Body:
I have a CSV with following values

ID, Value
1, a
2, b
3, c

How can I convert this csv to following string using Python

[('ID', 'Value'), (1, 'a'), (2, 'b'), (3, 'c')]

I was trying with the following code

with open('sample.csv', 'rb') as csvfile:
    reader = csv.reader(csvfile, delimiter=' ', quotechar='|')
    for row in reader:
        data = ', '.join(row)
        rows.append(data)
print rows

Am getting following output only

["'ID','Value'", "1,'a'", "2,'b'", "3,'c'"]

Body:
Do not read with rb but just r:

with open('sample.csv', 'r') as csvfile:
    csvtext = csvfile.readlines()

mylist = []
for line in csvtext:
    mylist.append(tuple(line.strip().split(', ')))
print(mylist)


问:
How to save jwt token from session storage into variable?
I made jwt authorization and I stored that token into session storage , but when i try to get that token into string and log it i get null , this is the function

```<code>login(user : User): void
  {
    this.header= new Headers({"content-Type": "application/json"});
    this.osobaService.create(user,this.tokenUrl,this.header).then(p=> {sessionStorage.setItem("Token",p._body.slice(1,-1))});
    this.tokenString = sessionStorage.getItem("Token");
    console.log(this.tokenString);
  }
</code>```

It should be simple getItem method but I'm getting null .

答:
The 'this.osobaService.create' is a async function. You are trying to log a value, before writing it. If you change your code like this, this should log a correct value.</p>

```<code>login(user : User): void
  {
    this.header= new Headers({"content-Type": "application/json"});
    this.osobaService.create(user,this.tokenUrl,this.header)
        .then(p=> {
             sessionStorage.setItem("Token",p._body.slice(1,-1))
             this.tokenString = sessionStorage.getItem("Token");
             console.log(this.tokenString);
        });
  }
</code>```

Body:
I made jwt authorization and I stored that token into session storage , but when i try to get that token into string and log it i get null , this is the function

login(user : User): void
  {
    this.header= new Headers({"content-Type": "application/json"});
    this.osobaService.create(user,this.tokenUrl,this.header).then(p=> {sessionStorage.setItem("Token",p._body.slice(1,-1))});
    this.tokenString = sessionStorage.getItem("Token");
    console.log(this.tokenString);
  }

It should be simple getItem method but I'm getting null .

Body:
The 'this.osobaService.create' is a async function. You are trying to log a value, before writing it. If you change your code like this, this should log a correct value.

login(user : User): void
  {
    this.header= new Headers({"content-Type": "application/json"});
    this.osobaService.create(user,this.tokenUrl,this.header)
        .then(p=> {
             sessionStorage.setItem("Token",p._body.slice(1,-1))
             this.tokenString = sessionStorage.getItem("Token");
             console.log(this.tokenString);
        });
  }


问:
C# Visio Containers
I am struggling getting to the contents (children) of a Container using C#.
Works fine if just drawn on the page, but once converted to a master, it is no longer recognized as a 'container'.

So, for example.
Create a new container from the 'Insert' tab.
From the 'Home' tab, draw 2 rectangles in the container, type some text in each, and then 'add to underlying container'.

After this, the code below reports the 2 rectangle Names & Texts.

However, I now drag the container into my stencil to create a master.
Then I drag the master to the page to create an instance.

Now the code does not find any MemberShapes at all.

What am I doing wrong ?
Any advice/guidance appreciated !!

```<code>    foreach (Microsoft.Office.Interop.Visio.Shape shape in Globals.ThisAddIn.Application.ActivePage.Shapes)
                {

                    System.Diagnostics.Debug.WriteLine(shape.Name);

                    if (shape.ContainerProperties != null) {
                        foreach (int memberID in shape.ContainerProperties.GetMemberShapes(0)) {
                            Microsoft.Office.Interop.Visio.Shape vsoShape = Globals.ThisAddIn.Application.ActivePage.Shapes.ItemFromID[memberID];
                            Debug.Print(vsoShape.Name);
                            Debug.Print(vsoShape.Text);
                        }
                    }
}
</code>```

答:
It's your master creation that's giving you trouble I suspect.  If you drag your new container onto your doc stencil to create a master the member shapes come along for the ride.  However, Visio likes masters to be grouped and if they're not it will group them on drop.  If you ungroup your new instance shape (container and members) and then run your code again it should report as expected.  The problem with this is that it breaks the link with the master.

I think you'll need to break up your shapes up into separate member and container masters.

If you were dropping a List type container shape then you could instruct Visio to drop additional list item shapes using the User.msvSDListItemMaster + EventDrop combo.  (See "Specifying a shape to insert into lists" section of the Custom Containers, Lists and Callouts in Visio 2010 post for more details.)  Unfortunately this doesn't work for straight container shapes as the drop position of the new member shapes isn't known.

If you want to have a prepopulated container then one option would be to either listen for the drop event in code and add the new members in the handler, or, fire a MarkerEvent with the QUEUEMARKEREVENT ShapeSheet function from the EventDrop cell.  Again, this implies that you'll then need to be listening for and process Application Marker Events.

I don't know how familiar you are with Visio events, but I covered them in the code part of the videos found here:

http://visualsignals.typepad.co.uk/vislog/2016/04/new-visio-training-videos.html

Update 13th Dec 2017 - adding associated course files post as well, which demos code used in course:

http://visualsignals.typepad.co.uk/vislog/2017/01/course-files-for-visio-flyby-for-developers-on-ch9.html

Title: C# Visio Containers

Body:
I am struggling getting to the contents (children) of a Container using C#.
Works fine if just drawn on the page, but once converted to a master, it is no longer recognized as a 'container'.

So, for example.
Create a new container from the 'Insert' tab.
From the 'Home' tab, draw 2 rectangles in the container, type some text in each, and then 'add to underlying container'.

After this, the code below reports the 2 rectangle Names & Texts.

However, I now drag the container into my stencil to create a master.
Then I drag the master to the page to create an instance.

Now the code does not find any MemberShapes at all.

What am I doing wrong ?
Any advice/guidance appreciated !!

    foreach (Microsoft.Office.Interop.Visio.Shape shape in Globals.ThisAddIn.Application.ActivePage.Shapes)
                {

                    System.Diagnostics.Debug.WriteLine(shape.Name);

                    if (shape.ContainerProperties != null) {
                        foreach (int memberID in shape.ContainerProperties.GetMemberShapes(0)) {
                            Microsoft.Office.Interop.Visio.Shape vsoShape = Globals.ThisAddIn.Application.ActivePage.Shapes.ItemFromID[memberID];
                            Debug.Print(vsoShape.Name);
                            Debug.Print(vsoShape.Text);
                        }
                    }
}


问:
How to get Default coontent-Type Android volley
I want know how to get default content-type from header in volley android

```<code>      @Override
        public Map<String, String> getHeaders() throws AuthFailureError {

            Map<String, String> headers = new HashMap<String, String>();
            headers.put("Authkey", Agent_Name);
            headers.put("apptype", "android");
            headers.put("apptoken", gcmID);
            return headers;
        }
</code>```

Here I did not mention content type,so how to get default content type.

答:
```<code>   I just append text fields to the body and created the following function to do it in multipart :

  private void buildTextPart(DataOutputStream dataOutputStream, String
parameterName, String parameterValue) throws IOException {

    dataOutputStream.writeBytes(twoHyphens + boundary + lineEnd);
    dataOutputStream.writeBytes("Content-Disposition: form-data; name=\"");
    dataOutputStream.write(parameterName.getBytes("UTF-8"));
    dataOutputStream.writeBytes(lineEnd);
    dataOutputStream.writeBytes("Content-Type: text/plain; charset=UTF-8" +
  lineEnd);
    dataOutputStream.writeBytes(lineEnd);
    dataOutputStream.write(parameterValue.getBytes("UTF-8"));
    dataOutputStream.writeBytes(lineEnd)

 }

 here mention multipart data format ,and text format as utf8,its working fine
</code>```

Body:
I want know how to get default content-type from header in volley android

      @Override
        public Map<String, String> getHeaders() throws AuthFailureError {

            Map<String, String> headers = new HashMap<String, String>();
            headers.put("Authkey", Agent_Name);
            headers.put("apptype", "android");
            headers.put("apptoken", gcmID);
            return headers;
        }

Here I did not mention content type,so how to get default content type.


问:
Object Normalization
In the same line as Database Normalization - is there an approach to object normalization, not design pattern, but the same mathematical like approach to normalizing object creation.  For example: first normal form: no repeating fields....
here's some links to DB Normalization:

http://en.wikipedia.org/wiki/Database_normalization
  http://databases.about.com/od/specificproducts/a/normalization.htm

Would this make object creation and self-documentation better?

Here's a link to a book about class normalization (guess we're really talking about classes)
http://www.agiledata.org/essays/classNormalization.html

答:
Normalization has a mathematical foundation in predicate logic, and a clear and specific goal that the same piece of information never be represented twice in a single model; the purpose of this goal is to eliminate the possibility of inconsistent information in a data model.  It can be shown via mathematical proof that if a data model has certain specific properties (that it passes tests for 1st Normal Form (1NF), 2NF, 3NF, etc.) that it is free from redundant data representation, i.e. it is Normalized.

Object orientation has no such underlying mathematical basis, and indeed, no clear and specific goal.  It is simply a design idea for introducing more abstraction.  The DRY principle, Command-Query Separation, Liskov Substitution Principle,  Open-Closed Principle, Tell-Don't-Ask, Dependency Inversion Principle, and other heuristics for improving quality of code (many of which apply to code in general, not just object oriented programs) are not absolute in nature; they are guidelines that programmers have found useful in improving understandability, maintainability, and testability of their code.

With a relational data model, you can say with absolute certainty whether it is "normalized" or not, because it must pass ALL the tests for normal form, and they are quite specific.  With an object model, on the other hand, because the goal of "understandable, maintainable, testable, etc" is rather vague, you cannot say with any certainty whether you have met that goal.  With many of the design heuristics, you cannot even say for sure whether you have followed them.  Have you followed the DRY principle if you're applying patterns to your design?  Surely repeated use of a pattern isn't DRY?  Furthermore, some of these heuristics or principles aren't always even necessarily good advice all the time.  I do try to follow Command-Query Separation, but such useful things as a Stack or a Queue violate that concept in order to give us a rather elegant and useful result.

OwnerDisplayName: meade

ContentLicense: CC BY-SA 2.5

Title: Object Normalization

LastEditorDisplayName: meade

OwnerDisplayName: Chris Teixeira


问:
How can I background the R process in ESS / Emacs?
I often run long R scripts when I start my R environment. I would like to be able to load / run the R script in Emacs / ESS and continue other work in another buffer.

When I press C-g or C-c C-c the process is interrupted, and I must restart the script.

What is the best way to background the R process in ESS / Emacs?

EDIT: Thank you for your answers and comments, but none of them address the fact that Emacs freezes when you load / run a large script and you can't change buffer.

I suppose my question is a little more general - can Emacs background a process to let you keep working?

答:
ESS runs R as asynchronous process. You don't need to background anything. You can run your code for hours and still work in ESS uninterrupted.

Your problem seems to be something else. When you execute your script you do it "visibly", i.e. your executed code is printed to the terminal. This cause Emacs to freeze.

Set ess-eval-visibly to nil and  huge chunks of code will be sent to R instantly:

```<code>(setq ess-eval-visibly nil)
</code>```

Cheers.

Update

There is a new setting for ess-eval-visibly in recent versions of ESS - 'nowait. It places your code in an inferior buffer and then sends it to the subprocess. In this way you can see your code  and all the output afterwards without waiting for the subprocess to finish.

Body:
ESS runs R as asynchronous process. You don't need to background anything. You can run your code for hours and still work in ESS uninterrupted.

Your problem seems to be something else. When you execute your script you do it "visibly", i.e. your executed code is printed to the terminal. This cause Emacs to freeze.

Set ess-eval-visibly to nil and  huge chunks of code will be sent to R instantly:

(setq ess-eval-visibly nil)

Cheers.

Update

There is a new setting for ess-eval-visibly in recent versions of ESS - 'nowait. It places your code in an inferior buffer and then sends it to the subprocess. In this way you can see your code  and all the output afterwards without waiting for the subprocess to finish.

ContentLicense: CC BY-SA 4.0


问:
MPRemoteCommandCenter does not work with Bluetooth Handsfree
I want to receive remote control events from Bluetooth Handsfree device, Below mentioned is my set of code for play and pause events.

```<code>MPRemoteCommandCenter.shared().nextTrackCommand.isEnabled = true
MPRemoteCommandCenter.shared().previousTrackCommand.isEnabled = true
MPRemoteCommandCenter.shared().nextTrackCommand.addTarget(self, action: #selector(playCommand))
MPRemoteCommandCenter.shared().previousTrackCommand.addTarget(self, action: #selector(previousCommand))
</code>```

But no such events are triggered. Any help will be appreciated.

答:
You need to call

```<code>[[UIApplication sharedApplication] beginReceivingRemoteControlEvents];
</code>```

in

```<code>viewWillAppear()
</code>```

in order to make your application get the desired events.

Body:
I want to receive remote control events from Bluetooth Handsfree device, Below mentioned is my set of code for play and pause events.

MPRemoteCommandCenter.shared().nextTrackCommand.isEnabled = true
MPRemoteCommandCenter.shared().previousTrackCommand.isEnabled = true
MPRemoteCommandCenter.shared().nextTrackCommand.addTarget(self, action: #selector(playCommand))
MPRemoteCommandCenter.shared().previousTrackCommand.addTarget(self, action: #selector(previousCommand))

But no such events are triggered. Any help will be appreciated.

Body:
You need to call

[[UIApplication sharedApplication] beginReceivingRemoteControlEvents];

in

viewWillAppear()

in order to make your application get the desired events.


问:
Does ImageIO.read() take EXIF orientation metadata into account?
In JPEG images, EXIF metadata is sometimes included and tells in what orientation the image should be shown.

The question is, whether Java's ImageIO.read() takes EXIF into account while reading a JPEG image, and automatically applies the transformation.

More concretely, if I use Java's ImageIO for converting a JPEG image with EXIF into a PNG image, is the orientation of the PNG image going to be correct? Or is the below code going to produce a PNG image without taking EXIF orientation instructions into account?

```<code>private byte[] convertToPng(byte[] imageFileAsByteArray) {
    ByteArrayInputStream bis = new ByteArrayInputStream(imageFileAsByteArray);
    BufferedImage bi = ImageIO.read(bis);
    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    ImageIO.write(bi, "png", bos);

    return bos.toByteArray();
}
</code>```

答:
The short answer is, unfortunately, no; ImageIO.read(..) (by default) does not take the Exif Orientation tag into account. Your PNG will be not be rotated accordingly.

However, all ImageIO.read(..) does internally, is to look up an appropriate ImageReader plug-in for the input, and delegate reading to it. And while the JRE-bundled plug-in does not take Exif into account, it is possible to add support for it, in a third-party ImageReader. Unfortunately, I don't know of any that do, but I am considering adding Exif orientation support to the TwelveMonkeys ImageIO JPEGImageReader in the future.

In the mean time, you have to apply the rotation yourself, by reading the metadata and rotating. The value of the orientation tag can be acquired either using the ImageIO JPEG metadata or some third-party library. I think both the mentioned metadata-extractor or TwelveMonkeys ImageIO can be used for this purpose. JAI ImageIO (using the TIFF metadata) can probably also do this.

If using the ImageIO JPEG metadata, be aware:

Note that an application wishing to interpret Exif metadata given a metadata tree structure in the javax_imageio_jpeg_image_1.0 format must check for an unknown marker segment with a tag indicating an APP1 marker and containing data identifying it as an Exif marker segment.

Body:
In JPEG images, EXIF metadata is sometimes included and tells in what orientation the image should be shown.

The question is, whether Java's ImageIO.read() takes EXIF into account while reading a JPEG image, and automatically applies the transformation.

More concretely, if I use Java's ImageIO for converting a JPEG image with EXIF into a PNG image, is the orientation of the PNG image going to be correct? Or is the below code going to produce a PNG image without taking EXIF orientation instructions into account?

private byte[] convertToPng(byte[] imageFileAsByteArray) {
    ByteArrayInputStream bis = new ByteArrayInputStream(imageFileAsByteArray);
    BufferedImage bi = ImageIO.read(bis);
    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    ImageIO.write(bi, "png", bos);

    return bos.toByteArray();
}


问:
django rest framework installation fails
How do I install the REST framework in django?

The following command throws an error on Mac OS X:

```<code>pip install djangorestframework-jsonapi
</code>```

Error:

Could not find a version that satisfies the
  requirement djangorestframework-jsonapi (from versions) No matching
  distribution found for djangorestframework-jsonapi

答: Try with pip3 install djangorestframework-jsonapi this command.

Body:
How do I install the REST framework in django?

The following command throws an error on Mac OS X:

pip install djangorestframework-jsonapi

Error:

Could not find a version that satisfies the
  requirement djangorestframework-jsonapi (from versions) No matching
  distribution found for djangorestframework-jsonapi


问:
Spring Boot SSL Client
I am new to Spring Boot.  So far I am enjoying it.  I have developed a demo SSL rest web server that correctly handles mutual X.509 certificate authentication.  Using an IE browser with self signed client & server certificates, I have tested that the demo rest web server is working correctly -- both the server and browser are successfully exchanging and validating each others certificates.

I am having trouble finding an SSL client example that shows how to include the client certificate and issue the https.  Anybody have a simple rest client example that shows how to consume my ssl server?

Best Regards,
Steve Mansfield

答:
This worked for me :</p>

```<code>TrustStrategy acceptingTrustStrategy = (X509Certificate[] chain, String authType) -> true;
javax.net.ssl.SSLContext sslContext = org.apache.http.ssl.SSLContexts.custom()
        .loadTrustMaterial(null, acceptingTrustStrategy).build();
SSLConnectionSocketFactory csf = new SSLConnectionSocketFactory(sslContext);
CloseableHttpClient httpClient = HttpClients.custom().setSSLSocketFactory(csf).build();
HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory();
requestFactory.setHttpClient(httpClient);
RestTemplate restTemplate = new RestTemplate(requestFactory);
</code>```

Title: Spring Boot SSL Client

Body:
This worked for me :

TrustStrategy acceptingTrustStrategy = (X509Certificate[] chain, String authType) -> true;
javax.net.ssl.SSLContext sslContext = org.apache.http.ssl.SSLContexts.custom()
        .loadTrustMaterial(null, acceptingTrustStrategy).build();
SSLConnectionSocketFactory csf = new SSLConnectionSocketFactory(sslContext);
CloseableHttpClient httpClient = HttpClients.custom().setSSLSocketFactory(csf).build();
HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory();
requestFactory.setHttpClient(httpClient);
RestTemplate restTemplate = new RestTemplate(requestFactory);


问:
How to do a data.table merge operation
note: this question and the following answers refer to data.table versions < 1.5.3; v. 1.5.3 was released in Feb 2011 to resolve this issue. see more recent treatment (03-2012): Translating SQL joins on foreign keys to R data.table syntax

I've been digging through the documentation for the data.table package (a replacement for data.frame that's much more efficient for certain operations), including Josh Reich's presentation on SQL and data.table at the NYC R Meetup (pdf), but can't figure this totally trivial operation out.

```<code>> x <- DT(a=1:3, b=2:4, key='a')
> x
     a b
[1,] 1 2
[2,] 2 3
[3,] 3 4
> y <- DT(a=1:3, c=c('a','b','c'), key='a')
> y
     a c
[1,] 1 a
[2,] 2 b
[3,] 3 c
> x[y]
     a b
[1,] 1 2
[2,] 2 3
[3,] 3 4
> merge(x,y)
  a b c
1 1 2 a
2 2 3 b
3 3 4 c
</code>```

The docs say "When [the first argument] is itself a data.table, a join is invoked similar to base::merge but uses binary search on the sorted key." Clearly this is not the case. Can I get the other columns from y into the result of x[y] with data.tables? It seems like it's just taking the rows of x where the key matches the key of y, but ignoring the rest of y entirely...

答:
I think using the base::merge function is not needed, as using data.table joins can be a lot faster. E.g. see the following. I make x and y data.tables with 3-3 columns:

```<code>x <- data.table( foo = 1:5, a=20:24, zoo = 5:1 )
y <- data.table( foo = 1:5, b=30:34, boo = 10:14)
setkey(x, foo)
setkey(y, foo)
</code>```

And merge both with base:merge and data.table joins to see the speed of executions:

```<code>system.time(merge(x,y))
##    user  system elapsed
##   0.027   0.000   0.023

system.time(x[,list(y,x)])
##    user  system elapsed
##   0.003   0.000   0.006
</code>```

The results are not identical, as the latter has one extra column:

```<code>merge(x,y)
##      foo  a zoo  b boo
## [1,]   1 20   5 30  10
## [2,]   2 21   4 31  11
## [3,]   3 22   3 32  12
## [4,]   4 23   2 33  13
## [5,]   5 24   1 34  14

x[,list(x,y)]
##      foo  a zoo foo.1  b boo
## [1,]   1 20   5     1 30  10
## [2,]   2 21   4     2 31  11
## [3,]   3 22   3     3 32  12
## [4,]   4 23   2     4 33  13
## [5,]   5 24   1     5 34  14
</code>```

Which could not make a big trouble :)

Title: How to do a data.table merge operation

Body:
note: this question and the following answers refer to data.table versions < 1.5.3; v. 1.5.3 was released in Feb 2011 to resolve this issue. see more recent treatment (03-2012): Translating SQL joins on foreign keys to R data.table syntax

I've been digging through the documentation for the data.table package (a replacement for data.frame that's much more efficient for certain operations), including Josh Reich's presentation on SQL and data.table at the NYC R Meetup (pdf), but can't figure this totally trivial operation out.

> x <- DT(a=1:3, b=2:4, key='a')
> x
     a b
[1,] 1 2
[2,] 2 3
[3,] 3 4
> y <- DT(a=1:3, c=c('a','b','c'), key='a')
> y
     a c
[1,] 1 a
[2,] 2 b
[3,] 3 c
> x[y]
     a b
[1,] 1 2
[2,] 2 3
[3,] 3 4
> merge(x,y)
  a b c
1 1 2 a
2 2 3 b
3 3 4 c

The docs say "When [the first argument] is itself a data.table, a join is invoked similar to base::merge but uses binary search on the sorted key." Clearly this is not the case. Can I get the other columns from y into the result of x[y] with data.tables? It seems like it's just taking the rows of x where the key matches the key of y, but ignoring the rest of y entirely...

Body:
I think using the base::merge function is not needed, as using data.table joins can be a lot faster. E.g. see the following. I make x and y data.tables with 3-3 columns:

x <- data.table( foo = 1:5, a=20:24, zoo = 5:1 )
y <- data.table( foo = 1:5, b=30:34, boo = 10:14)
setkey(x, foo)
setkey(y, foo)

And merge both with base:merge and data.table joins to see the speed of executions:

system.time(merge(x,y))
##    user  system elapsed
##   0.027   0.000   0.023

system.time(x[,list(y,x)])
##    user  system elapsed
##   0.003   0.000   0.006

The results are not identical, as the latter has one extra column:

merge(x,y)
##      foo  a zoo  b boo
## [1,]   1 20   5 30  10
## [2,]   2 21   4 31  11
## [3,]   3 22   3 32  12
## [4,]   4 23   2 33  13
## [5,]   5 24   1 34  14

x[,list(x,y)]
##      foo  a zoo foo.1  b boo
## [1,]   1 20   5     1 30  10
## [2,]   2 21   4     2 31  11
## [3,]   3 22   3     3 32  12
## [4,]   4 23   2     4 33  13
## [5,]   5 24   1     5 34  14

Which could not make a big trouble :)


问:
Change JRE in a NetBeans project
I have a NetBeans project which is using the JRE 1.4 environment which means I can't use generics.

How can I change the project to use 1.6(?), so I can use generics?

答:
In NetBeans 8.2,

right click the project, and select Properties

under the menu build/compile, select the Java platform from the drop down menu

Title: Change JRE in a NetBeans project


问:
Tomcat has OutOfMemoryError in Java heap space(InvocationTargetException)
Only do a simple Form post action in browser, The tomcat report

java.lang.OutOfMemoryError: Java heap space

  java.lang.reflect.InvocationTargetException

likes below. But only one computer (all browsers) has that problem, other computer has no problem.

```<code>Struts Problem Report
Struts has detected an unhandled exception:
Messages:
Java heap space
Stacktraces
java.lang.reflect.InvocationTargetException
    sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    java.lang.reflect.Method.invoke(Method.java:498)
    com.opensymphony.xwork2.DefaultActionInvocation.invokeAction(DefaultActionInvocation.java:452)
    com.opensymphony.xwork2.DefaultActionInvocation.invokeActionOnly(DefaultActionInvocation.java:291)
    com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:254)
    com.opensymphony.xwork2.interceptor.DefaultWorkflowInterceptor.doIntercept(DefaultWorkflowInterceptor.java:176)
    com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:98)
    com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:248)
    com.opensymphony.xwork2.validator.ValidationInterceptor.doIntercept(ValidationInterceptor.java:263)
    org.apache.struts2.interceptor.validation.AnnotationValidationInterceptor.doIntercept(AnnotationValidationInterceptor.java:68)
    com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:98)
    com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:248)
    com.opensymphony.xwork2.interceptor.ConversionErrorInterceptor.intercept(ConversionErrorInterceptor.java:133)
    com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:248)
    com.opensymphony.xwork2.interceptor.ParametersInterceptor.doIntercept(ParametersInterceptor.java:207)
    com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:98)
    com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:248)
    com.opensymphony.xwork2.interceptor.ParametersInterceptor.doIntercept(ParametersInterceptor.java:207)
    com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:98)
    com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:248)
    com.opensymphony.xwork2.interceptor.StaticParametersInterceptor.intercept(StaticParametersInterceptor.java:190)
    com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:248)
    org.apache.struts2.interceptor.MultiselectInterceptor.intercept(MultiselectInterceptor.java:75)
    com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:248)
    org.apache.struts2.interceptor.CheckboxInterceptor.intercept(CheckboxInterceptor.java:94)
    com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:248)
    org.apache.struts2.interceptor.FileUploadInterceptor.intercept(FileUploadInterceptor.java:314)
    com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:248)
    com.opensymphony.xwork2.interceptor.ModelDrivenInterceptor.intercept(ModelDrivenInterceptor.java:100)
    com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:248)
    com.opensymphony.xwork2.interceptor.ScopedModelDrivenInterceptor.intercept(ScopedModelDrivenInterceptor.java:141)
    com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:248)
    org.apache.struts2.interceptor.debugging.DebuggingInterceptor.intercept(DebuggingInterceptor.java:267)
    com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:248)
    com.opensymphony.xwork2.interceptor.ChainingInterceptor.intercept(ChainingInterceptor.java:142)
    com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:248)
    com.opensymphony.xwork2.interceptor.PrepareInterceptor.doIntercept(PrepareInterceptor.java:166)
    com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:98)
    com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:248)
    com.opensymphony.xwork2.interceptor.I18nInterceptor.intercept(I18nInterceptor.java:176)
    com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:248)
    org.apache.struts2.interceptor.ServletConfigInterceptor.intercept(ServletConfigInterceptor.java:164)
    com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:248)
    com.opensymphony.xwork2.interceptor.AliasInterceptor.intercept(AliasInterceptor.java:190)
    com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:248)
    com.opensymphony.xwork2.interceptor.ExceptionMappingInterceptor.intercept(ExceptionMappingInterceptor.java:187)
    com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:248)
    org.apache.struts2.impl.StrutsActionProxy.execute(StrutsActionProxy.java:52)
    org.apache.struts2.dispatcher.Dispatcher.serviceAction(Dispatcher.java:485)
    org.apache.struts2.dispatcher.ng.ExecuteOperations.executeAction(ExecuteOperations.java:77)
    org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter.doFilter(StrutsPrepareAndExecuteFilter.java:91)
    org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
    org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
    org.apache.struts2.dispatcher.ActionContextCleanUp.doFilter(ActionContextCleanUp.java:102)
    org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
    org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
    org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:199)
    org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96)
    org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:475)
    org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:140)
    org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:80)
    org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:624)
    org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:87)
    org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:342)
    org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:498)
    org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66)
    org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:796)
    org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1366)
    org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
    java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
    java.lang.Thread.run(Thread.java:748)

java.lang.OutOfMemoryError: Java heap space

You are seeing this page because development mode is enabled. Development mode, or devMode, enables extra debugging behaviors and reports to assist developers. To disable this mode, set:
  struts.devMode=false
in your WEB-INF/classes/struts.properties file.
</code>```

I'm not familiar with Tomcat, Thank you ALL!

答:
-If you run tomcat for than 10 pc, try config like that:
Tomcat8w.exe -> java tab -> set value(You can increase value to run.):
Initial memory: 512, Max memory: 1024, Thread Stack: 2000

-If 1-3pc, with 8gb ram add in
Java options: -XX:MaxpermSize=4096m
Initial memory: 4096, Max memory: 4096, Thread Stack: 2048

Body:
Only do a simple Form post action in browser, The tomcat report

java.lang.OutOfMemoryError: Java heap space

  java.lang.reflect.InvocationTargetException

likes below. But only one computer (all browsers) has that problem, other computer has no problem.

Struts Problem Report
Struts has detected an unhandled exception:
Messages:
Java heap space
Stacktraces
java.lang.reflect.InvocationTargetException
    sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    java.lang.reflect.Method.invoke(Method.java:498)
    com.opensymphony.xwork2.DefaultActionInvocation.invokeAction(DefaultActionInvocation.java:452)
    com.opensymphony.xwork2.DefaultActionInvocation.invokeActionOnly(DefaultActionInvocation.java:291)
    com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:254)
    com.opensymphony.xwork2.interceptor.DefaultWorkflowInterceptor.doIntercept(DefaultWorkflowInterceptor.java:176)
    com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:98)
    com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:248)
    com.opensymphony.xwork2.validator.ValidationInterceptor.doIntercept(ValidationInterceptor.java:263)
    org.apache.struts2.interceptor.validation.AnnotationValidationInterceptor.doIntercept(AnnotationValidationInterceptor.java:68)
    com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:98)
    com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:248)
    com.opensymphony.xwork2.interceptor.ConversionErrorInterceptor.intercept(ConversionErrorInterceptor.java:133)
    com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:248)
    com.opensymphony.xwork2.interceptor.ParametersInterceptor.doIntercept(ParametersInterceptor.java:207)
    com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:98)
    com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:248)
    com.opensymphony.xwork2.interceptor.ParametersInterceptor.doIntercept(ParametersInterceptor.java:207)
    com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:98)
    com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:248)
    com.opensymphony.xwork2.interceptor.StaticParametersInterceptor.intercept(StaticParametersInterceptor.java:190)
    com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:248)
    org.apache.struts2.interceptor.MultiselectInterceptor.intercept(MultiselectInterceptor.java:75)
    com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:248)
    org.apache.struts2.interceptor.CheckboxInterceptor.intercept(CheckboxInterceptor.java:94)
    com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:248)
    org.apache.struts2.interceptor.FileUploadInterceptor.intercept(FileUploadInterceptor.java:314)
    com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:248)
    com.opensymphony.xwork2.interceptor.ModelDrivenInterceptor.intercept(ModelDrivenInterceptor.java:100)
    com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:248)
    com.opensymphony.xwork2.interceptor.ScopedModelDrivenInterceptor.intercept(ScopedModelDrivenInterceptor.java:141)
    com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:248)
    org.apache.struts2.interceptor.debugging.DebuggingInterceptor.intercept(DebuggingInterceptor.java:267)
    com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:248)
    com.opensymphony.xwork2.interceptor.ChainingInterceptor.intercept(ChainingInterceptor.java:142)
    com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:248)
    com.opensymphony.xwork2.interceptor.PrepareInterceptor.doIntercept(PrepareInterceptor.java:166)
    com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:98)
    com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:248)
    com.opensymphony.xwork2.interceptor.I18nInterceptor.intercept(I18nInterceptor.java:176)
    com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:248)
    org.apache.struts2.interceptor.ServletConfigInterceptor.intercept(ServletConfigInterceptor.java:164)
    com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:248)
    com.opensymphony.xwork2.interceptor.AliasInterceptor.intercept(AliasInterceptor.java:190)
    com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:248)
    com.opensymphony.xwork2.interceptor.ExceptionMappingInterceptor.intercept(ExceptionMappingInterceptor.java:187)
    com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:248)
    org.apache.struts2.impl.StrutsActionProxy.execute(StrutsActionProxy.java:52)
    org.apache.struts2.dispatcher.Dispatcher.serviceAction(Dispatcher.java:485)
    org.apache.struts2.dispatcher.ng.ExecuteOperations.executeAction(ExecuteOperations.java:77)
    org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter.doFilter(StrutsPrepareAndExecuteFilter.java:91)
    org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
    org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
    org.apache.struts2.dispatcher.ActionContextCleanUp.doFilter(ActionContextCleanUp.java:102)
    org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
    org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
    org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:199)
    org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96)
    org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:475)
    org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:140)
    org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:80)
    org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:624)
    org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:87)
    org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:342)
    org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:498)
    org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66)
    org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:796)
    org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1366)
    org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
    java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
    java.lang.Thread.run(Thread.java:748)

java.lang.OutOfMemoryError: Java heap space

You are seeing this page because development mode is enabled. Development mode, or devMode, enables extra debugging behaviors and reports to assist developers. To disable this mode, set:
  struts.devMode=false
in your WEB-INF/classes/struts.properties file.

I'm not familiar with Tomcat, Thank you ALL!


问:
How could I migrate a win32 application to a x64 one?
Recently I worked on a facial recognition application in Visual Stuido 2015. In order to apply cuda libraries to the app, this app needs to migrate from win32 type to x64. I carefully change the configuration manager and moderate everything involved with x86 when making sure every extern dll or lib has its x64 version.

But after compiled in release mode, there is always a error message: "LNK1112 module computer type 'x86' conflicts target computer type 'x64'". The error file is CameraDS.obj which is written by directshow. And I checked the producing .obj files with dumpbin /headers, then discovered the header file values of every .obj is machine (x86). Delete these .obj files or just clean solution doesn't work, and the IDE just throws the same error message. I don't konw why.

Is there any solution?

答:
Is it the source of the lib CameraDS.obj?
https://github.com/souseiki/Stereo-Vision

Just recompile it for x64 as well.

Also check that you haven't left x86 anywhere, look at the answers of fatal error LNK1112: module machine type 'x64' conflicts with target machine type 'X86'


问:
how to reverse records in pl/sql
how to reverse records in pl/sql</p>

答:
Use an ORDER BY clause with either ASCENDING or DESCENDING when selecting your records.

If this isn't what you want, you need to learn how to ask questions, as this is rather vague and open to interpretation.

Title: how to reverse records in pl/sql

Body: how to reverse records in pl/sql


问:
How to tell which query had an error?
I am trying to convert my mysqli database that was very vulnerable to PDO prepared statements. I think i almost got it since it actully inputs the registration data to the database but not to the other databases. So i think there must be some issues on those queries but i can't figure it out. Here below is my code.</p>

```<code><?php
session_start();
// DATABASE CONNECTION
$user = '****';
$pass = '****';

//CREATE CONNECTION
// $conn = new mysqli($dbserver, $dbusername, $dbpassword, $db);
$pdo = new PDO('mysql:host=localhost;dbname=****', $user, $pass);

// ASSIGN VARIABLE FROM FORM
$username = $_POST['username'];
$password = $_POST['password'];
$email    = $_POST['email'];

$password = password_hash($password, PASSWORD_BCRYPT);

// CHECK IF USER IS UNIQUE

    $stmt = $pdo->prepare("SELECT username FROM users WHERE username = :name");
    $stmt->bindParam(':name', $username);
    $stmt->execute();

    if ($stmt->rowCount() > 0) {
        echo "That username already exist!";
    } else {
        //INSERT DATA INTO DATABASE
        $sql = "INSERT INTO users ( username, password, email )
    VALUES ( :username, :password, :email )";
        $sql1 = "INSERT INTO stats (id, username)
VALUES ((SELECT id FROM users WHERE username=':username'), (SELECT username FROM users WHERE username=':username'))";
        $sql2 = "INSERT INTO progression (id, username)
VALUES ((SELECT id FROM users WHERE username=':username'), (SELECT username FROM users WHERE username=':username'))";
        $sql3 = "INSERT INTO powervalues (id, username)
VALUES ((SELECT id FROM users WHERE username=':username'), (SELECT username FROM users WHERE username=':username'))";

        // EXECUTE AND PREPARE
        $query = $pdo->prepare($sql);
        $query1 = $pdo->prepare($sql1);
        $query2 = $pdo->prepare($sql2);
        $query3 = $pdo->prepare($sql3);
        $result = $query->execute(array( ':username'=>$username, ':password'=>$password, ':email'=>$email ));
        $result1 = $query1->execute(array( ':username'=>$username ));
        $result2 = $query2->execute(array( ':username'=>$username ));
        $result3 = $query3->execute(array( ':username'=>$username ));
        //EXECUTE QUERY
        if ($result && $result1 && $result2 && $result3) {
            $_SESSION['Accountsucess'] = "Account has been added sucessfully.";
            header("location: ../../index.php?page=index");
        } else {
            echo "Error database failure";
        }
    }
</code>```

答:
Instead of continually selecting various parts of information, once you have inserted the user in the users table, fetch the last insert ID and then use that in subsequent calls...

```<code>  $sql = "INSERT INTO users ( username, password, email )
    VALUES ( :username, :password, :email )";
  $sql1 = "INSERT INTO stats (id, username)
    VALUES (:id,:username)";

    // EXECUTE AND PREPARE
    $query = $pdo->prepare($sql);
    $query1 = $pdo->prepare($sql1);

    $result = $query->execute(array( ':username'=>$username, ':password'=>$password, ':email'=>$email ));
    // Fetch id of new user
    $id = $pdo->lastInsertId();
    $result1 = $query1->execute(array( ':id' => $id, ':username'=>$username ));
</code>```

Repeat this same logic for each of the other statements.

Title: How to tell which query had an error?

Body:
I am trying to convert my mysqli database that was very vulnerable to PDO prepared statements. I think i almost got it since it actully inputs the registration data to the database but not to the other databases. So i think there must be some issues on those queries but i can't figure it out. Here below is my code.

<?php
session_start();
// DATABASE CONNECTION
$user = '****';
$pass = '****';

//CREATE CONNECTION
// $conn = new mysqli($dbserver, $dbusername, $dbpassword, $db);
$pdo = new PDO('mysql:host=localhost;dbname=****', $user, $pass);

// ASSIGN VARIABLE FROM FORM
$username = $_POST['username'];
$password = $_POST['password'];
$email    = $_POST['email'];

$password = password_hash($password, PASSWORD_BCRYPT);

// CHECK IF USER IS UNIQUE

    $stmt = $pdo->prepare("SELECT username FROM users WHERE username = :name");
    $stmt->bindParam(':name', $username);
    $stmt->execute();

    if ($stmt->rowCount() > 0) {
        echo "That username already exist!";
    } else {
        //INSERT DATA INTO DATABASE
        $sql = "INSERT INTO users ( username, password, email )
    VALUES ( :username, :password, :email )";
        $sql1 = "INSERT INTO stats (id, username)
VALUES ((SELECT id FROM users WHERE username=':username'), (SELECT username FROM users WHERE username=':username'))";
        $sql2 = "INSERT INTO progression (id, username)
VALUES ((SELECT id FROM users WHERE username=':username'), (SELECT username FROM users WHERE username=':username'))";
        $sql3 = "INSERT INTO powervalues (id, username)
VALUES ((SELECT id FROM users WHERE username=':username'), (SELECT username FROM users WHERE username=':username'))";

        // EXECUTE AND PREPARE
        $query = $pdo->prepare($sql);
        $query1 = $pdo->prepare($sql1);
        $query2 = $pdo->prepare($sql2);
        $query3 = $pdo->prepare($sql3);
        $result = $query->execute(array( ':username'=>$username, ':password'=>$password, ':email'=>$email ));
        $result1 = $query1->execute(array( ':username'=>$username ));
        $result2 = $query2->execute(array( ':username'=>$username ));
        $result3 = $query3->execute(array( ':username'=>$username ));
        //EXECUTE QUERY
        if ($result && $result1 && $result2 && $result3) {
            $_SESSION['Accountsucess'] = "Account has been added sucessfully.";
            header("location: ../../index.php?page=index");
        } else {
            echo "Error database failure";
        }
    }

Body:
Instead of continually selecting various parts of information, once you have inserted the user in the users table, fetch the last insert ID and then use that in subsequent calls...

  $sql = "INSERT INTO users ( username, password, email )
    VALUES ( :username, :password, :email )";
  $sql1 = "INSERT INTO stats (id, username)
    VALUES (:id,:username)";

    // EXECUTE AND PREPARE
    $query = $pdo->prepare($sql);
    $query1 = $pdo->prepare($sql1);

    $result = $query->execute(array( ':username'=>$username, ':password'=>$password, ':email'=>$email ));
    // Fetch id of new user
    $id = $pdo->lastInsertId();
    $result1 = $query1->execute(array( ':id' => $id, ':username'=>$username ));

Repeat this same logic for each of the other statements.


问:
VSTS v.Next Build Definitions Multiple Branches
I've recently transitioned from XAML builds to v.Next builds.  I've always kept one build definition per branch but I see the new system has the ability for a single build definition to trigger on multiple branches and pull requests.

Is this a good idea?  What are things to watch out for and the best ways to set this up?

The first couple concerns that come to mind are:

1) Version numbers.   How would I handle scenarios such as an old maintenance branch versioning as 1.0.,  master versioning as 2.0. and a dev build as say 0.2.*  so I don't confuse build artifacts?  Is there a better way?

2) What if the repos tree has changed?  What if master expects to build a .sln in one folder but a dev branch has since moved it to another folder?

Any other concerns and resolutions?

答:
Single build definition to trigger multiple branches and pull request can make VSTS build more flexible. You can choose the way as you need:

If you want to build a certain branch for a build definition, you can specify the certain branch name. Assume if you only want to build master branch, you can specify master branch in Get Source step (for manually build), or specify master branch in Branch filters (for CI build).

If you want to build multiple branches in a build definition (for CI build), you can specify the branches in branch filters on Triggers Tab.

If you want to verify a PR before merging, you can add build validation for branch policy.

For your concerns:

Even a build definition can trigger multiple branches, but for a certain build, it build a certain branch after changes are pushed on this branch. And you can detect which branch is actually build, and update branch version number correspondingly.

Such as you have a build definition which can trigger to build both for master branch and dev branch. After pushing changes to master branch, a build will be queued for master branch. And you can get the branch name by some ways, so you can increase the version number correspondingly.

You can not only specify which branches can be triggered in your build definition, but also specify the folders which can be triggered in path filters. Assume there are folderA and folderB both contain .sln, you want to trigger build only when the .sln file changes under folderA, so you can specify branch filters and path filters as below:

For the situation: multiple branches can be triggered by a build definition, you can add a PowerShell task to detect which branch is building. The script as below:

```<code>$head=$(git rev-parse HEAD)
$sha=$head.Substring(0,7)
$branches=$(git branch -rv)
for ($i=0;$i -lt $branches.Length; $i++)
{
  if ($branches[$i] -match $sha)
  {
    $tbranch=$branches[$i] -split "\s+"
    $local=$tbranch[1] -split '/'
    $br=$local[1]
    echo "You are building $br branch"
    break
  }
}
</code>```

Body:
Single build definition to trigger multiple branches and pull request can make VSTS build more flexible. You can choose the way as you need:

If you want to build a certain branch for a build definition, you can specify the certain branch name. Assume if you only want to build master branch, you can specify master branch in Get Source step (for manually build), or specify master branch in Branch filters (for CI build).

If you want to build multiple branches in a build definition (for CI build), you can specify the branches in branch filters on Triggers Tab.

If you want to verify a PR before merging, you can add build validation for branch policy.

For your concerns:

Even a build definition can trigger multiple branches, but for a certain build, it build a certain branch after changes are pushed on this branch. And you can detect which branch is actually build, and update branch version number correspondingly.

Such as you have a build definition which can trigger to build both for master branch and dev branch. After pushing changes to master branch, a build will be queued for master branch. And you can get the branch name by some ways, so you can increase the version number correspondingly.

You can not only specify which branches can be triggered in your build definition, but also specify the folders which can be triggered in path filters. Assume there are folderA and folderB both contain .sln, you want to trigger build only when the .sln file changes under folderA, so you can specify branch filters and path filters as below:

For the situation: multiple branches can be triggered by a build definition, you can add a PowerShell task to detect which branch is building. The script as below:

$head=$(git rev-parse HEAD)
$sha=$head.Substring(0,7)
$branches=$(git branch -rv)
for ($i=0;$i -lt $branches.Length; $i++)
{
  if ($branches[$i] -match $sha)
  {
    $tbranch=$branches[$i] -split "\s+"
    $local=$tbranch[1] -split '/'
    $br=$local[1]
    echo "You are building $br branch"
    break
  }
}


问:
SqlConnection error vs2015 with C#
I work with VS 2012 and SQL Server 2012. When I changed to VS 2015 & SQL Server 2014, my SqlConnection didn't work and causing errors that the servers could not be found.

My code:

```<code>SqlConnection cn = new SqlConnection(@"Data Source=(local); Initial Catalog=jood; Integrated Security=true;MultipleActiveResultSets=true");

public Form1()
{
    cn.Open();
    cn.Close();
    InitializeComponent();
}
</code>```

Error

An unhandled exception of type 'System.Data.SqlClient.SqlException' occurred in System.Data.dll

  Additional information: A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: Named Pipes Provider, error: 40 - Could not open a connection to SQL Server)

答:
If you plan on declaring your SqlConnection property outside of a method, you need to set an access qualifier (public, private, whatever). Try using localdb instead of local as well. Do your initialization before you do your connections.

If this still isn't working, check your Sql configuration settings and make sure you have access to the database with your windows credentials instead of just an sql login like sa/sa

```<code>public SqlConnection cn = new SqlConnection(@"data source=(localdb);initial catalog=jood;Integrated Security=true;MultipleActiveResultSets=true");

public Form1()
{
    InitializeComponent();

    cn.Open();
    cn.Close();
}
</code>```

Tried this just now with VS2015 and SQL Server 2014 - Worked fine.

EDIT: If you can, try explicitly telling it your server name rather than using localdb.

Title: SqlConnection error vs2015 with C#

Body:
I work with VS 2012 and SQL Server 2012. When I changed to VS 2015 & SQL Server 2014, my SqlConnection didn't work and causing errors that the servers could not be found.

My code:

SqlConnection cn = new SqlConnection(@"Data Source=(local); Initial Catalog=jood; Integrated Security=true;MultipleActiveResultSets=true");

public Form1()
{
    cn.Open();
    cn.Close();
    InitializeComponent();
}

Error

An unhandled exception of type 'System.Data.SqlClient.SqlException' occurred in System.Data.dll

  Additional information: A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: Named Pipes Provider, error: 40 - Could not open a connection to SQL Server)

Body:
If you plan on declaring your SqlConnection property outside of a method, you need to set an access qualifier (public, private, whatever). Try using localdb instead of local as well. Do your initialization before you do your connections.

If this still isn't working, check your Sql configuration settings and make sure you have access to the database with your windows credentials instead of just an sql login like sa/sa

public SqlConnection cn = new SqlConnection(@"data source=(localdb);initial catalog=jood;Integrated Security=true;MultipleActiveResultSets=true");

public Form1()
{
    InitializeComponent();

    cn.Open();
    cn.Close();
}

Tried this just now with VS2015 and SQL Server 2014 - Worked fine.

EDIT: If you can, try explicitly telling it your server name rather than using localdb.


问:
Can't run NMAKE in the command prompt after upgrade to Visual Studio 2017
I have some power shell scripts file it uses both MSBUILD.exe and NMAKE, I invoke it by command prompt not developer command prompt of VS 2017, but it is not recognized after executed VsMSBuildCmd.bat file.

But it works fine on the Visual Studio 2015.

Besides, it is working through developer command prompt of VS 2017.

Any suggestions?

答:
Can't run NMAKE in the command prompt after upgrade to Visual Studio 2017

I got the same result "'nmake' is not recognized as an internal or external command" after executed the VsMSBuildCmd.bat file from VS2017 installation directory: C:\Program Files (x86)\Microsoft Visual Studio\2017\Enterprise\Common7\Tools:

After test, I found the solution for this issue, after executed the VsMSBuildCmd.bat, still need to executed the vcvars.bat. The path of vcvars.bat is:

```<code>C:\Program Files (x86)\Microsoft Visual Studio\2017\Enterprise\Common7\Tools\vsdevcmd\ext
</code>```

In this case, NMAKE command would be recognized in command prompt:

Body:
Can't run NMAKE in the command prompt after upgrade to Visual Studio 2017

I got the same result "'nmake' is not recognized as an internal or external command" after executed the VsMSBuildCmd.bat file from VS2017 installation directory: C:\Program Files (x86)\Microsoft Visual Studio\2017\Enterprise\Common7\Tools:

After test, I found the solution for this issue, after executed the VsMSBuildCmd.bat, still need to executed the vcvars.bat. The path of vcvars.bat is:

C:\Program Files (x86)\Microsoft Visual Studio\2017\Enterprise\Common7\Tools\vsdevcmd\ext

In this case, NMAKE command would be recognized in command prompt:


问:
How to connect akka(java) with RDBMS
I am new to Akka and want to create a CRUD application by using any RDBMS. I have gone through the akka-persistence which is quite confusing for me. But it lacks any implementation code.
Can anybody point me to the relative links/ git hub repository which will help in understanding.

Till now I have created a simple hello world application.

答:
I suggest to use Slick. There are several supported RDBMS connectors such as Postgres, Sql Server (Mssql), Mysql, Oracle, DB2. Previously I had to connect to an Oracle 12 database.

I added the dependency (in my case it was gradle) which can be found in docs.

```<code>"com.lightbend.akka:akka-stream-alpakka-slick_2.11:<version>",
</code>```

After that I configured the slick as you can see below.

```<code>slick-oracle {
   profile = "slick.jdbc.OracleProfile$"
   db {
     dataSourceClass = "slick.jdbc.DriverDataSource"
     connectionPool = disabled
     properties {
       driver = "oracle.jdbc.OracleDriver"
       url = "jdbc:oracle:thin:@//localhost:1521/xe"
       user = user
       password = password
     }
   }
}
</code>```

Title: How to connect akka(java) with RDBMS

Body:
I suggest to use Slick. There are several supported RDBMS connectors such as Postgres, Sql Server (Mssql), Mysql, Oracle, DB2. Previously I had to connect to an Oracle 12 database.

I added the dependency (in my case it was gradle) which can be found in docs.

"com.lightbend.akka:akka-stream-alpakka-slick_2.11:<version>",

After that I configured the slick as you can see below.

slick-oracle {
   profile = "slick.jdbc.OracleProfile$"
   db {
     dataSourceClass = "slick.jdbc.DriverDataSource"
     connectionPool = disabled
     properties {
       driver = "oracle.jdbc.OracleDriver"
       url = "jdbc:oracle:thin:@//localhost:1521/xe"
       user = user
       password = password
     }
   }
}