问:
Windows IoT BackgroundTask Async/Await
I am having a play with a Raspberry Pi 3 running Windows IoT. I have wired up a DS18B20 sensor and I am able to communicate to it fine via a UWP app.

I now wanted to make this app into a BackgroundTask app.
I am using this code for the OneWire coms

```<code>class WireSearchResult
{
    public byte[] id = new byte[8];
    public int lastForkPoint = 0;
}
public class OneWire
{
    private SerialDevice serialPort = null;
    DataWriter dataWriteObject = null;
    DataReader dataReaderObject = null;

    public async Task<string> GetFirstSerialPort()
    {
        try
        {
            string aqs = SerialDevice.GetDeviceSelector("UART0");
            var dis = await DeviceInformation.FindAllAsync(aqs);
            if (dis.Count > 0)
            {
                var deviceInfo = dis.First();
                return deviceInfo.Id;
            }
        }
        catch (Exception ex)
        {
            Debug.WriteLine("Unable to get serial device: " + ex.Message);
        }

        return null;
    }

    public void shutdown()
    {
        if (serialPort != null)
        {
            serialPort.Dispose();
            serialPort = null;
        }
    }

    async Task<bool> onewireReset(string deviceId)
    {
        try
        {
            if (serialPort != null)
                serialPort.Dispose();

            serialPort = await SerialDevice.FromIdAsync(deviceId);

            // Configure serial settings
            serialPort.WriteTimeout = TimeSpan.FromMilliseconds(1000);
            serialPort.ReadTimeout = TimeSpan.FromMilliseconds(1000);
            serialPort.BaudRate = 9600;
            serialPort.Parity = SerialParity.None;
            serialPort.StopBits = SerialStopBitCount.One;
            serialPort.DataBits = 8;
            serialPort.Handshake = SerialHandshake.None;

            dataWriteObject = new DataWriter(serialPort.OutputStream);
            dataWriteObject.WriteByte(0xF0);
            await dataWriteObject.StoreAsync();

            dataReaderObject = new DataReader(serialPort.InputStream);
            await dataReaderObject.LoadAsync(1);
            byte resp = dataReaderObject.ReadByte();
            if (resp == 0xFF)
            {
                System.Diagnostics.Debug.WriteLine("Nothing connected to UART");
                return false;
            }
            else if (resp == 0xF0)
            {
                System.Diagnostics.Debug.WriteLine("No 1-wire devices are present");
                return false;
            }
            else
            {
                //System.Diagnostics.Debug.WriteLine("Response: " + resp);
                serialPort.Dispose();
                serialPort = await SerialDevice.FromIdAsync(deviceId);

                // Configure serial settings
                serialPort.WriteTimeout = TimeSpan.FromMilliseconds(1000);
                serialPort.ReadTimeout = TimeSpan.FromMilliseconds(1000);
                serialPort.BaudRate = 115200;
                serialPort.Parity = SerialParity.None;
                serialPort.StopBits = SerialStopBitCount.One;
                serialPort.DataBits = 8;
                serialPort.Handshake = SerialHandshake.None;
                dataWriteObject = new DataWriter(serialPort.OutputStream);
                dataReaderObject = new DataReader(serialPort.InputStream);
                return true;
            }
        }
        catch (Exception ex)
        {
            System.Diagnostics.Debug.WriteLine("Exception: " + ex.Message);
            return false;
        }
    }

    public async Task onewireWriteByte(byte b)
    {
        for (byte i = 0; i < 8; i++, b = (byte)(b >> 1))
        {
            // Run through the bits in the byte, extracting the
            // LSB (bit 0) and sending it to the bus
            await onewireBit((byte)(b & 0x01));
        }
    }

    async Task<byte> onewireBit(byte b)
    {
        var bit = b > 0 ? 0xFF : 0x00;
        dataWriteObject.WriteByte((byte)bit);
        await dataWriteObject.StoreAsync();
        await dataReaderObject.LoadAsync(1);
        var data = dataReaderObject.ReadByte();
        return (byte)(data & 0xFF);
    }

    async Task<byte> onewireReadByte()
    {
        byte b = 0;
        for (byte i = 0; i < 8; i++)
        {
            // Build up byte bit by bit, LSB first
            b = (byte)((b >> 1) + 0x80 * await onewireBit(1));
        }
       // System.Diagnostics.Debug.WriteLine("onewireReadByte result: " + b);
        return b;
    }

    public async Task<double> getTemperature(string deviceId)
    {
        double tempCelsius = -200;

        if (await onewireReset(deviceId))
        {
            await onewireWriteByte(0xCC); //1-Wire SKIP ROM command (ignore device id)
            await onewireWriteByte(0x44); //DS18B20 convert T command
                                          // (initiate single temperature conversion)
                                          // thermal data is stored in 2-byte temperature
                                          // register in scratchpad memory

            // Wait for at least 750ms for data to be collated
            await Task.Delay(750);

            // Get the data
            await onewireReset(deviceId);
            await onewireWriteByte(0xCC); //1-Wire Skip ROM command (ignore device id)
            await onewireWriteByte(0xBE); //DS18B20 read scratchpad command
                                          // DS18B20 will transmit 9 bytes to master (us)
                                          // starting with the LSB

            byte tempLSB = await onewireReadByte(); //read lsb
            byte tempMSB = await onewireReadByte(); //read msb

            // Reset bus to stop sensor sending unwanted data
            await onewireReset(deviceId);

            // Log the Celsius temperature
            tempCelsius = ((tempMSB * 256) + tempLSB) / 16.0;
            var temp2 = ((tempMSB << 8) + tempLSB) * 0.0625; //just another way of calculating it

            System.Diagnostics.Debug.WriteLine("Temperature: " + tempCelsius + " degrees C " + temp2);
        }
        return tempCelsius;
    }
}
</code>```

And finally the StartupTask

```<code>public sealed class StartupTask : IBackgroundTask
{
    private BackgroundTaskDeferral deferral;

    private OneWire onewire;
    private string deviceId = string.Empty;
    private bool inprog = false;
    private Timer timer;

    public void Run(IBackgroundTaskInstance taskInstance)
    {
        deferral = taskInstance.GetDeferral();

        onewire = new OneWire();
        deviceId = await onewire.GetFirstSerialPort();

        if(deviceId != null)
          await onewire.getTemperature(deviceId));

        BackgroundTaskDeferral.Complete();
    }

}
</code>```

The problem I have is that when I run this code it hangs on one of the lines that disposes of the SerialDevice in OneWire class.

I have read in a few places that its related to the BackgroundTask and using Async/Await

答:
This issue is not related to the BackgroundTask. Because your code produces the same issue in non BackgroundTask(app).

Its reason looks like SerialPort is somewhat prone to deadlock.

I found there are too many callings of onewireReset method that close and reopen the SerialPort. I don´t know why should this be done but this cause the problem.

So there is a workaround: Rewrite the related part logic and make sure open the SerialPort at the start of your program and dispose it when you don't need it any more.

Title: Windows IoT BackgroundTask Async/Await

Body:
I am having a play with a Raspberry Pi 3 running Windows IoT. I have wired up a DS18B20 sensor and I am able to communicate to it fine via a UWP app.

I now wanted to make this app into a BackgroundTask app.
I am using this code for the OneWire coms

class WireSearchResult
{
    public byte[] id = new byte[8];
    public int lastForkPoint = 0;
}
public class OneWire
{
    private SerialDevice serialPort = null;
    DataWriter dataWriteObject = null;
    DataReader dataReaderObject = null;

    public async Task<string> GetFirstSerialPort()
    {
        try
        {
            string aqs = SerialDevice.GetDeviceSelector("UART0");
            var dis = await DeviceInformation.FindAllAsync(aqs);
            if (dis.Count > 0)
            {
                var deviceInfo = dis.First();
                return deviceInfo.Id;
            }
        }
        catch (Exception ex)
        {
            Debug.WriteLine("Unable to get serial device: " + ex.Message);
        }

        return null;
    }

    public void shutdown()
    {
        if (serialPort != null)
        {
            serialPort.Dispose();
            serialPort = null;
        }
    }

    async Task<bool> onewireReset(string deviceId)
    {
        try
        {
            if (serialPort != null)
                serialPort.Dispose();

            serialPort = await SerialDevice.FromIdAsync(deviceId);

            // Configure serial settings
            serialPort.WriteTimeout = TimeSpan.FromMilliseconds(1000);
            serialPort.ReadTimeout = TimeSpan.FromMilliseconds(1000);
            serialPort.BaudRate = 9600;
            serialPort.Parity = SerialParity.None;
            serialPort.StopBits = SerialStopBitCount.One;
            serialPort.DataBits = 8;
            serialPort.Handshake = SerialHandshake.None;

            dataWriteObject = new DataWriter(serialPort.OutputStream);
            dataWriteObject.WriteByte(0xF0);
            await dataWriteObject.StoreAsync();

            dataReaderObject = new DataReader(serialPort.InputStream);
            await dataReaderObject.LoadAsync(1);
            byte resp = dataReaderObject.ReadByte();
            if (resp == 0xFF)
            {
                System.Diagnostics.Debug.WriteLine("Nothing connected to UART");
                return false;
            }
            else if (resp == 0xF0)
            {
                System.Diagnostics.Debug.WriteLine("No 1-wire devices are present");
                return false;
            }
            else
            {
                //System.Diagnostics.Debug.WriteLine("Response: " + resp);
                serialPort.Dispose();
                serialPort = await SerialDevice.FromIdAsync(deviceId);

                // Configure serial settings
                serialPort.WriteTimeout = TimeSpan.FromMilliseconds(1000);
                serialPort.ReadTimeout = TimeSpan.FromMilliseconds(1000);
                serialPort.BaudRate = 115200;
                serialPort.Parity = SerialParity.None;
                serialPort.StopBits = SerialStopBitCount.One;
                serialPort.DataBits = 8;
                serialPort.Handshake = SerialHandshake.None;
                dataWriteObject = new DataWriter(serialPort.OutputStream);
                dataReaderObject = new DataReader(serialPort.InputStream);
                return true;
            }
        }
        catch (Exception ex)
        {
            System.Diagnostics.Debug.WriteLine("Exception: " + ex.Message);
            return false;
        }
    }

    public async Task onewireWriteByte(byte b)
    {
        for (byte i = 0; i < 8; i++, b = (byte)(b >> 1))
        {
            // Run through the bits in the byte, extracting the
            // LSB (bit 0) and sending it to the bus
            await onewireBit((byte)(b & 0x01));
        }
    }

    async Task<byte> onewireBit(byte b)
    {
        var bit = b > 0 ? 0xFF : 0x00;
        dataWriteObject.WriteByte((byte)bit);
        await dataWriteObject.StoreAsync();
        await dataReaderObject.LoadAsync(1);
        var data = dataReaderObject.ReadByte();
        return (byte)(data & 0xFF);
    }

    async Task<byte> onewireReadByte()
    {
        byte b = 0;
        for (byte i = 0; i < 8; i++)
        {
            // Build up byte bit by bit, LSB first
            b = (byte)((b >> 1) + 0x80 * await onewireBit(1));
        }
       // System.Diagnostics.Debug.WriteLine("onewireReadByte result: " + b);
        return b;
    }

    public async Task<double> getTemperature(string deviceId)
    {
        double tempCelsius = -200;

        if (await onewireReset(deviceId))
        {
            await onewireWriteByte(0xCC); //1-Wire SKIP ROM command (ignore device id)
            await onewireWriteByte(0x44); //DS18B20 convert T command
                                          // (initiate single temperature conversion)
                                          // thermal data is stored in 2-byte temperature
                                          // register in scratchpad memory

            // Wait for at least 750ms for data to be collated
            await Task.Delay(750);

            // Get the data
            await onewireReset(deviceId);
            await onewireWriteByte(0xCC); //1-Wire Skip ROM command (ignore device id)
            await onewireWriteByte(0xBE); //DS18B20 read scratchpad command
                                          // DS18B20 will transmit 9 bytes to master (us)
                                          // starting with the LSB

            byte tempLSB = await onewireReadByte(); //read lsb
            byte tempMSB = await onewireReadByte(); //read msb

            // Reset bus to stop sensor sending unwanted data
            await onewireReset(deviceId);

            // Log the Celsius temperature
            tempCelsius = ((tempMSB * 256) + tempLSB) / 16.0;
            var temp2 = ((tempMSB << 8) + tempLSB) * 0.0625; //just another way of calculating it

            System.Diagnostics.Debug.WriteLine("Temperature: " + tempCelsius + " degrees C " + temp2);
        }
        return tempCelsius;
    }
}

And finally the StartupTask

public sealed class StartupTask : IBackgroundTask
{
    private BackgroundTaskDeferral deferral;

    private OneWire onewire;
    private string deviceId = string.Empty;
    private bool inprog = false;
    private Timer timer;

    public void Run(IBackgroundTaskInstance taskInstance)
    {
        deferral = taskInstance.GetDeferral();

        onewire = new OneWire();
        deviceId = await onewire.GetFirstSerialPort();

        if(deviceId != null)
          await onewire.getTemperature(deviceId));

        BackgroundTaskDeferral.Complete();
    }

}

The problem I have is that when I run this code it hangs on one of the lines that disposes of the SerialDevice in OneWire class.

I have read in a few places that its related to the BackgroundTask and using Async/Await


来源: stackexchange

问:
JS Script link accepting PHP variables and showing %27
I have a
```

答:
As Satpal says, encoded value of ' is %27

remove the single quote like:

```<code>type=calculator&min=50&max=400&amount=".<?php echo $price;?>
</code>```

as it is also useless in your query string so you can remove it, and try again.

Edited: Instead of:

```<code>type=calculator&min=50&max=400&amount=".<?php echo $price;?>"
</code>```

try

```<code>type=calculator&min=50&max=400&amount=<?php echo $price; ?>"
</code>```

ContentLicense: CC BY-SA 3.0

Body: I have a

Body:
As Satpal says, encoded value of ' is %27

remove the single quote like:

type=calculator&min=50&max=400&amount=".<?php echo $price;?>

as it is also useless in your query string so you can remove it, and try again.

Edited: Instead of:

type=calculator&min=50&max=400&amount=".<?php echo $price;?>"

try

type=calculator&min=50&max=400&amount=<?php echo $price; ?>"


问:
Update two ID's at once SQL - PHP
I have a table that's PK is an int field.
My problem is I need to swap two of the values round.

This is my current code:

```<code>$newId = (int)$id; $newId = $newId - 1;

$result = mysql_query("UPDATE homeScroller SET id = '$newId' WHERE id = '$id'") or die('error '.mysql_error());
$result2 = mysql_query("UPDATE homeScroller SET id = '$id ' WHERE id = '$newId'") or die('error '.mysql_error());
</code>```

The table contains at max 3 rows that contain info for an slideshow on the frontpage of the website. The frontpage orders them by their IDs. So to change the order I need to edit the ID's.

答:
Assign one with a temporary id (0, because auto_increment usually starts at 1, so 0 should be unused):

```<code>$result = mysql_query("UPDATE homeScroller SET id = 0 WHERE id = '$id'");
$result = mysql_query("UPDATE homeScroller SET id = '$id ' WHERE id = '$newId'");
$result = mysql_query("UPDATE homeScroller SET id = '$newId ' WHERE id = 0");
</code>```

IMPORTANT: However, you shouldn't rely on the primary key for ordering results, if you want to be able to change the order easily. Add a sequence column and sort by that instead.

ContentLicense: CC BY-SA 2.5

Title: Update two ID's at once SQL - PHP

Body:
I have a table that's PK is an int field.
My problem is I need to swap two of the values round.

This is my current code:

$newId = (int)$id; $newId = $newId - 1;

$result = mysql_query("UPDATE homeScroller SET id = '$newId' WHERE id = '$id'") or die('error '.mysql_error());
$result2 = mysql_query("UPDATE homeScroller SET id = '$id ' WHERE id = '$newId'") or die('error '.mysql_error());

The table contains at max 3 rows that contain info for an slideshow on the frontpage of the website. The frontpage orders them by their IDs. So to change the order I need to edit the ID's.

Body:
Assign one with a temporary id (0, because auto_increment usually starts at 1, so 0 should be unused):

$result = mysql_query("UPDATE homeScroller SET id = 0 WHERE id = '$id'");
$result = mysql_query("UPDATE homeScroller SET id = '$id ' WHERE id = '$newId'");
$result = mysql_query("UPDATE homeScroller SET id = '$newId ' WHERE id = 0");

IMPORTANT: However, you shouldn't rely on the primary key for ordering results, if you want to be able to change the order easily. Add a sequence column and sort by that instead.


问:
scikit-lean GridSearchCV n_jobs != 1 freezing
I'm running grid search on random forests and trying to use n_jobs different than one but the kernel freezes, there is no CPU usage. With n_jobs=1 it works fine. I can't even stop the command with ctl-C and have to restart the kernel.
I'm running on windows 7. I saw that there is a similar problem with OS X but the solution is not relevant for windows 7.

```<code>from sklearn.ensemble import RandomForestClassifier
rf_tfdidf = Pipeline([('vect',tfidf),
                  ('clf', RandomForestClassifier(n_estimators=50,
class_weight='balanced_subsample'))])

param_grid = [{'vect__ngram_range':[(1,1)],
          'vect__stop_words': [stop],
          'vect__tokenizer':[tokenizer]
          }]
if __name__ == '__main__':
gs_rf_tfidf = GridSearchCV(rf_tfdidf, param_grid, scoring='accuracy', cv=5,
                                                           verbose=10,
                                                           n_jobs=2)
gs_rf_tfidf.fit(X_train_part, y_train_part)
</code>```

thanks.

答:
The indent after if __name__ == '__main__': is not correct. If it's not the case and it's a copy paste mistake then you can try something like :

```<code>if __name__ =='main':
    # your code indented !
</code>```

So the first line of your script is if __name__ == '__main__': and then the rest code follows with the appropriate indent.

New Code

```<code>from sklearn.ensemble import RandomForestClassifier
from sklearn.pipeline import Pipeline

if __name__ == '__main__':

    rf_tfdidf = Pipeline([('vect',tfidf),('clf', RandomForestClassifier(n_estimators=50,class_weight='balanced_subsample'))])

    param_grid = [{'vect__ngram_range':[(1,1)],'vect__stop_words': [stop],'vect__tokenizer':[tokenizer]}]

    gs_rf_tfidf = GridSearchCV(rf_tfdidf, param_grid, scoring='accuracy', cv=5,verbose=10, n_jobs=-1)

    gs_rf_tfidf.fit(X_train_part, y_train_part)
</code>```

This works fine for me (windows 8.1)

EDIT

The following works fine using PyCharm. I have not used spyder but it should also work for spyder:

Code

```<code>Class Test(object):
    def __init__(self):
        ###code here
        ###code here

if __name__ == '__main__':
    Test()
</code>```

Body:
I'm running grid search on random forests and trying to use n_jobs different than one but the kernel freezes, there is no CPU usage. With n_jobs=1 it works fine. I can't even stop the command with ctl-C and have to restart the kernel.
I'm running on windows 7. I saw that there is a similar problem with OS X but the solution is not relevant for windows 7.

from sklearn.ensemble import RandomForestClassifier
rf_tfdidf = Pipeline([('vect',tfidf),
                  ('clf', RandomForestClassifier(n_estimators=50,
class_weight='balanced_subsample'))])

param_grid = [{'vect__ngram_range':[(1,1)],
          'vect__stop_words': [stop],
          'vect__tokenizer':[tokenizer]
          }]
if __name__ == '__main__':
gs_rf_tfidf = GridSearchCV(rf_tfdidf, param_grid, scoring='accuracy', cv=5,
                                                           verbose=10,
                                                           n_jobs=2)
gs_rf_tfidf.fit(X_train_part, y_train_part)

thanks.

Body:
The indent after if __name__ == '__main__': is not correct. If it's not the case and it's a copy paste mistake then you can try something like :

if __name__ =='main':
    # your code indented !

So the first line of your script is if __name__ == '__main__': and then the rest code follows with the appropriate indent.

New Code

from sklearn.ensemble import RandomForestClassifier
from sklearn.pipeline import Pipeline

if __name__ == '__main__':

    rf_tfdidf = Pipeline([('vect',tfidf),('clf', RandomForestClassifier(n_estimators=50,class_weight='balanced_subsample'))])

    param_grid = [{'vect__ngram_range':[(1,1)],'vect__stop_words': [stop],'vect__tokenizer':[tokenizer]}]

    gs_rf_tfidf = GridSearchCV(rf_tfdidf, param_grid, scoring='accuracy', cv=5,verbose=10, n_jobs=-1)

    gs_rf_tfidf.fit(X_train_part, y_train_part)

This works fine for me (windows 8.1)

EDIT

The following works fine using PyCharm. I have not used spyder but it should also work for spyder:

Code

Class Test(object):
    def __init__(self):
        ###code here
        ###code here

if __name__ == '__main__':
    Test()


问:
Angular 4 Can't bind to 'dragula' since it isn't a known property of 'div'
I'm struggling with binding ng2-dragula to AspNetCore SPA template. Tried everything, but still getting:

```<code>Exception: Call to Node module failed with error: Error: Template parse errors:
Can't bind to 'dragula' since it isn't a known property of 'div'. ("
<div>
<div class='wrapper'>
<div class='container' [ERROR ->][dragula]='"first-bag"'>
<div>Drag/drop item 1</div>
</div>
"): ng:///AppModule/DragulaComponent.html@7:31
at syntaxError (C:\Users\...\ClientApp\dist\vendor.js:36125:34)
at ...
</code>```

Has anyone used ng2-dragula in AspDotnetCoreSpa?

dragula.component.html

```<code><div>
 <div class='wrapper'>
  <div class='container' [dragula]='"first-bag"'>
   <div>Drag/drop item 1</div>
  </div>
 </div>
</div>
</code>```

dragula.component.ts

```<code>import { Component } from '@angular/core';
import { DragulaModule, DragulaService } from 'ng2-dragula'

@Component({
   selector: 'dragula',
   templateUrl: './dragula.component.html',
   styleUrls: ['../../../../node_modules/dragula/dist/dragula.min.css']
 })
 export class DragulaComponent {
}
</code>```

app.module.client.ts

```<code>import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { FormsModule } from '@angular/forms';
import { DragulaModule } from 'ng2-dragula';
import { HttpModule } from '@angular/http';
import { sharedConfig } from './app.module.shared';

@NgModule({
    bootstrap: sharedConfig.bootstrap,
    declarations: sharedConfig.declarations,
    imports: [
        BrowserModule,
        FormsModule,
        DragulaModule,
        HttpModule,
        ...sharedConfig.imports
    ],
    providers: [
        { provide: 'ORIGIN_URL', useValue: location.origin }
    ]
})
export class AppModule {
}
</code>```

app.module.shared.ts

```<code>import { NgModule } from '@angular/core';
import { RouterModule } from '@angular/router';

import { AppComponent } from './components/app/app.component'
import { NavMenuComponent } from './components/navmenu/navmenu.component';
import { HomeComponent } from './components/home/home.component';
import { FetchDataComponent } from './components/fetchdata/fetchdata.component';
import { CounterComponent } from './components/counter/counter.component';
import { DragulaComponent } from './components/dragula/dragula.component';

export const sharedConfig: NgModule = {
    bootstrap: [ AppComponent ],
    declarations: [
        AppComponent,
        NavMenuComponent,
        CounterComponent,
        FetchDataComponent,
        DragulaComponent,
        HomeComponent
    ],
    imports: [
        RouterModule.forRoot([
            { path: '', redirectTo: 'home', pathMatch: 'full' },
            { path: 'home', component: HomeComponent },
            { path: 'counter', component: CounterComponent },
            { path: 'fetch-data', component: FetchDataComponent },
            { path: 'dragula', component: DragulaComponent },
            { path: '**', redirectTo: 'home' }
        ])
    ]
};
</code>```

答:
I hope you are using a module base structure(as below):

Click : Project Structure

In this application there are modules like dashboard, dragula..etc.

In this case if you want to add dragula drag and drop (ng2-dragula), what you have to do is,  add DragulaModule in the app.module.ts using
import { DragulaModule } from '../../node_modules/ng2-dragula/ng2-dragula';

once you add like this and if you try to use [dragula]='"bag-something"' in the dragula.component.html, which is the html file, still it will give the error Can't bind to 'dragula' since it isn't a known property of 'div'.

So the solution is add DragulaModule in the module's xxx.module.tsfile.In this given case you will have to add in the dragula module's dragula.module.tsfile.

Note: when import DragulaModule the path to the ng2-dragula/ng2-dragula may differ depending on your project structure.

Body:
I'm struggling with binding ng2-dragula to AspNetCore SPA template. Tried everything, but still getting:

Exception: Call to Node module failed with error: Error: Template parse errors:
Can't bind to 'dragula' since it isn't a known property of 'div'. ("

][dragula]='"first-bag"'>

Drag/drop item 1

"): ng:///AppModule/DragulaComponent.html@7:31
at syntaxError (C:\Users\...\ClientApp\dist\vendor.js:36125:34)
at ...

Has anyone used ng2-dragula in AspDotnetCoreSpa?

dragula.component.html

Drag/drop item 1

dragula.component.ts

import { Component } from '@angular/core';
import { DragulaModule, DragulaService } from 'ng2-dragula'

@Component({
   selector: 'dragula',
   templateUrl: './dragula.component.html',
   styleUrls: ['../../../../node_modules/dragula/dist/dragula.min.css']
 })
 export class DragulaComponent {
}

app.module.client.ts

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { FormsModule } from '@angular/forms';
import { DragulaModule } from 'ng2-dragula';
import { HttpModule } from '@angular/http';
import { sharedConfig } from './app.module.shared';

@NgModule({
    bootstrap: sharedConfig.bootstrap,
    declarations: sharedConfig.declarations,
    imports: [
        BrowserModule,
        FormsModule,
        DragulaModule,
        HttpModule,
        ...sharedConfig.imports
    ],
    providers: [
        { provide: 'ORIGIN_URL', useValue: location.origin }
    ]
})
export class AppModule {
}

app.module.shared.ts

import { NgModule } from '@angular/core';
import { RouterModule } from '@angular/router';

import { AppComponent } from './components/app/app.component'
import { NavMenuComponent } from './components/navmenu/navmenu.component';
import { HomeComponent } from './components/home/home.component';
import { FetchDataComponent } from './components/fetchdata/fetchdata.component';
import { CounterComponent } from './components/counter/counter.component';
import { DragulaComponent } from './components/dragula/dragula.component';

export const sharedConfig: NgModule = {
    bootstrap: [ AppComponent ],
    declarations: [
        AppComponent,
        NavMenuComponent,
        CounterComponent,
        FetchDataComponent,
        DragulaComponent,
        HomeComponent
    ],
    imports: [
        RouterModule.forRoot([
            { path: '', redirectTo: 'home', pathMatch: 'full' },
            { path: 'home', component: HomeComponent },
            { path: 'counter', component: CounterComponent },
            { path: 'fetch-data', component: FetchDataComponent },
            { path: 'dragula', component: DragulaComponent },
            { path: '**', redirectTo: 'home' }
        ])
    ]
};

ContentLicense: CC BY-SA 4.0


问:
how to compile mariadb to get libmysqlclient.so? (missing libmysqlclient.so in /usr/local/mysql/lib)
I wanted to move our database from mysql (community version) to mariadb with the further use of php7.1/apache2.4.25... So I have to compile mariadb in our new production environment. I compiled it with these options:

```<code>cmake -DCMAKE_CXX_FLAGS:STRING="-std=c++11" -DCONC_WITH_CURL=ON -DCONC_WITH_EXTERNAL_ZLIB=ON -DDISABLE_SHARED=OFF -DCONC_WITH_MYSQLCOMPAT:BOOL=ON -DPLUGIN_CLIENT_ED25519:STRING=DYNAMIC .
make all && make install
</code>```

The mysql community version has a libmysqlclient.so in /usr/local/mysql/lib located. If I compile it with the options given above I only found these files in /usr/local/mysql/lib (MariaDB 10.2.6):

```<code># ls -l /usr/local/mysql/lib/
total 3572
-rw-r--r-- 1 root root 2305518 Jul  4 08:14 libmariadbclient.a
lrwxrwxrwx 1 root root      15 Jul  4 08:31 libmariadb.so -> libmariadb.so.3
-rwxr-xr-x 1 root root 1297664 Jul  4 08:14 libmariadb.so.3
-rw-r--r-- 1 root root   48406 Jul  4 08:14 libmysqlservices.a
drwxr-xr-x 2 root root    4096 Jul  4 08:31 plugin
</code>```

How can I get libmysqlclient.so? There isn't also any libmariadbclient.so just libmariadbclient.a ...

Thank you for further hints!

答:
OK, now I found a solution.
I've just did a symbolic link to libmariadb.so and it now looks like the following:

```<code>ls -l /usr/local/mysql/lib/
total 3572
-rw-r--r-- 1 root root 2305518 Jul  4 16:21 libmariadbclient.a
lrwxrwxrwx 1 root root      15 Jul  4 16:39 libmariadb.so -> libmariadb.so.3
-rwxr-xr-x 1 root root 1297664 Jul  4 16:21 libmariadb.so.3
lrwxrwxrwx 1 root root      15 Jul  4 16:40 libmysqlclient_r.so -> libmariadb.so.3
lrwxrwxrwx 1 root root      15 Jul  4 16:40 libmysqlclient.so -> libmariadb.so.3
-rw-r--r-- 1 root root   48406 Jul  4 16:21 libmysqlservices.a
drwxr-xr-x 2 root root    4096 Jul  4 16:39 plugin
</code>```

In this case PHP 7 would finally find the mysql libraries...

Body:
I wanted to move our database from mysql (community version) to mariadb with the further use of php7.1/apache2.4.25... So I have to compile mariadb in our new production environment. I compiled it with these options:

cmake -DCMAKE_CXX_FLAGS:STRING="-std=c++11" -DCONC_WITH_CURL=ON -DCONC_WITH_EXTERNAL_ZLIB=ON -DDISABLE_SHARED=OFF -DCONC_WITH_MYSQLCOMPAT:BOOL=ON -DPLUGIN_CLIENT_ED25519:STRING=DYNAMIC .
make all && make install

The mysql community version has a libmysqlclient.so in /usr/local/mysql/lib located. If I compile it with the options given above I only found these files in /usr/local/mysql/lib (MariaDB 10.2.6):

# ls -l /usr/local/mysql/lib/
total 3572
-rw-r--r-- 1 root root 2305518 Jul  4 08:14 libmariadbclient.a
lrwxrwxrwx 1 root root      15 Jul  4 08:31 libmariadb.so -> libmariadb.so.3
-rwxr-xr-x 1 root root 1297664 Jul  4 08:14 libmariadb.so.3
-rw-r--r-- 1 root root   48406 Jul  4 08:14 libmysqlservices.a
drwxr-xr-x 2 root root    4096 Jul  4 08:31 plugin

How can I get libmysqlclient.so? There isn't also any libmariadbclient.so just libmariadbclient.a ...

Thank you for further hints!

Body:
OK, now I found a solution.
I've just did a symbolic link to libmariadb.so and it now looks like the following:

ls -l /usr/local/mysql/lib/
total 3572
-rw-r--r-- 1 root root 2305518 Jul  4 16:21 libmariadbclient.a
lrwxrwxrwx 1 root root      15 Jul  4 16:39 libmariadb.so -> libmariadb.so.3
-rwxr-xr-x 1 root root 1297664 Jul  4 16:21 libmariadb.so.3
lrwxrwxrwx 1 root root      15 Jul  4 16:40 libmysqlclient_r.so -> libmariadb.so.3
lrwxrwxrwx 1 root root      15 Jul  4 16:40 libmysqlclient.so -> libmariadb.so.3
-rw-r--r-- 1 root root   48406 Jul  4 16:21 libmysqlservices.a
drwxr-xr-x 2 root root    4096 Jul  4 16:39 plugin

In this case PHP 7 would finally find the mysql libraries...


问:
MySql.Data.MySqlClient for C#, time expires for a large MySql table
I am using MySql.Data.MySqlClient for C# in one of my applications.

At certain point, my .net application selects, from one large MySql table, which :

has two columns,

one column is the primary key ( PRI, int(11), auto increment )

other column is the column that contains some text, ( varchar(8000) )

one example entry for this column is:

info1=a;info2=b;cIndex=1;info4=d;info5=0.33;

just by chance, the entries on this very large table that includes the text segment "'%cIndex=1;%'" are before from the entries that includes the text segment for larger cIndex values, such as 34.

For instance:

the entry with a column2 value of
"info1=a;info2=b;cIndex=1;info4=d;info5=0.33"; is the 45566th entry
on this database,

whereas the entry with column2 value of
"info1=a;info2=b;cIndex=34;info4=d;info5=0.33;" is the 10,000,000th
entry on the table.

So basically, the entries with lower cIndex values are before from
the entries with higher cIndex values.

Key difference for this table from my earlier applications is that, the table I am running sql statement is "very large" by my standards;

with 2 columns

yet 24.6 million rows.

and with a data structure I mentioned above.

An example of the sql statement I am running from within my application is:

```<code>SELECT column2 FROM myLargeTable WHERE (column2 LIKE
'%info3=1;%') AND (column2 LIKE '%cIndex=0;%');
</code>```

And, the method I am using in my c# application in order to run this query for a result is basically as follows:

```<code>public static string getInfoFromDb(string tbl, string col, string whr)
{

string myInfo = "error";

string sqlStr = "SELECT " + col + " from " + tbl + " " + whr + " " + " LIMIT 1 ";

MySqlConnection cn = new MySqlConnection(cstr);
cn.Open();
try
{
MySqlCommand co = new MySqlCommand(sqlStr, cn);
MySqlDataReader rd = co.ExecuteReader();
while (rd.Read()) { myInfo = rd.GetString(col); }
co.Dispose();
}

catch { /* do nothing */}
cn.Close();

return myInfo;
}
</code>```

(So, the code is pretty much simple and it worked, for long years, for my databases where the tables sizes was much smaller at around, say, 70000+ rows)

My question is:

my sql statement returns the correct result when it is run from the
editor page of Toad-for-MySql, for any cIndex value - either it is a
smaller value such as 1, or a larger value such as 34. In any case,
the sql statement returns the correct result.

And, expectedly, this sql statement returns the correct result when the same sql statement is run, from within my C# application this time, when the cIndex value is small such as 1, i.e. SELECT column2 FROM myLargeTable WHERE (column2 LIKE '%info3=1;%') AND (column2 LIKE '%cIndex=1;%') returns the correct result.

But, interestingly, and this time unexpectedly, the very same sql statement returns error saying timeout expired when the same sql statement is run, from within my C# application, when the cIndex value of interest in the sql statement is larger, such as 34. i.e. SELECT column2 FROM myLargeTable WHERE (column2 LIKE '%info3=1;%') AND (column2 LIKE '%cIndex=34;%')

Any help is very much appreciated.

Thanks in advance for your time and considerations.

答:
I figured out that the error is due to timeout for larger tables.

So, apparently, adding this line of code into my method solved the problem:

```<code>co.CommandTimeout = 600; // keep this value relatively large while working with large databases
</code>```

Body:
I am using MySql.Data.MySqlClient for C# in one of my applications.

At certain point, my .net application selects, from one large MySql table, which :

has two columns,

one column is the primary key ( PRI, int(11), auto increment )

other column is the column that contains some text, ( varchar(8000) )

one example entry for this column is:

info1=a;info2=b;cIndex=1;info4=d;info5=0.33;

just by chance, the entries on this very large table that includes the text segment "'%cIndex=1;%'" are before from the entries that includes the text segment for larger cIndex values, such as 34.

For instance:

the entry with a column2 value of
"info1=a;info2=b;cIndex=1;info4=d;info5=0.33"; is the 45566th entry
on this database,

whereas the entry with column2 value of
"info1=a;info2=b;cIndex=34;info4=d;info5=0.33;" is the 10,000,000th
entry on the table.

So basically, the entries with lower cIndex values are before from
the entries with higher cIndex values.

Key difference for this table from my earlier applications is that, the table I am running sql statement is "very large" by my standards;

with 2 columns

yet 24.6 million rows.

and with a data structure I mentioned above.

An example of the sql statement I am running from within my application is:

SELECT column2 FROM myLargeTable WHERE (column2 LIKE
'%info3=1;%') AND (column2 LIKE '%cIndex=0;%');

And, the method I am using in my c# application in order to run this query for a result is basically as follows:

public static string getInfoFromDb(string tbl, string col, string whr)
{

string myInfo = "error";

string sqlStr = "SELECT " + col + " from " + tbl + " " + whr + " " + " LIMIT 1 ";

MySqlConnection cn = new MySqlConnection(cstr);
cn.Open();
try
{
MySqlCommand co = new MySqlCommand(sqlStr, cn);
MySqlDataReader rd = co.ExecuteReader();
while (rd.Read()) { myInfo = rd.GetString(col); }
co.Dispose();
}

catch { /* do nothing */}
cn.Close();

return myInfo;
}

(So, the code is pretty much simple and it worked, for long years, for my databases where the tables sizes was much smaller at around, say, 70000+ rows)

My question is:

my sql statement returns the correct result when it is run from the
editor page of Toad-for-MySql, for any cIndex value - either it is a
smaller value such as 1, or a larger value such as 34. In any case,
the sql statement returns the correct result.

And, expectedly, this sql statement returns the correct result when the same sql statement is run, from within my C# application this time, when the cIndex value is small such as 1, i.e. SELECT column2 FROM myLargeTable WHERE (column2 LIKE '%info3=1;%') AND (column2 LIKE '%cIndex=1;%') returns the correct result.

But, interestingly, and this time unexpectedly, the very same sql statement returns error saying timeout expired when the same sql statement is run, from within my C# application, when the cIndex value of interest in the sql statement is larger, such as 34. i.e. SELECT column2 FROM myLargeTable WHERE (column2 LIKE '%info3=1;%') AND (column2 LIKE '%cIndex=34;%')

Any help is very much appreciated.

Thanks in advance for your time and considerations.

Body:
I figured out that the error is due to timeout for larger tables.

So, apparently, adding this line of code into my method solved the problem:

co.CommandTimeout = 600; // keep this value relatively large while working with large databases


问:
How to fetch all records using SQL query using JOIN command (related to Distinct)
This is my SQL Query

```<code>SELECT tmdb_movies.movie_title
,GROUP_CONCAT(DISTINCT recommendations.recommendations_vote_average) as recommendations_vote_average

FROM tmdb_movies

LEFT JOIN recommendations ON recommendations.recommendations_tmdb_id=tmdb_movies.tmdb_id

Where tmdb_movies.tmdb_id=155

GROUP BY tmdb_movies.movie_title
</code>```

This is how my recommentions able looks like:

So, now ,GROUP_CONCAT(DISTINCT recommendations.recommendations_vote_average) as recommendations_vote_average
 If I use DISTINCT here, then it do not show vote_average of the following movies: The Matrix, Inception, Iron Man 2, Captain America: The First Avenger. +it shows wrong vote_average of all movies (leaving first)

If i do not use Distinct then it shows 7.5 in all records.

How to solve this problem? Let me know, if you need more information.

答:
Try This:        </p>

```<code>        SELECT tmdb_movies.movie_title,
        GROUP_CONCAT(recommendations.recommendations_vote_average)
         as recommendations_vote_average
        FROM tmdb_movies
        LEFT JOIN (select * from recommendations group by recommendations_vote_average)
        recommendations
        ON recommendations.recommendations_tmdb_id=tmdb_movies.tmdb_id
        Where tmdb_movies.tmdb_id=155
        GROUP BY tmdb_movies.movie_title
</code>```

Body:
This is my SQL Query

SELECT tmdb_movies.movie_title
,GROUP_CONCAT(DISTINCT recommendations.recommendations_vote_average) as recommendations_vote_average

FROM tmdb_movies

LEFT JOIN recommendations ON recommendations.recommendations_tmdb_id=tmdb_movies.tmdb_id

Where tmdb_movies.tmdb_id=155

GROUP BY tmdb_movies.movie_title

This is how my recommentions able looks like:

So, now ,GROUP_CONCAT(DISTINCT recommendations.recommendations_vote_average) as recommendations_vote_average
 If I use DISTINCT here, then it do not show vote_average of the following movies: The Matrix, Inception, Iron Man 2, Captain America: The First Avenger. +it shows wrong vote_average of all movies (leaving first)

If i do not use Distinct then it shows 7.5 in all records.

How to solve this problem? Let me know, if you need more information.

Body:
Try This:

        SELECT tmdb_movies.movie_title,
        GROUP_CONCAT(recommendations.recommendations_vote_average)
         as recommendations_vote_average
        FROM tmdb_movies
        LEFT JOIN (select * from recommendations group by recommendations_vote_average)
        recommendations
        ON recommendations.recommendations_tmdb_id=tmdb_movies.tmdb_id
        Where tmdb_movies.tmdb_id=155
        GROUP BY tmdb_movies.movie_title


问:
Find the kth smallest element in an unsorted array of non-negative integers
Not allowed to modify the array ( The array is read only ).
Using constant extra space is allowed.

ex:
A : [2 1 4 3 2]
k : 3

answer : 2

I did it below way. The answer is correct but need to be more memory efficient.

```<code>void insert_sorted(vector<int> &B, int a,int k)
{
    for(int i=0;i<k;i++)
    {
        if(B[i]>=a)
        {
            for(int j=k-1;j>i;j--)
                B[j]=B[j-1];
            B[i]=a;
            return;
        }
    }
}

int Solution::kthsmallest(const vector<int> &A, int k) {

    vector <int> B;
    for(int i=0;i<k;i++)
    {
        B.push_back(INT_MAX);
    }
    int l=A.size();

    for(int i=0;i<l;i++)
    {
        if(B[k-1]>=A[i])
            insert_sorted(B,A[i],k);
    }

    return B[k-1];
}
</code>```

答:
The question does not ask for any time constraints. An O(nk) solution is fairly simple, by iterating the array k times (at most), and discarding one element (and its duplicates) each time.

```<code>int FindKthSmallesr(const std::vector<int>& v, int k) {
  // assuming INT_MIN cannot be a value. Could be relaxed by an extra iteration.
  int last_min = INT_MIN;
  while (k > 0) {
    int current_min = INT_MAX;
    for (int x : v) {
      if (x <= last_min) continue;
      current_min = std::min(current_min, x);
    }
    last_min = current_min;
    for (int x : v) {
      if (x == current_min) k--;
    }
  }
  return last_min;
}
</code>```

Code on ideone: http://ideone.com/RjRIkM

Body:
Not allowed to modify the array ( The array is read only ).
Using constant extra space is allowed.

ex:
A : [2 1 4 3 2]
k : 3

answer : 2

I did it below way. The answer is correct but need to be more memory efficient.

void insert_sorted(vector<int> &B, int a,int k)
{
    for(int i=0;i<k;i++)
    {
        if(B[i]>=a)
        {
            for(int j=k-1;j>i;j--)
                B[j]=B[j-1];
            B[i]=a;
            return;
        }
    }
}

int Solution::kthsmallest(const vector<int> &A, int k) {

    vector <int> B;
    for(int i=0;i<k;i++)
    {
        B.push_back(INT_MAX);
    }
    int l=A.size();

    for(int i=0;i<l;i++)
    {
        if(B[k-1]>=A[i])
            insert_sorted(B,A[i],k);
    }

    return B[k-1];
}

Body:
The question does not ask for any time constraints. An O(nk) solution is fairly simple, by iterating the array k times (at most), and discarding one element (and its duplicates) each time.

int FindKthSmallesr(const std::vector<int>& v, int k) {
  // assuming INT_MIN cannot be a value. Could be relaxed by an extra iteration.
  int last_min = INT_MIN;
  while (k > 0) {
    int current_min = INT_MAX;
    for (int x : v) {
      if (x <= last_min) continue;
      current_min = std::min(current_min, x);
    }
    last_min = current_min;
    for (int x : v) {
      if (x == current_min) k--;
    }
  }
  return last_min;
}

Code on ideone: http://ideone.com/RjRIkM


问:
parse_str and ajax and sql injection
I want post data with ajax to the php file.

I  write this code:

```<code>$.ajax({
            type: 'post',
            url: 'ajax-processor.php',
            data: {
                ser: $('#user_new').serialize(),  //#user_new is form
                actioncode: 25,
                mobile: 911111111
            },
            dataType: 'json',
            success: function (responce) {

                }
</code>```

and in php file

```<code> if (isset($_POST['ser'])) {
        $serArray = array();
        parse_str($_POST['ser'], $serArray);
</code>```

Doing echo  $serArray return an empty Array

What is problem?

What is the best way of get data that sent whit serialize jquery in php file as a  object?

Also, is secure use $serArray in query mysql whit out any change?

Thanks

答:
i do this

```<code>parse_str(urldecode($_POST['ser']),$serArray);
</code>```

and get value

```<code>$fname = $serArray['fname'];
</code>```

and

```<code>$fname = mysqli_real_escape_string($fname);
</code>```

to send to mysql

Title: parse_str and ajax and sql injection

Body:
I want post data with ajax to the php file.

I  write this code:

$.ajax({
            type: 'post',
            url: 'ajax-processor.php',
            data: {
                ser: $('#user_new').serialize(),  //#user_new is form
                actioncode: 25,
                mobile: 911111111
            },
            dataType: 'json',
            success: function (responce) {

                }

and in php file

 if (isset($_POST['ser'])) {
        $serArray = array();
        parse_str($_POST['ser'], $serArray);

Doing echo  $serArray return an empty Array

What is problem?

What is the best way of get data that sent whit serialize jquery in php file as a  object?

Also, is secure use $serArray in query mysql whit out any change?

Thanks

Body:
i do this

parse_str(urldecode($_POST['ser']),$serArray);

and get value

$fname = $serArray['fname'];

and

$fname = mysqli_real_escape_string($fname);

to send to mysql


答:
```<code>UPDATE  homeScroller
SET     id = CASE id WHEN $id THEN $newid ELSE $id END
WHERE   id IN ($id, $newid)
</code>```

Title: Update two ID's at once SQL - PHP


问:
Backtracking solution for palindrome partitioning issue with displacement of sub-string in the output
I am solving the question of palindrome partitioning on Leetcode.

I have written a recursive solution which prints the correct Lists of substrings but for one of the test cases, the order in the list does not match the expected output.

Input:

cbbbcc

Output:

[["c","b","b","b","c","c"],["b","b","b","c","cc"],["b","c","bb","c","c"],["b","bb","c","cc"],["c","bb","b","c","c"],["bb","b","c","cc"],["c","bbb","c","c"],["bbb","c","cc"],["cbbbc","c"]]

Expected:

[["c","b","b","b","c","c"],["c","b","b","b","cc"],["c","b","bb","c","c"],["c","b","bb","cc"],["c","bb","b","c","c"],["c","bb","b","cc"],["c","bbb","c","c"],["c","bbb","cc"],["cbbbc","c"]]

I am not able to figure out why is my recursive call shifting the first element "c" in this example.

```<code>public class Solution {

public List<List<String>> partition(String s) {

    List<List<String>> result = new ArrayList<>();
    backTrack(result, new ArrayList<String>(), s);

    return result;
}

private void backTrack(List<List<String>> result, List<String> cur, String s){

    if(s.length() == 0)
        result.add(new ArrayList<>(cur));

    /* length = i+1 */
    for(int i = 0; i < s.length(); i++){
        if(isPalindrome(s.substring(0, i+1))){
            cur.add(s.substring(0, i+1));
            backTrack(result, cur, s.substring(i+1, s.length()));
            cur.remove(s.substring(0, i+1));
        }
    }

}

private boolean isPalindrome(String s){
    int start = 0, end = s.length() - 1;
    char[] schars = s.toCharArray();

    while(start < end){
        if(schars[start] != schars[end])
            return false;
        start++;
        end--;
    }
    return true;
}
}
</code>```

I did go through an example and as per my logic, I do not see any reason that "c" should be displaced as in the output.

答:
The problem is because of the way you expect add and remove to behave with your List.

Initially, you are building up cur from s (here cbbbcc):

```<code>s           cur
1. cbbbcc   []
2. bbbcc    [c]
3. bbcc     [c, b]
4. bcc      [c, b, b]
5. cc       [c, b, b, b]
6. c        [c, b, b, b, c]
7.          [c, b, b, b, c, c]
</code>```

Now, the calls to backTrack() return in the reverse order 7, 6, 5, ...

Thus, this line:

```<code>cur.remove(s.substring(0, i+1));
</code>```

is first run with the substring "c".

Ideally, your code should remove the rightmost "c" from cur. But the remove method removes the first "c" that it encounters, which is at position 0. From here on, your ordering is always wrong.

The easiest solution would be to always add to the first position to match the default behaviour for remove(). You would need to invert the String before using it in this way, though.

I've modified your code appropriately, here:

```<code>import java.util.*;
import java.lang.*;

public class Solution {

  public List<List<String>> partition(String s) {

      List<List<String>> result = new ArrayList<>();
      backTrack(result, new ArrayList<String>(), new StringBuilder(s).reverse().toString());  // EDIT 1: Invert String

      return result;
  }

  private void backTrack(List<List<String>> result, List<String> cur, String s) {
      if(s.length() == 0) result.add(new ArrayList<>(cur));

      for(int i = 0; i < s.length(); i++){
          if(isPalindrome(s.substring(0, i+1))){
              cur.add(0, s.substring(0, i+1)); // EDIT 2: Add to beginning of list
              backTrack(result, cur, s.substring(i+1, s.length()));
              cur.remove(s.substring(0, i+1));
          }
      }
  }

  private boolean isPalindrome(String s) {
      int start = 0, end = s.length() - 1;
      char[] schars = s.toCharArray();

      while(start < end){
          if(schars[start] != schars[end])
              return false;
          start++;
          end--;
      }
      return true;
  }
}
</code>```

You can run in online here or below.

```

Alternatively, instead of reversing the string and adding to the left of the list, you could simply remove() by finding the rightmost occurrence of the character in the list.

Body:
I am solving the question of palindrome partitioning on Leetcode.

I have written a recursive solution which prints the correct Lists of substrings but for one of the test cases, the order in the list does not match the expected output.

Input:

cbbbcc

Output:

[["c","b","b","b","c","c"],["b","b","b","c","cc"],["b","c","bb","c","c"],["b","bb","c","cc"],["c","bb","b","c","c"],["bb","b","c","cc"],["c","bbb","c","c"],["bbb","c","cc"],["cbbbc","c"]]

Expected:

[["c","b","b","b","c","c"],["c","b","b","b","cc"],["c","b","bb","c","c"],["c","b","bb","cc"],["c","bb","b","c","c"],["c","bb","b","cc"],["c","bbb","c","c"],["c","bbb","cc"],["cbbbc","c"]]

I am not able to figure out why is my recursive call shifting the first element "c" in this example.

public class Solution {

public List<List<String>> partition(String s) {

    List<List<String>> result = new ArrayList<>();
    backTrack(result, new ArrayList<String>(), s);

    return result;
}

private void backTrack(List<List<String>> result, List<String> cur, String s){

    if(s.length() == 0)
        result.add(new ArrayList<>(cur));

    /* length = i+1 */
    for(int i = 0; i < s.length(); i++){
        if(isPalindrome(s.substring(0, i+1))){
            cur.add(s.substring(0, i+1));
            backTrack(result, cur, s.substring(i+1, s.length()));
            cur.remove(s.substring(0, i+1));
        }
    }

}

private boolean isPalindrome(String s){
    int start = 0, end = s.length() - 1;
    char[] schars = s.toCharArray();

    while(start < end){
        if(schars[start] != schars[end])
            return false;
        start++;
        end--;
    }
    return true;
}
}

I did go through an example and as per my logic, I do not see any reason that "c" should be displaced as in the output.

Body:
The problem is because of the way you expect add and remove to behave with your List.

Initially, you are building up cur from s (here cbbbcc):

s           cur
1. cbbbcc   []
2. bbbcc    [c]
3. bbcc     [c, b]
4. bcc      [c, b, b]
5. cc       [c, b, b, b]
6. c        [c, b, b, b, c]
7.          [c, b, b, b, c, c]

Now, the calls to backTrack() return in the reverse order 7, 6, 5, ...

Thus, this line:

cur.remove(s.substring(0, i+1));

is first run with the substring "c".

Ideally, your code should remove the rightmost "c" from cur. But the remove method removes the first "c" that it encounters, which is at position 0. From here on, your ordering is always wrong.

The easiest solution would be to always add to the first position to match the default behaviour for remove(). You would need to invert the String before using it in this way, though.

I've modified your code appropriately, here:

import java.util.*;
import java.lang.*;

public class Solution {

  public List<List<String>> partition(String s) {

      List<List<String>> result = new ArrayList<>();
      backTrack(result, new ArrayList<String>(), new StringBuilder(s).reverse().toString());  // EDIT 1: Invert String

      return result;
  }

  private void backTrack(List<List<String>> result, List<String> cur, String s) {
      if(s.length() == 0) result.add(new ArrayList<>(cur));

      for(int i = 0; i < s.length(); i++){
          if(isPalindrome(s.substring(0, i+1))){
              cur.add(0, s.substring(0, i+1)); // EDIT 2: Add to beginning of list
              backTrack(result, cur, s.substring(i+1, s.length()));
              cur.remove(s.substring(0, i+1));
          }
      }
  }

  private boolean isPalindrome(String s) {
      int start = 0, end = s.length() - 1;
      char[] schars = s.toCharArray();

      while(start < end){
          if(schars[start] != schars[end])
              return false;
          start++;
          end--;
      }
      return true;
  }
}

You can run in online here or below.

<script src="//repl.it/embed/JNx4/0.js"></script>

Alternatively, instead of reversing the string and adding to the left of the list, you could simply remove() by finding the rightmost occurrence of the character in the list.


问:
Protocols are not calling in swift Ios
Hi I am using NSUrlSession for calling a Web services in my Swift programing and more-ever I am new for Swift programming language.

In my below program I am using BackGroundClass for integrating webservices and after getting result I am using Protocols for receiving that response in my ViewController, but those protocols functions are not calling in my ViewController can some one help me please.

ViewController:-

```<code>import UIKit

class ViewController: UIViewController,sampleProtocal {

    override func viewDidLoad() {
        super.viewDidLoad()

        BackGroundClass.delegate = self

        let params = ["scancode":"KK03799-008", "UserName":"admin"] as Dictionary<String, String>
        let backGround=BackGroundClass();
        backGround.callPostService("my Url", parameters: params)

    }

    func getResponse(result: NSDictionary) {
        print("Final response is\(result)");
    }

    func getErrorResponse(error: NSString) {
        print("Final Eroor code is\(error)")
    }
}
</code>```

BackGroundClass:-

```<code>import UIKit

protocol sampleProtocal :  NSObjectProtocol{

    func getResponse(result:NSDictionary)
    func getErrorResponse(error:NSString)
}

class BackGroundClass: NSObject {

   var delegate:sampleProtocal?

    func callPostService(url:String,parameters:NSDictionary){

        print("url is===>\(url)")

        let request = NSMutableURLRequest(URL: NSURL(string:url)!)

        let session = NSURLSession.sharedSession()
        request.HTTPMethod = "POST"

        //Note : Add the corresponding "Content-Type" and "Accept" header. In this example I had used the application/json.
        request.addValue("application/json", forHTTPHeaderField: "Content-Type")
        request.addValue("application/json", forHTTPHeaderField: "Accept")

        request.HTTPBody = try! NSJSONSerialization.dataWithJSONObject(parameters, options: [])

        let task = session.dataTaskWithRequest(request) { data, response, error in
            guard data != nil else {
                print("no data found: \(error)")
                return
            }

            do {
                if let json = try NSJSONSerialization.JSONObjectWithData(data!, options: []) as? NSDictionary {
                    print("Response: \(json)")
                    self.mainResponse(json)
                } else {
                    let jsonStr = NSString(data: data!, encoding: NSUTF8StringEncoding)// No error thrown, but not NSDictionary
                    print("Error could not parse JSON: \(jsonStr)")
                    self.eroorResponse(jsonStr!)
                }
            } catch let parseError {
                print(parseError)// Log the error thrown by `JSONObjectWithData`
                let jsonStr = NSString(data: data!, encoding: NSUTF8StringEncoding)
                print("Error could not parse JSON: '\(jsonStr)'")
                self.eroorResponse(jsonStr!)
            }
        }

        task.resume()
    }

    func mainResponse(result:NSDictionary){
        delegate?.getResponse(result)
    }

    func eroorResponse(result:NSString){
        delegate?.getErrorResponse(result)
    }
}
</code>```

答:
Because you are not assigning the delegate</p>

```<code>// remove this
//BackGroundClass.delegate = self

let params = ["scancode":"KK03799-008", "UserName":"admin"] as Dictionary<String, String>
let backGround=BackGroundClass();
// assign delegate here
backGround.delegate = self
backGround.callPostService("my Url", parameters: params)
</code>```

Title: Protocols are not calling in swift Ios

Body:
Hi I am using NSUrlSession for calling a Web services in my Swift programing and more-ever I am new for Swift programming language.

In my below program I am using BackGroundClass for integrating webservices and after getting result I am using Protocols for receiving that response in my ViewController, but those protocols functions are not calling in my ViewController can some one help me please.

ViewController:-

import UIKit

class ViewController: UIViewController,sampleProtocal {

    override func viewDidLoad() {
        super.viewDidLoad()

        BackGroundClass.delegate = self

        let params = ["scancode":"KK03799-008", "UserName":"admin"] as Dictionary<String, String>
        let backGround=BackGroundClass();
        backGround.callPostService("my Url", parameters: params)

    }

    func getResponse(result: NSDictionary) {
        print("Final response is\(result)");
    }

    func getErrorResponse(error: NSString) {
        print("Final Eroor code is\(error)")
    }
}

BackGroundClass:-

import UIKit

protocol sampleProtocal :  NSObjectProtocol{

    func getResponse(result:NSDictionary)
    func getErrorResponse(error:NSString)
}

class BackGroundClass: NSObject {

   var delegate:sampleProtocal?

    func callPostService(url:String,parameters:NSDictionary){

        print("url is===>\(url)")

        let request = NSMutableURLRequest(URL: NSURL(string:url)!)

        let session = NSURLSession.sharedSession()
        request.HTTPMethod = "POST"

        //Note : Add the corresponding "Content-Type" and "Accept" header. In this example I had used the application/json.
        request.addValue("application/json", forHTTPHeaderField: "Content-Type")
        request.addValue("application/json", forHTTPHeaderField: "Accept")

        request.HTTPBody = try! NSJSONSerialization.dataWithJSONObject(parameters, options: [])

        let task = session.dataTaskWithRequest(request) { data, response, error in
            guard data != nil else {
                print("no data found: \(error)")
                return
            }

            do {
                if let json = try NSJSONSerialization.JSONObjectWithData(data!, options: []) as? NSDictionary {
                    print("Response: \(json)")
                    self.mainResponse(json)
                } else {
                    let jsonStr = NSString(data: data!, encoding: NSUTF8StringEncoding)// No error thrown, but not NSDictionary
                    print("Error could not parse JSON: \(jsonStr)")
                    self.eroorResponse(jsonStr!)
                }
            } catch let parseError {
                print(parseError)// Log the error thrown by `JSONObjectWithData`
                let jsonStr = NSString(data: data!, encoding: NSUTF8StringEncoding)
                print("Error could not parse JSON: '\(jsonStr)'")
                self.eroorResponse(jsonStr!)
            }
        }

        task.resume()
    }

    func mainResponse(result:NSDictionary){
        delegate?.getResponse(result)
    }

    func eroorResponse(result:NSString){
        delegate?.getErrorResponse(result)
    }
}

Body:
Because you are not assigning the delegate

// remove this
//BackGroundClass.delegate = self

let params = ["scancode":"KK03799-008", "UserName":"admin"] as Dictionary<String, String>
let backGround=BackGroundClass();
// assign delegate here
backGround.delegate = self
backGround.callPostService("my Url", parameters: params)


问:
django models filefield upload
I want to create a song list for eg  "movie name Titanic and it contains all its songs" but I don't know to add more than one song in a movie, can some one help me here?

Here is what I am doing

views.py

```<code>from django.shortcuts import render_to_response
from .models import Songs

def Songs(request):
    songs = Songs.objects.all()
    return render_to_response('profile_page.html',{'songs':songs})
</code>```

models.py

```<code>from django.db import models

class Movie(models.Model):
    name= models.CharField(max_length = 100)

class Songs(models.Model):
    movie = models.ForeignKey(Movie, default= 1)
    song_title = models.CharField(max_length=20)
    song_poster = models.FileField()
    song_list = models.FileField()
</code>```

urls.py

```<code>from django.conf.urls import url
from . import views

urlpatterns = [
    url(r'^',views.Songs),
]
</code>```

答:
create a model called Movie

```<code>class Movie(models.Model):
    name= models.CharField(max_length = 100)
    // other fields as needed

class Songs(models.Model):
    movie = models.ForeignKey(Movie)
    song_title = models.CharField(max_length=20)
    song_poster = models.FileField()
    song_list = models.FileField()
</code>```

then add songs according to movie and query according to movie id

Title: django models filefield upload

Body:
I want to create a song list for eg  "movie name Titanic and it contains all its songs" but I don't know to add more than one song in a movie, can some one help me here?

Here is what I am doing

views.py

from django.shortcuts import render_to_response
from .models import Songs

def Songs(request):
    songs = Songs.objects.all()
    return render_to_response('profile_page.html',{'songs':songs})

models.py

from django.db import models

class Movie(models.Model):
    name= models.CharField(max_length = 100)

class Songs(models.Model):
    movie = models.ForeignKey(Movie, default= 1)
    song_title = models.CharField(max_length=20)
    song_poster = models.FileField()
    song_list = models.FileField()

urls.py

from django.conf.urls import url
from . import views

urlpatterns = [
    url(r'^',views.Songs),
]

Body:
create a model called Movie

class Movie(models.Model):
    name= models.CharField(max_length = 100)
    // other fields as needed

class Songs(models.Model):
    movie = models.ForeignKey(Movie)
    song_title = models.CharField(max_length=20)
    song_poster = models.FileField()
    song_list = models.FileField()

then add songs according to movie and query according to movie id


问:
Use web page framework (i.e. Bootstrap) only on application part, not (static) website pages?
I already have a design for a website. If I would use i.e. Bootstrap, it would take a lot of work to convert bootstrap to the design (more than I would gain from the framework). Yet this only applies to the design and relatively static pages (home, content).
I feel however that I would gain benefit if using Bootstrap for the application part (inputs with error messages, buttons, date picker, and so on).
Would there be a problem just using some elements without the "frame"  around it (no BS-grid)? </p>

答: No there will be no problem but take cae that you also take the css and js while of the part you want want in the folder.</p>


问:
Need to get the predicted values into a csv or Sframe or Dataframe in Python

Prerequisites

Dataset I'm working with is MovieLens 100k

Python Packages I'm using is Surprise, Io and Pandas

Agenda is to test the recommendation system using KNN (+ K-Fold) on Algorithms: Vector cosine & Pearson, for both User based CF & Item based CF

Briefing

So far, I have coded for both UBCF & IBCF as below

Q1. IBCF Generates data as per input given to it, I need it to export a csv file since I need to find out the predicted values

Q2. UBCF needs to enter each data separately and doesn't work even with immediate below code:

```<code>csvfile = 'pred_matrix.csv'
    with open(csvfile, "w") as output:
        writer = csv.writer(output,lineterminator='\n')
#algo.predict(user_id, item_id, estimated_ratings)
        for val in algo.predict(str(range(1,943)),range(1,1683),1):
            writer.writerow([val])
</code>```

Clearly it throws the error of lists, as it cannot be Comma separated.

Q3 Getting Precision & Recall on Evaluated and Recommended values

CODE

STARTS WITH

```<code>if ip == 1:
    one = 'cosine'
else:
    one = 'pearson'

choice = raw_input("Filtering Method: \n1.User based \n2.Item based \n Choice:")

if choice == '1':
    user_based_cf(one)
elif choice == '2':
    item_based_cf(one)
else:
    sim_op={}
    exit(0)
</code>```

UBCF:

```<code>def user_based_cf(co_pe):
    # INITIALIZE REQUIRED PARAMETERS
    path = '/home/mister-t/Projects/PycharmProjects/RecommendationSys/ml-100k/u.user'
    prnt = "USER"
    sim_op = {'name': co_pe, 'user_based': True}
    algo = KNNBasic(sim_options=sim_op)

    # RESPONSIBLE TO EXECUTE DATA SPLITS Mentioned in STEP 4
    perf = evaluate(algo, df, measures=['RMSE', 'MAE'])
    print_perf(perf)
    print type(perf)

    # START TRAINING
    trainset = df.build_full_trainset()

    # APPLYING ALGORITHM KNN Basic
    res = algo.train(trainset)
    print "\t\t >>>TRAINED SET<<<<\n\n", res

    # PEEKING PREDICTED VALUES
    search_key = raw_input("Enter User ID:")
    item_id = raw_input("Enter Item ID:")
    actual_rating = input("Enter actual Rating:")

    print algo.predict(str(search_key), item_id, actual_rating)
</code>```

IBCF

```<code>def item_based_cf(co_pe):
    # INITIALIZE REQUIRED PARAMETERS
    path = '/location/ml-100k/u.item'
    prnt = "ITEM"
    sim_op = {'name': co_pe, 'user_based': False}
    algo = KNNBasic(sim_options=sim_op)

 # RESPONSIBLE TO EXECUTE DATA SPLITS = 2
 perf = evaluate(algo, df, measures=['RMSE', 'MAE'])
 print_perf(perf)
 print type(perf)

 # START TRAINING
 trainset = df.build_full_trainset()

 # APPLYING ALGORITHM KNN Basic
 res = algo.train(trainset)
 print "\t\t >>>TRAINED SET<<<<\n\n", res

 # Read the mappings raw id <-> movie name
 rid_to_name, name_to_rid = read_item_names(path)

 search_key = raw_input("ID:")
 print "ALGORITHM USED : ", one
 toy_story_raw_id = name_to_rid[search_key]
 toy_story_inner_id = algo.trainset.to_inner_iid(toy_story_raw_id)

 # Retrieve inner ids of the nearest neighbors of Toy Story.
 k=5
 toy_story_neighbors = algo.get_neighbors(toy_story_inner_id, k=k)

 # Convert inner ids of the neighbors into names.
 toy_story_neighbors = (algo.trainset.to_raw_iid(inner_id)
                    for inner_id in toy_story_neighbors)
 toy_story_neighbors = (rid_to_name[rid]
                    for rid in toy_story_neighbors)
 print 'The ', k,' nearest neighbors of ', search_key,' are:'
 for movie in toy_story_neighbors:
     print(movie)
</code>```

答:
Q1. IBCF Generates data as per input given to it, I need it to export a csv file since I need to find out the predicted values

the easiest way to dump anything to a csv would be to use the csv module!

```<code>import csv

res = [x, y, z, ....]
csvfile = "<path to output csv or txt>"

#Assuming res is a flat list
with open(csvfile, "w") as output:
    writer = csv.writer(output, lineterminator='\n')
    for val in res:
        writer.writerow([val])

#Assuming res is a list of lists
with open(csvfile, "w") as output:
    writer = csv.writer(output, lineterminator='\n')
    writer.writerows(res)
</code>```

Body:
Prerequisites

Dataset I'm working with is MovieLens 100k

Python Packages I'm using is Surprise, Io and Pandas

Agenda is to test the recommendation system using KNN (+ K-Fold) on Algorithms: Vector cosine & Pearson, for both User based CF & Item based CF

Briefing

So far, I have coded for both UBCF & IBCF as below

Q1. IBCF Generates data as per input given to it, I need it to export a csv file since I need to find out the predicted values

Q2. UBCF needs to enter each data separately and doesn't work even with immediate below code:

csvfile = 'pred_matrix.csv'
    with open(csvfile, "w") as output:
        writer = csv.writer(output,lineterminator='\n')
#algo.predict(user_id, item_id, estimated_ratings)
        for val in algo.predict(str(range(1,943)),range(1,1683),1):
            writer.writerow([val])

Clearly it throws the error of lists, as it cannot be Comma separated.

Q3 Getting Precision & Recall on Evaluated and Recommended values

CODE

STARTS WITH

if ip == 1:
    one = 'cosine'
else:
    one = 'pearson'

choice = raw_input("Filtering Method: \n1.User based \n2.Item based \n Choice:")

if choice == '1':
    user_based_cf(one)
elif choice == '2':
    item_based_cf(one)
else:
    sim_op={}
    exit(0)

UBCF:

def user_based_cf(co_pe):
    # INITIALIZE REQUIRED PARAMETERS
    path = '/home/mister-t/Projects/PycharmProjects/RecommendationSys/ml-100k/u.user'
    prnt = "USER"
    sim_op = {'name': co_pe, 'user_based': True}
    algo = KNNBasic(sim_options=sim_op)

    # RESPONSIBLE TO EXECUTE DATA SPLITS Mentioned in STEP 4
    perf = evaluate(algo, df, measures=['RMSE', 'MAE'])
    print_perf(perf)
    print type(perf)

    # START TRAINING
    trainset = df.build_full_trainset()

    # APPLYING ALGORITHM KNN Basic
    res = algo.train(trainset)
    print "\t\t >>>TRAINED SET<<<<\n\n", res

    # PEEKING PREDICTED VALUES
    search_key = raw_input("Enter User ID:")
    item_id = raw_input("Enter Item ID:")
    actual_rating = input("Enter actual Rating:")

    print algo.predict(str(search_key), item_id, actual_rating)

IBCF

def item_based_cf(co_pe):
    # INITIALIZE REQUIRED PARAMETERS
    path = '/location/ml-100k/u.item'
    prnt = "ITEM"
    sim_op = {'name': co_pe, 'user_based': False}
    algo = KNNBasic(sim_options=sim_op)

 # RESPONSIBLE TO EXECUTE DATA SPLITS = 2
 perf = evaluate(algo, df, measures=['RMSE', 'MAE'])
 print_perf(perf)
 print type(perf)

 # START TRAINING
 trainset = df.build_full_trainset()

 # APPLYING ALGORITHM KNN Basic
 res = algo.train(trainset)
 print "\t\t >>>TRAINED SET<<<<\n\n", res

 # Read the mappings raw id <-> movie name
 rid_to_name, name_to_rid = read_item_names(path)

 search_key = raw_input("ID:")
 print "ALGORITHM USED : ", one
 toy_story_raw_id = name_to_rid[search_key]
 toy_story_inner_id = algo.trainset.to_inner_iid(toy_story_raw_id)

 # Retrieve inner ids of the nearest neighbors of Toy Story.
 k=5
 toy_story_neighbors = algo.get_neighbors(toy_story_inner_id, k=k)

 # Convert inner ids of the neighbors into names.
 toy_story_neighbors = (algo.trainset.to_raw_iid(inner_id)
                    for inner_id in toy_story_neighbors)
 toy_story_neighbors = (rid_to_name[rid]
                    for rid in toy_story_neighbors)
 print 'The ', k,' nearest neighbors of ', search_key,' are:'
 for movie in toy_story_neighbors:
     print(movie)

Body:
Q1. IBCF Generates data as per input given to it, I need it to export a csv file since I need to find out the predicted values

the easiest way to dump anything to a csv would be to use the csv module!

import csv

res = [x, y, z, ....]
csvfile = "<path to output csv or txt>"

#Assuming res is a flat list
with open(csvfile, "w") as output:
    writer = csv.writer(output, lineterminator='\n')
    for val in res:
        writer.writerow([val])

#Assuming res is a list of lists
with open(csvfile, "w") as output:
    writer = csv.writer(output, lineterminator='\n')
    writer.writerows(res)


问:
I cannot find the name of a dynamically created javascript object (in jQuery)
I have a page which uses javascript to add some textboxes to the page, and then we try to do some work based on these later.

What I am having a lot of trouble with though is that I cannot return the 'name' value which I am saving with the js.

Full page source (albeit a simplified version) is below.

```<code><html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <script type="text/javascript" src="Scripts/jquery-1.4.1-vsdoc.js"></script>
    <script type="text/javascript">
    $(document).ready(function () {
        //we use live because the inputs havent been created yet.
        $('.myclass').live('blur', function () {

            //debugger;
            alert('textbox selected has ID '+ $(this).attr('id') ); //this returns txtInput
            alert('textbox selected has name '+ $(this).attr('name') ); //this returns null (or an empty string).
        });

    AddInputTextBox("My Label: ", "txtInput", "mydiv", "MyName");

    });

    function AddInputTextBox(LabelValue, Id, divToAddTo, NameKey) {
        //debugger;
        var txtbox = document.createElement('input');
        txtbox.setAttribute("type", "text");
        txtbox.setAttribute("id", Id);
        txtbox.setAttribute("name", NameKey);
        txtbox.setAttribute("class", "myclass");

        alert('Textbox created with name = ' + txtbox.name);

        var foo = document.getElementById(divToAddTo);
        foo.innerHTML += LabelValue;
        foo.appendChild(txtbox);
    }
    </script>
</head>

<body>
    <div id="mydiv">
        <!-- placeholder -->
    </div>
</body>
</html>
</code>```

So as you can see, document.ready runs and creates one textbox.
when the blur fires (box loses focus) - I can access the ID, class, type, etc, but I cannot get a value for the 'name'.

Sure it is something dead simple, but can someone tell me why?

答:
When you create <input> elements with IE, you have to do it like this:

```<code>var txtbox = document.createElement('<input name="' + NameKey + '">');
</code>```

IE doesn't like you changing the "name" attribute of an <input> once it exists, so you have to tell it what you're going to do in the call to "createElement()".

One might wonder why you're not using jQuery to build your dynamic content, since you've loading it anyway.

(edit I thought it was the "type" attribute, but now I think it's "name".)

Body:
I have a page which uses javascript to add some textboxes to the page, and then we try to do some work based on these later.

What I am having a lot of trouble with though is that I cannot return the 'name' value which I am saving with the js.

Full page source (albeit a simplified version) is below.

So as you can see, document.ready runs and creates one textbox.
when the blur fires (box loses focus) - I can access the ID, class, type, etc, but I cannot get a value for the 'name'.

Sure it is something dead simple, but can someone tell me why?

Body:
When you create <input> elements with IE, you have to do it like this:

var txtbox = document.createElement('<input name="' + NameKey + '">');

IE doesn't like you changing the "name" attribute of an <input> once it exists, so you have to tell it what you're going to do in the call to "createElement()".

One might wonder why you're not using jQuery to build your dynamic content, since you've loading it anyway.

(edit I thought it was the "type" attribute, but now I think it's "name".)


问:
How to force logout user when close tab
I am developing a enterprise application using spring and struts. But, i'm getting issue on Tab close. how to force user logging out when close the browser tab or open same page on another tab.

i have been try using onbeforeunload but i am getting issue when application running on mobile browser. and i also have seen following sample but No one has clear explanation.

How to kill session when user closed the browser without logout

How to Detect Browser Window /Tab Close Event?

is there any solution to achieve this problem using javascript or from server?
Thanks

答:
You may start a ajax request by page onload, and get a tracking session id/serial from server.

Later force all of the requests operations to include the tracking session you just gave to the page using the ajax call above.

If user opens up a new tab, the ajax load starts again. and As far as you check the live session tracks in the server with associated user, you may redirect the user to somewhere else or etc.

I don't think you may rely on onbeforeunload, just the same thing you experience.

As others stated, http is stateless, and cookies and requests are only stuffs you can check the state of the user.

At the server, session cookies could be invalidated by session timeout(if we assume user going to brew some coffee, e.g. it closes the page/tab).

And as explained in above solution, if he/she opens a new tab, the new ajax call might block him/her to perform a new login or etc.

I suggest you may find another solution instead of this approach you are trying to get. It's much easier and more senseful to sync the page state with the last opened page. Let the user opens 5 same page, and just sync them all with each other(simplest solution: refresh others when one gets updated)

Title: How to force logout user when close tab


问:
Difference between classes in Java vs JavaScript?
I have some experience with C# and Java, but I'm trying to learn javascript/node.js. I can't quite figure out what the problem is with this code.

So I have my main.js file, and it has this code:

```<code>const MyClass = require("./MyClass");
let myclass = new MyClass("my string!");

myclass.repeatString();
</code>```

The MyClass it's calling has this code:

```<code>class MyClass {
    constructor(myString) {
        this.myString = myString;
    }

    repeatString() {
        console.log(myString);
    }
}

module.exports = MyClass;
</code>```

When I try to run this, I get ReferenceError: myString is not defined when it tries to execute that repeatString() method. What am I doing wrong/what's the right way to do this?

答:
To access the variable of a class, use this. variable name.

Please check the code below.

class MyClass {
    constructor(myString) {
        this.myString = myString;
    }

    repeatString() {
        console.log(this.myString);
    }
}

const myClass = new MyClass('Hello');
myClass.repeatString();```

Body:
I have some experience with C# and Java, but I'm trying to learn javascript/node.js. I can't quite figure out what the problem is with this code.

So I have my main.js file, and it has this code:

const MyClass = require("./MyClass");
let myclass = new MyClass("my string!");

myclass.repeatString();

The MyClass it's calling has this code:

class MyClass {
    constructor(myString) {
        this.myString = myString;
    }

    repeatString() {
        console.log(myString);
    }
}

module.exports = MyClass;

When I try to run this, I get ReferenceError: myString is not defined when it tries to execute that repeatString() method. What am I doing wrong/what's the right way to do this?


问:
Hibernate constraint ConstraintViolationException. Is there an easy way to ignore duplicate entries?
Basically I've got the below schema and I'm inserting records if they don't exists. However when it comes to inserting a duplicate it throws and error as I would expect. My question is whether there is an easy way to make Hibernate to just ignore inserts which would in effect insert duplicates? </p>

```<code>CREATE TABLE IF NOT EXISTS `method` (
  `id` bigint(20) NOT NULL AUTO_INCREMENT,
  `name` varchar(10) DEFAULT NULL,
  PRIMARY KEY (`id`),
  UNIQUE KEY `name` (`name`)
) ENGINE=MyISAM  DEFAULT CHARSET=latin1 AUTO_INCREMENT=2 ;

SEVERE: Duplicate entry 'GET' for key 'name'
Exception in thread "pool-11-thread-4" org.hibernate.exception.ConstraintViolationException: could not insert:
</code>```

答:
You can use @SqlInsert annotation on your entity, to change the sql hibernate uses to make insertion in Database, hibernate currently must be using this statement

```<code>insert into method(name, id) values (?,?)
</code>```

If you are using mysql, you can use the @SqlInsert statement to change the insert sql by using insert ignore mysql statement

```<code>@SQLInsert(sql = "insert ignore into method(name, id) values (?,?)")
</code>```

However you should get the insert sqls by enabling show sql mode in hibernate, since the order of the columns is generated via some logic, and their docs suggest this way.

Body:
Basically I've got the below schema and I'm inserting records if they don't exists. However when it comes to inserting a duplicate it throws and error as I would expect. My question is whether there is an easy way to make Hibernate to just ignore inserts which would in effect insert duplicates?

CREATE TABLE IF NOT EXISTS `method` (
  `id` bigint(20) NOT NULL AUTO_INCREMENT,
  `name` varchar(10) DEFAULT NULL,
  PRIMARY KEY (`id`),
  UNIQUE KEY `name` (`name`)
) ENGINE=MyISAM  DEFAULT CHARSET=latin1 AUTO_INCREMENT=2 ;

SEVERE: Duplicate entry 'GET' for key 'name'
Exception in thread "pool-11-thread-4" org.hibernate.exception.ConstraintViolationException: could not insert:

Body:
You can use @SqlInsert annotation on your entity, to change the sql hibernate uses to make insertion in Database, hibernate currently must be using this statement

insert into method(name, id) values (?,?)

If you are using mysql, you can use the @SqlInsert statement to change the insert sql by using insert ignore mysql statement

@SQLInsert(sql = "insert ignore into method(name, id) values (?,?)")

However you should get the insert sqls by enabling show sql mode in hibernate, since the order of the columns is generated via some logic, and their docs suggest this way.


问:
Replace in ColdFusion spoiling SQL query
I've got the below MySQL query, it's causing an error, the error is below too.

```<code>    SELECT DISTINCT s.id as id, s.auctioneer as auctioneer, s.advertType as advertType, s.saleType as saleType, an.name as auctioneerName, st.entryCopy as saleTypeName, at.entryCopy as advertTypeName, s.heading AS heading, sl.city AS city, sd.id AS sdId, sd.startDate AS startDate
    FROM    sales s LEFT JOIN saleloc sl ON sl.saleId = s.id LEFT JOIN saledates sd ON sd.saleLoc = sl.id,
            auctioneers an,
            lookupcopy st,
            lookupcopy at
    #replace(findWhere,"''","'","all")# AND
    s.id = sd.saleId AND sl.saleId = s.id
    AND an.id = s.auctioneer
    AND st.id = s.saleType
    AND at.id = s.advertType
    GROUP BY id
    ORDER BY startDate, auctioneerName, city
</code>```

Error from database

```<code>SELECT DISTINCT s.id as id, s.auctioneer as auctioneer, s.advertType as advertType, s.saleType as saleType, an.name as auctioneerName, st.entryCopy as saleTypeName, at.entryCopy as advertTypeName, s.heading AS heading, sl.city AS city, sd.id AS sdId, sd.startDate AS startDate
FROM sales s
LEFT JOIN saleloc sl ON sl.saleId = s.id
LEFT JOIN saledates sd ON sd.saleLoc = sl.id, auctioneers an, lookupcopy st, lookupcopy at
'WHERE s.advertType > 0
AND s.saleType > 0
AND sl.region = "2" '
AND s.id = sd.saleId
AND sl.saleId = s.id
AND an.id = s.auctioneer
AND st.id = s.saleType
AND at.id = s.advertType
GROUP BY id
ORDER BY startDate, auctioneerName, city
</code>```

I didn't write this code and I'm not sure why the #Replace()# is being used, can anyone see how to fix the syntax error it's causing?

答:
```<code>Before the query code, do a replace as follows:

<cfset findWhere = Replace(findWhere, "''", "'", "ALL")#
<cfif Left(findWhere, 1) EQ "'">
    <cfset findWhere = Right(findWhere, Len(findWhere) - 1)>
</cfif>
<cfif Right(findWhere, 1) EQ "'">
    <cfset findWhere = Left(findWhere, Len(findWhere) - 1)>
</cfif>

<cfquery name="qry" datasource="mysql">
SELECT DISTINCT s.id as id, s.auctioneer as auctioneer, s.advertType as advertType, s.saleType as saleType, an.name as auctioneerName, st.entryCopy as saleTypeName, at.entryCopy as advertTypeName, s.heading AS heading, sl.city AS city, sd.id AS sdId, sd.startDate AS startDate
FROM    sales s
LEFT JOIN saleloc sl ON sl.saleId = s.id
LEFT JOIN saledates sd ON sd.saleLoc = sl.id,
        auctioneers an,
        lookupcopy st,
        lookupcopy at
#findWhere# AND
s.id = sd.saleId AND sl.saleId = s.id
AND an.id = s.auctioneer
AND st.id = s.saleType
AND at.id = s.advertType
GROUP BY id
ORDER BY startDate, auctioneerName, city
</cfquery>
</code>```

Body:
I've got the below MySQL query, it's causing an error, the error is below too.

    SELECT DISTINCT s.id as id, s.auctioneer as auctioneer, s.advertType as advertType, s.saleType as saleType, an.name as auctioneerName, st.entryCopy as saleTypeName, at.entryCopy as advertTypeName, s.heading AS heading, sl.city AS city, sd.id AS sdId, sd.startDate AS startDate
    FROM    sales s LEFT JOIN saleloc sl ON sl.saleId = s.id LEFT JOIN saledates sd ON sd.saleLoc = sl.id,
            auctioneers an,
            lookupcopy st,
            lookupcopy at
    #replace(findWhere,"''","'","all")# AND
    s.id = sd.saleId AND sl.saleId = s.id
    AND an.id = s.auctioneer
    AND st.id = s.saleType
    AND at.id = s.advertType
    GROUP BY id
    ORDER BY startDate, auctioneerName, city

Error from database

SELECT DISTINCT s.id as id, s.auctioneer as auctioneer, s.advertType as advertType, s.saleType as saleType, an.name as auctioneerName, st.entryCopy as saleTypeName, at.entryCopy as advertTypeName, s.heading AS heading, sl.city AS city, sd.id AS sdId, sd.startDate AS startDate
FROM sales s
LEFT JOIN saleloc sl ON sl.saleId = s.id
LEFT JOIN saledates sd ON sd.saleLoc = sl.id, auctioneers an, lookupcopy st, lookupcopy at
'WHERE s.advertType > 0
AND s.saleType > 0
AND sl.region = "2" '
AND s.id = sd.saleId
AND sl.saleId = s.id
AND an.id = s.auctioneer
AND st.id = s.saleType
AND at.id = s.advertType
GROUP BY id
ORDER BY startDate, auctioneerName, city

I didn't write this code and I'm not sure why the #Replace()# is being used, can anyone see how to fix the syntax error it's causing?


问:
Query one table, to get name from another table
I have 3 tables in my database, Categories,Subcategories and Articles.
My Articles table contains columns caled CategoryID and SubcategoryID, which are foreign keys of the table Categories and Subcategories.

My question is, how can I get the name of the Category and Subcategory stored only as ID's in my Articles Table.

I think I need a kind of subquery or join.

Here is what I have:

```<code>SELECT ArticleTitle
      ,CategoryID
      ,SubcategoryID
  FROM Articles
 WHERE SubcategoryID =
        (SELECT SubcategoryName
           FROM Subcategories
          WHERE SubcategoryName = 'info'
         )
</code>```

When I execute this code in mysql, there are no erros, but I receive 0 results. All tables are containing some data.

答:
Using Joins :

SELECT a.ArticleTitle AS ArticleTitle,
c.CategoryName AS CategoryName,s.SubcategoryName AS SubcategoryName

FROM

Articles a JOIN Categories c on a.CategoryID=c.ID JOIN Subcategories s on a.SubcategoryID=s.ID

WHERE s.SubcategoryName = 'info';

Body:
I have 3 tables in my database, Categories,Subcategories and Articles.
My Articles table contains columns caled CategoryID and SubcategoryID, which are foreign keys of the table Categories and Subcategories.

My question is, how can I get the name of the Category and Subcategory stored only as ID's in my Articles Table.

I think I need a kind of subquery or join.

Here is what I have:

SELECT ArticleTitle
      ,CategoryID
      ,SubcategoryID
  FROM Articles
 WHERE SubcategoryID =
        (SELECT SubcategoryName
           FROM Subcategories
          WHERE SubcategoryName = 'info'
         )

When I execute this code in mysql, there are no erros, but I receive 0 results. All tables are containing some data.


问:
Bootstrap Modal in image not working in iOS
I'm having issues with the bootstrap modal not performing as it should on Safari and iOS. I've read similar issues in Stack Overflow, but couldn't find one with a problem using Modals in an image. Can somebody provide some insight and help please?

```<code><img alt="therapist" class="img-circle" data-target="#linda" data-toggle="modal" src="img/team/linda.png"> // modal opens when image is clicked
<h3 class="team--name" data-target="#linda" data-toggle="modal">Linda</h3>
<!-- Modal -->
<div aria-labelledby="myModalLabel" class="modal fade" id="linda" role="dialog" tabindex="-1">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <button aria-label="Close" class="close" data-dismiss="modal" type="button"><span aria-hidden="true">×</span></button>
                <h2 class="modal-title team--name" id="myModalLabel">Linda</h2>
                <h4 class="team--name">CAMTC</h4>
            </div>
            <div class="modal-body">
                <p>Linda brings compassion, positive energy and balance into her clients' lives</p>
            </div>
            <div class="modal-footer">
                <button class="btn btn-success" data-dismiss="modal" type="button">Close</button>
            </div>
        </div>
    </div>
</div>
</code>```

I have tried implementing the class below inside the image with no avail.

```<code>.clickable {
    cursor: pointer;
}
</code>```

答:
Case fixed.

I've added the following script to append modal to body.

```<code>$(document).ready(function () {
    $(".modal").appendTo("body");
});
</code>```

Body:
I'm having issues with the bootstrap modal not performing as it should on Safari and iOS. I've read similar issues in Stack Overflow, but couldn't find one with a problem using Modals in an image. Can somebody provide some insight and help please?

 // modal opens when image is clicked

Linda

                <button aria-label="Close" class="close" data-dismiss="modal" type="button">×</button>

Linda

CAMTC

Linda brings compassion, positive energy and balance into her clients' lives

                <button class="btn btn-success" data-dismiss="modal" type="button">Close</button>

I have tried implementing the class below inside the image with no avail.

.clickable {
    cursor: pointer;
}

Body:
Case fixed.

I've added the following script to append modal to body.

$(document).ready(function () {
    $(".modal").appendTo("body");
});


问:
Keeping emails synchronized between Firebase auth and database
I am using Firebase Web for a SaaS solution. My purpose is to have access to users' email at any time, either for sending notifications or triggering alerts from the backend.

For security reasons, Firebase auth does not allow to list users' email or to fetch emails based on user IDs. As a consequence, I keep a copy of the email into a specific collection in the Firebase database when a user account is created. The copy is made by a Cloud function that is triggered on user creation (following guidelines: https://firebase.google.com/docs/auth/extend-with-functions).

Thanks to the copy available in the Firebase database, I can access users' email. However, my issue is when a user changes his email.

Firebase auth provides the updateEmail function that returns a promise. I use this last to update the email in Firebase auth. Then, when the promise resolves I update the user email in the Firebase database. However, this has a major drawback: all the logic is performed on the client side and since both operations are not performed in a transaction if the client refreshes or closes his browser (or assume it crashes), then it is possible that Firebase auth is updated but not the Firebase database, thus leading to an inconsistent state.

I looked at the documentation, expecting the possibility to trigger a Cloud function when user auth information is updated. Unfortunately, I cannot find such a feature.

Another solution I thought about is to update the database from the Web client. Then, this last triggers a Cloud function that updates Firebase auth with the admin SDK. This last solution works but bypasses the check performed by updateEmail that ensures the new email is not used by another account. Also, the account hijacking protection performed by updateEmail is evicted, which is really bad from a security point of view.

Any idea to solve this problem properly is welcome.

答:
Here are a couple of options:

When calling updateEmail, update the email in your database first before calling updateEmail. THowever, if an error occurs, you need to catch it and undo that change in your db.

When a user wants to updateEmail, send their id token and new email to your server or firebase function http endpoint. There you verify the ID token with the admin SDK, then use the client SDK require('firebase'), using the uid from the ID token, admin.auth().createCustomToken(uid), then using client SDK, firebase.auth().signInWithCustomToken(customToken). You can then call user.updateEmail(newEmail) on the backend and save the email.

Always save the uid only and just use Admin SDK admin.auth().getUser(uid) to look up the user and get their email. This guarantees you get the user's latest email as you will not be able to catch the email revocation if the user chooses to do so.

No need to save anything. Use the CLI SDK to download all your users and their emails. Check https://firebase.google.com/docs/cli/auth#authexport
This is also better as you will always be able to get the latest email per user even if they revoke the email change.


问:
How do I stop after_create callback that interacts with an external API from being executed when running rspec tests?
I have a Rails model with an after_create callback, that has code which interacts with an external API. That code is getting executed and content on another app is being created when I run rspec tests.

I want to do something such as:

```<code>after_create :external_api_code, unless: testing?

def testing?
  #what goes here to recognize that the object is being created in a test?
end
</code>```

答:
One of possible solution may be to just stub the external_api_code in all tests and unstub it where its call is really needed. Of course this solution will work but it requires some monkey business because you have to place the stubbing code in all test files of your project. This is possible RSpec code to do it:

```<code>before(:all) do
    User.any_instance.stub(:external_api_code)
end
</code>```

like this in your model test case file.

Body:
I have a Rails model with an after_create callback, that has code which interacts with an external API. That code is getting executed and content on another app is being created when I run rspec tests.

I want to do something such as:

after_create :external_api_code, unless: testing?

def testing?
  #what goes here to recognize that the object is being created in a test?
end

Body:
One of possible solution may be to just stub the external_api_code in all tests and unstub it where its call is really needed. Of course this solution will work but it requires some monkey business because you have to place the stubbing code in all test files of your project. This is possible RSpec code to do it:

before(:all) do
    User.any_instance.stub(:external_api_code)
end

like this in your model test case file.