问:
Swinject inject self's property into new UIViewController
Let's pretend we have an UITableViewController that on didSelectRowAtSection loads an instance of a class named i.e.: ClassToInject and it wants to inject it through a property injection because our ViewControllerToBePushed has a property of ClassToInject, that subsequently (because it's an UITabBarViewController) on the didSet callback it searches for all its viewControllers property that conforms to ClassToInjectPresentable simple as:

```<code>protocol ClassToInjectPresentable {
  var property: ClassToInject { get set }
}
</code>```

Until now, i would just do something like this:

```<code>func didSelectRowAtIndexPath {
     let classToInject = self.loadClassToInjectFor(indexPath)
     let tabBarViewController = SomeTabBarViewController()
     tabBarViewController.property = classToInject
     self.navigationController.push(tabBarViewController, animated: true)
}
</code>```

And in SomeTabBarViewController ...

```<code>class SomeTabBarViewController: ClassToInjectPresentable {
  var property: ClassToInject? {
  didSet(newValue) {
      self.viewControllers.filter{ $0 is ClassToInjectPresentable }.map{ $0 as! ClassToInjectPresentable }.forEach{ $0.property = newValue }
  }
 }
</code>```

And everything should be get loaded nice and easy (but it's not). I've read about Swinject and this might be solved with it. I have seen lots of examples registering things like:

```<code>container.register(Animal.self) { _ in Cat(name: "Mimi") }
</code>```

But I don't know if I can register some property that is loaded in self:

```<code>container.register(ClassToInjectInjector.self) { _ in
self.loadClassToInjectFor(indexPath) }
// And then
container.register(ClassToInjectPresentable.self) { _ in
SomeTabBarViewController() }
    .initCompleted { r, p in
        let tabBar = p as! SomeTabBarViewController
        tabBar.property = r.resolve(ClassToInjectInjector.self)
        // And lastly?
        self.navigationController.pushViewController(tabBar, animated: true)
    }
}
</code>```

答:
It is difficult to recommend proper solution without knowing details of your application, but here are some suggestions:

```<code>container.register(ClassToInjectInjector.self) { _ in
    self.loadClassToInjectFor(indexPath)
}
</code>```

In general, all register-ations should be done outside of your objects. Common setup ishaving  one global Container, which contains all the registrations - you should look at them as instructions to build application objects without any implicit context. If your dependency needs to be created in the UITableViewController, you can pass it to resolve method as an argument:

```<code>container.register(ClassToInjectPresentable.self) { resolver, property in
    let tabBar = SomeTabBarViewController()
    tabBar.property = property
    return tabBar
}

// in UItableVIewController
container.resolve(ClassToInjectPresentable.self,
                  argument: self.loadClassToInjectFor(indexPath))
</code>```

Also this is usually a bad idea:

```<code>.initCompleted { r, p in
    ...
    self.navigationController.pushViewController(tabBar, animated: true)
 }
</code>```

You should not mix application logic with DI - use Swinject purely for constructing your dependencies.

So your UITableViewController might look something like this:

```<code>func didSelectRowAtIndexPath {
    let classToInject = self.loadClassToInjectFor(indexPath)
    let tabBar = container.resolve(
        SomeTabBarViewController.self, argument: loadClassToInjectFor(indexPath)
    )
    navigationController.push(tabBar, animated: true)
}
</code>```

As for your TabBar and its view controllers: how do the UIViewControllers get into TabBar? Is it possible to do something like this?

```<code>class SomeTabBarViewController {
    init(viewControllers: [UIViewController]) {
        ...
    }
}

container.register(SomeTabBarViewController.self) { r, property
    SomeTabBarViewController(viewControllers:[
        r.resolve(MyViewController.self, argument: property),
        r.resolve(MyViewController2.self, argument: property)
    ])
}
</code>```

Body:
Let's pretend we have an UITableViewController that on didSelectRowAtSection loads an instance of a class named i.e.: ClassToInject and it wants to inject it through a property injection because our ViewControllerToBePushed has a property of ClassToInject, that subsequently (because it's an UITabBarViewController) on the didSet callback it searches for all its viewControllers property that conforms to ClassToInjectPresentable simple as:

protocol ClassToInjectPresentable {
  var property: ClassToInject { get set }
}

Until now, i would just do something like this:

func didSelectRowAtIndexPath {
     let classToInject = self.loadClassToInjectFor(indexPath)
     let tabBarViewController = SomeTabBarViewController()
     tabBarViewController.property = classToInject
     self.navigationController.push(tabBarViewController, animated: true)
}

And in SomeTabBarViewController ...

class SomeTabBarViewController: ClassToInjectPresentable {
  var property: ClassToInject? {
  didSet(newValue) {
      self.viewControllers.filter{ $0 is ClassToInjectPresentable }.map{ $0 as! ClassToInjectPresentable }.forEach{ $0.property = newValue }
  }
 }

And everything should be get loaded nice and easy (but it's not). I've read about Swinject and this might be solved with it. I have seen lots of examples registering things like:

container.register(Animal.self) { _ in Cat(name: "Mimi") }

But I don't know if I can register some property that is loaded in self:

container.register(ClassToInjectInjector.self) { _ in
self.loadClassToInjectFor(indexPath) }
// And then
container.register(ClassToInjectPresentable.self) { _ in
SomeTabBarViewController() }
    .initCompleted { r, p in
        let tabBar = p as! SomeTabBarViewController
        tabBar.property = r.resolve(ClassToInjectInjector.self)
        // And lastly?
        self.navigationController.pushViewController(tabBar, animated: true)
    }
}

Body:
It is difficult to recommend proper solution without knowing details of your application, but here are some suggestions:

container.register(ClassToInjectInjector.self) { _ in
    self.loadClassToInjectFor(indexPath)
}

In general, all register-ations should be done outside of your objects. Common setup ishaving  one global Container, which contains all the registrations - you should look at them as instructions to build application objects without any implicit context. If your dependency needs to be created in the UITableViewController, you can pass it to resolve method as an argument:

container.register(ClassToInjectPresentable.self) { resolver, property in
    let tabBar = SomeTabBarViewController()
    tabBar.property = property
    return tabBar
}

// in UItableVIewController
container.resolve(ClassToInjectPresentable.self,
                  argument: self.loadClassToInjectFor(indexPath))

Also this is usually a bad idea:

.initCompleted { r, p in
    ...
    self.navigationController.pushViewController(tabBar, animated: true)
 }

You should not mix application logic with DI - use Swinject purely for constructing your dependencies.

So your UITableViewController might look something like this:

func didSelectRowAtIndexPath {
    let classToInject = self.loadClassToInjectFor(indexPath)
    let tabBar = container.resolve(
        SomeTabBarViewController.self, argument: loadClassToInjectFor(indexPath)
    )
    navigationController.push(tabBar, animated: true)
}

As for your TabBar and its view controllers: how do the UIViewControllers get into TabBar? Is it possible to do something like this?

class SomeTabBarViewController {
    init(viewControllers: [UIViewController]) {
        ...
    }
}

container.register(SomeTabBarViewController.self) { r, property
    SomeTabBarViewController(viewControllers:[
        r.resolve(MyViewController.self, argument: property),
        r.resolve(MyViewController2.self, argument: property)
    ])
}


来源: stackexchange

问:
Cross join left join count row
I have these tables:

Task Group table

id       name
 1        cooking
 2        baking

Task Status table

id       name
 1        open
 2        done?
 3        completed
 4        re-open
 5        suspend

Tasks table

project_id   task_group_id   task_status_id   task_name
 1             1               1               cooking martabak
 1             1               2               cooking sate kambing
 1             1               3               cooking nasi uduk
 1             1               4               cooking nasi goreng
 1             1               1               cooking martabak telor
 1             1               2               cooking sate ayam
 1             1               5               cooking nasi tutug oncom
 1             1               5               cooking nasi pera
 1             2               1               bake nastar
 1             2               2               bake bolu pisang
 1             2               3               bake bika ambon
 1             2               5               bake bolu kukus
 1             2               3               bake cheese stik
 1             2               1               bake bolu ketan
 1             2               5               bake papais
 1             2               1               bake boled

and the result that what i want is like this:

project      task_group       task_status      number
 Restaurant   Cooking          Completed        1
 Restaurant   Cooking          Done?            2
 Restaurant   Cooking          Open             2
 Restaurant   Cooking          Re-open          1
 Restaurant   Baking           Completed        2
 Restaurant   Baking           Done?            1
 Restaurant   Baking           Open             3
 Restaurant   Baking           Re-open          0

task status "suspend" is excluded

i have tried to cross join tasks table with task status table using subquery with where clause task_status.name in ('open', 'done?', 'completed', 're-open'), but i can't get the right count aggregation

答:
I think you can do something like this:</p>

```<code>SELECT
    project.name AS project,
    Task_Group.name as task_group ,
    Task_Status.name as task_status,
    COUNT(*) AS number
FROM
    Tasks
    JOIN Task_Group
        ON Tasks.task_group_id = Task_Group.id
    JOIN Task_Status
        ON Task.task_status_id=Task_Status.id
    JOIN project_table
        ON Task.project_id=project_table.project_id
WHERE
    Task_Status.Id IN(1,2,3,4)
GROUP BY
    project_table.name,
    Task_Group.name,
    Task_Status.name
</code>```

ContentLicense: CC BY-SA 3.0

Title: Cross join left join count row

Body:
I think you can do something like this:

SELECT
    project.name AS project,
    Task_Group.name as task_group ,
    Task_Status.name as task_status,
    COUNT(*) AS number
FROM
    Tasks
    JOIN Task_Group
        ON Tasks.task_group_id = Task_Group.id
    JOIN Task_Status
        ON Task.task_status_id=Task_Status.id
    JOIN project_table
        ON Task.project_id=project_table.project_id
WHERE
    Task_Status.Id IN(1,2,3,4)
GROUP BY
    project_table.name,
    Task_Group.name,
    Task_Status.name


问:
Angular 2 routes load different component based on type of parameter
I need to load different components based on the type of route parameter. if the route parameters is string then load one component like below,

{ path: 'care/action/:string',component: StringComponent},

if the route parameters is number then load another component like below

{ path: 'care/action/:number', component: NumberComponent},

Please note that URL will remain same, only type of parameter will change.

How to achieve this?

Thanks in advance.

答: You might want to leverage matcher property on your route configs and pass a matching function to it. Your matcher function would use regular expression to check if its a string (for string route) or number (for number).</p>


问:
Read a file out of an android application
I need to place a file on a specific folder, so that my application can read it. First i want to try to create a new file with a specific path, but anyway i try, on the android dev tool on eclipse, I have an IOException.
Do you know a way to create "helloworld.txt"  - For example - on the virtual device?

Thanks.

PS: I tried "new File(Environment.get..., "helloworld.txt").mkdirs();", and stuffs like that

答:
If you want to create a file in the sdcard, you should check if the sdcard is ready (more info here), apart from the fact you need this permission in the AndroidManifest.xml

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

Try not use hard-code the path of the sdcard, use instead the API for that.

On the other hand, if you want to create a private file on the phone storage you can use this methods:

```<code>FileOutputStream fos = context.openFileOutput(FILE_NAME, Context.MODE_PRIVATE);
</code>```

ContentLicense: CC BY-SA 2.5

Body:
If you want to create a file in the sdcard, you should check if the sdcard is ready (more info here), apart from the fact you need this permission in the AndroidManifest.xml

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

Try not use hard-code the path of the sdcard, use instead the API for that.

On the other hand, if you want to create a private file on the phone storage you can use this methods:

FileOutputStream fos = context.openFileOutput(FILE_NAME, Context.MODE_PRIVATE);


问:
Pass table as parameter into sql server UDF
I'd like to pass a table as a parameter into a scaler UDF.

I'd also prefer to restrict the parameter to tables with only one column. (optional)

Is this possible?

EDIT

I don't want to pass a table name, I'd like to pass the table of data (as a reference I presume)

EDIT

I would want my Scaler UDF to basically take a table of values and return a CSV list of the rows.

IE

```<code>col1
"My First Value"
"My Second Value"
...
"My nth Value"
</code>```

would return

```<code>"My First Value, My Second Value,... My nth Value"
</code>```

I'd like to do some filtering on the table though, IE ensuring that there are no nulls and to ensure there are no duplicates. I was expecting something along the lines of:

```<code>SELECT dbo.MyFunction(SELECT DISTINCT myDate FROM myTable WHERE myDate IS NOT NULL)
</code>```

答:
you can do something like this

/* CREATE USER DEFINED TABLE TYPE */

```<code>CREATE TYPE StateMaster AS TABLE
(
 StateCode VARCHAR(2),
 StateDescp VARCHAR(250)
)
GO
</code>```

/*CREATE  FUNCTION WHICH TAKES TABLE AS A PARAMETER  */

```<code>CREATE FUNCTION TableValuedParameterExample(@TmpTable StateMaster READONLY)
RETURNS  VARCHAR(250)
AS
BEGIN
 DECLARE @StateDescp VARCHAR(250)
 SELECT @StateDescp = StateDescp FROM @TmpTable
 RETURN @StateDescp
END
GO
</code>```

/*CREATE  STORED PROCEDURE WHICH TAKES TABLE AS A PARAMETER  */

```<code>CREATE PROCEDURE TableValuedParameterExample_SP
(
@TmpTable StateMaster READONLY
)
AS
BEGIN
 INSERT INTO StateMst
  SELECT * FROM @TmpTable
END
GO

BEGIN
/* DECLARE VARIABLE OF TABLE USER DEFINED TYPE */
DECLARE @MyTable StateMaster

/* INSERT DATA INTO TABLE TYPE */
INSERT INTO @MyTable VALUES('11','AndhraPradesh')
INSERT INTO @MyTable VALUES('12','Assam')

/* EXECUTE STORED PROCEDURE */
EXEC TableValuedParameterExample_SP @MyTable
GO
</code>```

For more details check this link: http://sailajareddy-technical.blogspot.in/2012/09/passing-table-valued-parameter-to.html

Body:
I'd like to pass a table as a parameter into a scaler UDF.

I'd also prefer to restrict the parameter to tables with only one column. (optional)

Is this possible?

EDIT

I don't want to pass a table name, I'd like to pass the table of data (as a reference I presume)

EDIT

I would want my Scaler UDF to basically take a table of values and return a CSV list of the rows.

IE

col1
"My First Value"
"My Second Value"
...
"My nth Value"

would return

"My First Value, My Second Value,... My nth Value"

I'd like to do some filtering on the table though, IE ensuring that there are no nulls and to ensure there are no duplicates. I was expecting something along the lines of:

SELECT dbo.MyFunction(SELECT DISTINCT myDate FROM myTable WHERE myDate IS NOT NULL)

Body:
you can do something like this

/* CREATE USER DEFINED TABLE TYPE */

CREATE TYPE StateMaster AS TABLE
(
 StateCode VARCHAR(2),
 StateDescp VARCHAR(250)
)
GO

/*CREATE  FUNCTION WHICH TAKES TABLE AS A PARAMETER  */

CREATE FUNCTION TableValuedParameterExample(@TmpTable StateMaster READONLY)
RETURNS  VARCHAR(250)
AS
BEGIN
 DECLARE @StateDescp VARCHAR(250)
 SELECT @StateDescp = StateDescp FROM @TmpTable
 RETURN @StateDescp
END
GO

/*CREATE  STORED PROCEDURE WHICH TAKES TABLE AS A PARAMETER  */

CREATE PROCEDURE TableValuedParameterExample_SP
(
@TmpTable StateMaster READONLY
)
AS
BEGIN
 INSERT INTO StateMst
  SELECT * FROM @TmpTable
END
GO

BEGIN
/* DECLARE VARIABLE OF TABLE USER DEFINED TYPE */
DECLARE @MyTable StateMaster

/* INSERT DATA INTO TABLE TYPE */
INSERT INTO @MyTable VALUES('11','AndhraPradesh')
INSERT INTO @MyTable VALUES('12','Assam')

/* EXECUTE STORED PROCEDURE */
EXEC TableValuedParameterExample_SP @MyTable
GO

For more details check this link: http://sailajareddy-technical.blogspot.in/2012/09/passing-table-valued-parameter-to.html


问:
Keep user input after press input type="submit" without using JQuery or Ajax
i'm creating a python web application which get multiple user input from input type="number" and calculation will be done when input type="submit" is pressed. I managed to do it but it appears that input that user entered earlier disappear because the page refresh when submitted. Can anyone help me how to keep the user input even after input type="submit" is pressed.

This is my python script:

```<code>from flask import Flask, render_template, request
import math

app = Flask(__name__, template_folder='C:\\Users\\iyzadsyammil\\.PyCharmCE2017.1\\config\\fileTemplates')

@app.route('/')
def index():
    return render_template('index.html')

@app.route('/Menu')
def showmenu():
    return render_template('index.html')

@app.route('/App',methods=['GET', 'POST'])
def showapp():
    outpb=0
    x=0
    logpb=0
    error=" "

    if request.method=='POST':
        ingor = request.form['inGOR']
        inog = request.form['inOG']
        ingg = request.form['inGG']
        inws = request.form['inWS']
        intemp = request.form['inT']
        inpress = request.form['inP']
        innc = request.form['inNC']
        cor1 = request.form['cor1']
        cor2 = request.form['cor2']
        cor3 = request.form['cor3']
        cor4 = request.form['cor4']

        ingor = float(ingor)
        inog = float(inog)
        ingg = float(ingg)
        inws = float(inws)
        intemp = float(intemp)
        inpress = float(inpress)
        innc = float(innc)

        try:
            if cor1 == "VB":
                if inog <= 30:
                    outpb = ((27.64*ingor/ingg)*10**((-11.172*inog)/(intemp+460)))**(1/1.0937)
                else:
                    outpb = ((56.06*ingor/ingg)*10**((-10.393*inog)/(intemp+460)))**(1/1.187)
            elif cor1 == "AM":
                outpb = 0.00538088*ingor**0.715082*ingg**-1.87784*(141.5/(inog+131.5))**3.1437*(intemp+460)**1.32657
            elif cor1 == "G":
                x = (ingor/ingg)**0.816*((intemp**0.172)/(inog**0.989))
                logpb = 1.7669 + 1.7447 * math.log10(x) - (0.30218*(math.log10(x)**2))
                outpb = 10**logpb
            elif cor1 == "PF":
                x = 7.916*(10**-4)*inog**1.541-(4.561*(10**-5)*intemp**1.3911)
                outpb = ((112.727*ingor**0.577421)/(ingg**0.8439*10**x))-1391.051
            elif cor1 == "S":
                outpb = 18.2*((ingor/ingg)**0.83*10**(0.00091*intemp-0.0125*inog)-1.4)
            else:
                outpb = "Invalid Correlation!!"
        except ValueError:
            error = "Please enter an appropriate value!"

    return render_template('app.html',error=error,outpb=outpb)

if __name__ == "__main__":
    app.run(debug=True)
</code>```

This is my current html page :

<!DOCTYPE html>

    <title>Testing Program</title>

    <link href="http://getbootstrap.com/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="http://getbootstrap.com/examples/jumbotron-narrow/jumbotron-narrow.css" rel="stylesheet">

Home

App

Log In

Sign Up

Experiment

WELCOME!!

            <form method="POST" class="col-lg-6" >

PVT Application

Input Data

Solution GOR(Rs) 	<input type="number" step="any" name="inGOR">	scf/bbl

Oil Gravity 	<input type="number" step="any" name="inOG">	API

Gas Gravity 	<input type="number" step="any" name="inGG">	gr/cc

Water Salinity 	<input type="number" step="any" name="inWS">	ppm

Temperature 	<input type="number" step="any" name="inT">	◦F

Pressure 	<input type="number" step="any" name="inP">	Psia

Nitrogen Content 	<input type="number" step="any" name="inNC">	%mol

Correlation

                        Bubble Point Pressure(Pb)

                            <select name="cor1">
                                <option value="none"></option>
                                <option value="VB">Vasquez and beggs</option>
                                <option value="AM">Al-Marhoun</option>
                                <option value="G">Glaso</option>
                                <option value="PF">Petrosky and Farshad</option>
                                <option value="S">Standing</option>
                            </select>

                        Solution GOR(Rs)

                            <select name="cor2">
                                <option value=" "></option>
                                <option value="VB">Vasquez and beggs</option>
                                <option value="AM">Al-Marhoun</option>
                                <option value="G">Glaso</option>
                                <option value="PF">Petrosky and Farshad</option>
                                <option value="S">Standing</option>
                            </select>

                        Oil Formation Volume Factor(Bo)

                            <select name="cor3">
                                <option value=" "></option>
                                <option value="VB">Vasquez and beggs</option>
                                <option value="AM">Al-Marhoun</option>
                                <option value="G">Glaso</option>
                                <option value="PF">Petrosky and Farshad</option>
                                <option value="S">Standing</option>
                            </select>

                        Viscosity(µo)

                            <select name="cor4">
                                <option value=" "></option>
                                <option value="CC">Chew Connally</option>
                                <option value="BR">Beggs Robinson</option>
                            </select>

                        <input type="submit" value="Calculate">

Result

Pb	{{outpb}}

Rs(Solution GOR)

Corrected Pb(Nitrogen Effect)

Bo

Co

µo

答:
No jQuery, no Ajax. but obviously you need some JS.

```<code><input id="number" type="number" value="num">
<input id="submit" type="submit" value="submit">

document.getElementById("submit").addEventListener("click", function(){
  var val = document.getElementById("number").value
  sessionStorage.setItem("number", val);
});

window.onload = function() {
  var session_value = sessionStorage.getItem("number") || 0;
  document.getElementById("number").value = session_value;
}
</code>```

If you give some clues that how do you use python (db interaction, templating etc.) another solutions might be considered.

sessionStorage

Body:
i'm creating a python web application which get multiple user input from input type="number" and calculation will be done when input type="submit" is pressed. I managed to do it but it appears that input that user entered earlier disappear because the page refresh when submitted. Can anyone help me how to keep the user input even after input type="submit" is pressed.

This is my python script:

from flask import Flask, render_template, request
import math

app = Flask(__name__, template_folder='C:\\Users\\iyzadsyammil\\.PyCharmCE2017.1\\config\\fileTemplates')

@app.route('/')
def index():
    return render_template('index.html')

@app.route('/Menu')
def showmenu():
    return render_template('index.html')

@app.route('/App',methods=['GET', 'POST'])
def showapp():
    outpb=0
    x=0
    logpb=0
    error=" "

    if request.method=='POST':
        ingor = request.form['inGOR']
        inog = request.form['inOG']
        ingg = request.form['inGG']
        inws = request.form['inWS']
        intemp = request.form['inT']
        inpress = request.form['inP']
        innc = request.form['inNC']
        cor1 = request.form['cor1']
        cor2 = request.form['cor2']
        cor3 = request.form['cor3']
        cor4 = request.form['cor4']

        ingor = float(ingor)
        inog = float(inog)
        ingg = float(ingg)
        inws = float(inws)
        intemp = float(intemp)
        inpress = float(inpress)
        innc = float(innc)

        try:
            if cor1 == "VB":
                if inog <= 30:
                    outpb = ((27.64*ingor/ingg)*10**((-11.172*inog)/(intemp+460)))**(1/1.0937)
                else:
                    outpb = ((56.06*ingor/ingg)*10**((-10.393*inog)/(intemp+460)))**(1/1.187)
            elif cor1 == "AM":
                outpb = 0.00538088*ingor**0.715082*ingg**-1.87784*(141.5/(inog+131.5))**3.1437*(intemp+460)**1.32657
            elif cor1 == "G":
                x = (ingor/ingg)**0.816*((intemp**0.172)/(inog**0.989))
                logpb = 1.7669 + 1.7447 * math.log10(x) - (0.30218*(math.log10(x)**2))
                outpb = 10**logpb
            elif cor1 == "PF":
                x = 7.916*(10**-4)*inog**1.541-(4.561*(10**-5)*intemp**1.3911)
                outpb = ((112.727*ingor**0.577421)/(ingg**0.8439*10**x))-1391.051
            elif cor1 == "S":
                outpb = 18.2*((ingor/ingg)**0.83*10**(0.00091*intemp-0.0125*inog)-1.4)
            else:
                outpb = "Invalid Correlation!!"
        except ValueError:
            error = "Please enter an appropriate value!"

    return render_template('app.html',error=error,outpb=outpb)

if __name__ == "__main__":
    app.run(debug=True)

This is my current html page :

<!DOCTYPE html>

    <title>Testing Program</title>

    <link href="http://getbootstrap.com/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="http://getbootstrap.com/examples/jumbotron-narrow/jumbotron-narrow.css" rel="stylesheet">

Home

App

Log In

Sign Up

Experiment

WELCOME!!

            <form method="POST" class="col-lg-6" >

PVT Application

Input Data

Solution GOR(Rs) 	<input type="number" step="any" name="inGOR">	scf/bbl

Oil Gravity 	<input type="number" step="any" name="inOG">	API

Gas Gravity 	<input type="number" step="any" name="inGG">	gr/cc

Water Salinity 	<input type="number" step="any" name="inWS">	ppm

Temperature 	<input type="number" step="any" name="inT">	◦F

Pressure 	<input type="number" step="any" name="inP">	Psia

Nitrogen Content 	<input type="number" step="any" name="inNC">	%mol

Correlation

                        Bubble Point Pressure(Pb)

                            <select name="cor1">
                                <option value="none"></option>
                                <option value="VB">Vasquez and beggs</option>
                                <option value="AM">Al-Marhoun</option>
                                <option value="G">Glaso</option>
                                <option value="PF">Petrosky and Farshad</option>
                                <option value="S">Standing</option>
                            </select>

                        Solution GOR(Rs)

                            <select name="cor2">
                                <option value=" "></option>
                                <option value="VB">Vasquez and beggs</option>
                                <option value="AM">Al-Marhoun</option>
                                <option value="G">Glaso</option>
                                <option value="PF">Petrosky and Farshad</option>
                                <option value="S">Standing</option>
                            </select>

                        Oil Formation Volume Factor(Bo)

                            <select name="cor3">
                                <option value=" "></option>
                                <option value="VB">Vasquez and beggs</option>
                                <option value="AM">Al-Marhoun</option>
                                <option value="G">Glaso</option>
                                <option value="PF">Petrosky and Farshad</option>
                                <option value="S">Standing</option>
                            </select>

                        Viscosity(µo)

                            <select name="cor4">
                                <option value=" "></option>
                                <option value="CC">Chew Connally</option>
                                <option value="BR">Beggs Robinson</option>
                            </select>

                        <input type="submit" value="Calculate">

Result

Pb	{{outpb}}

Rs(Solution GOR)

Corrected Pb(Nitrogen Effect)

Bo

Co

µo

Body:
No jQuery, no Ajax. but obviously you need some JS.

<input id="number" type="number" value="num">
<input id="submit" type="submit" value="submit">

document.getElementById("submit").addEventListener("click", function(){
  var val = document.getElementById("number").value
  sessionStorage.setItem("number", val);
});

window.onload = function() {
  var session_value = sessionStorage.getItem("number") || 0;
  document.getElementById("number").value = session_value;
}

If you give some clues that how do you use python (db interaction, templating etc.) another solutions might be considered.

sessionStorage


问:
Check multiple checkbox in asp net, bootstrap
I have found some answers about checking checkboxes in group but even if i copy this to mine side it wont works.
I have easy example of checkbox group.
Could any one explain me what am i doing wrong?

var options = [];

$('.dropdown-menu a').on('click', function(event) {

  var $target = $(event.currentTarget),
    val = $target.attr('data-value'),
    $inp = $target.find('input'),
    idx;

  if ((idx = options.indexOf(val)) > -1) {
    options.splice(idx, 1);
    setTimeout(function() {
      $inp.prop('checked', false)
    }, 0);
  } else {
    options.push(val);
    setTimeout(function() {
      $inp.prop('checked', true)
    }, 0);
  }

  $(event.target).blur();

  console.log(options);
  return false;
});

$("#checkAll").click(function() {
  $(".check").prop('checked', $(this).prop('checked'));
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js">
</script>

<div class="btn-group btn-group-sm">
  <input id="btnZatwierdz" class="btn btn-default btn-sm dropdown-toggle" type="submit" value="Filtruj" aria-haspopup="true" aria-expanded="false" onserverclick="btnZatwierdzClick" runat="server"></input>
  <button type="button" class="btn btn-default btn-sm dropdown-toggle" data-toggle="dropdown">
    <span class="glyphicon glyphicon-cog"></span>
    <span class="caret"></span>
  </button>
  <ul class="dropdown-menu">
    <li>

        <input id="CheckboxHunting" type="checkbox" runat="server" />
        Hunting

    </li>
    <li>

        <input id="CheckboxFarming" type="checkbox" runat="server" />
        Farming

    </li>
    <li class="dropdown-submenu">

        <input id="checkAll" type="checkbox" />
        Hunting

      <ul class="dropdown-menu">
        <li>

            <input id="Checkbox2" name="checkbox-2" type="checkbox" runat="server" />
            Hunting

        </li>
        <li>

            <input id="Checkbox3" name="checkbox-3" type="checkbox" runat="server" />
            Farming

        </li>
      </ul>
    </li>
  </ul>
</div></code>```

答:
Try with this

```<code>$("#checkAll").click(function() {
  $(this).closest("li").find("input[id^='Checkbox']").prop('checked', $(this).prop('checked'));
});
</code>```

This will take the closest li of $("#checkAll") and then find all inputs that starts with Checkbox (id^='Checkbox')

var options = [];

$('.dropdown-menu a').on('click', function(event) {

  var $target = $(event.currentTarget),
    val = $target.attr('data-value'),
    $inp = $target.find('input'),
    idx;

  if ((idx = options.indexOf(val)) > -1) {
    options.splice(idx, 1);
    setTimeout(function() {
      $inp.prop('checked', false)
    }, 0);
  } else {
    options.push(val);
    setTimeout(function() {
      $inp.prop('checked', true)
    }, 0);
  }

  $(event.target).blur();

  console.log(options);
  return false;
});

$("#checkAll").click(function() {
  $(this).closest("li").find("input[id^='Checkbox']").prop('checked', $(this).prop('checked'));
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js">
</script>

<div class="btn-group btn-group-sm">
  <input id="btnZatwierdz" class="btn btn-default btn-sm dropdown-toggle" type="submit" value="Filtruj" aria-haspopup="true" aria-expanded="false" onserverclick="btnZatwierdzClick" runat="server"></input>
  <button type="button" class="btn btn-default btn-sm dropdown-toggle" data-toggle="dropdown">
    <span class="glyphicon glyphicon-cog"></span>
    <span class="caret"></span>
  </button>
  <ul class="dropdown-menu">
    <li>

        <input id="CheckboxHunting" type="checkbox" runat="server" />  Hunting

    </li>
    <li>

        <input id="CheckboxFarming" type="checkbox" runat="server" />  Farming

    </li>
    <li class="dropdown-submenu">

        <input id="checkAll" type="checkbox" />  Hunting

      <ul class="dropdown-menu">
        <li>

            <input id="Checkbox2" name="checkbox-2" type="checkbox" runat="server" />  Hunting

        </li>
        <li>

            <input id="Checkbox3" name="checkbox-3" type="checkbox" runat="server" />  Farming

        </li>
      </ul>
    </li>
  </ul>
</div></code>```

Body:
I have found some answers about checking checkboxes in group but even if i copy this to mine side it wont works.
I have easy example of checkbox group.
Could any one explain me what am i doing wrong?

var options = [];

$('.dropdown-menu a').on('click', function(event) {

  var $target = $(event.currentTarget),
    val = $target.attr('data-value'),
    $inp = $target.find('input'),
    idx;

  if ((idx = options.indexOf(val)) > -1) {
    options.splice(idx, 1);
    setTimeout(function() {
      $inp.prop('checked', false)
    }, 0);
  } else {
    options.push(val);
    setTimeout(function() {
      $inp.prop('checked', true)
    }, 0);
  }

  $(event.target).blur();

  console.log(options);
  return false;
});

$("#checkAll").click(function() {
  $(".check").prop('checked', $(this).prop('checked'));
});

  <input id="btnZatwierdz" class="btn btn-default btn-sm dropdown-toggle" type="submit" value="Filtruj" aria-haspopup="true" aria-expanded="false" onserverclick="btnZatwierdzClick" runat="server"></input>
  <button type="button" class="btn btn-default btn-sm dropdown-toggle" data-toggle="dropdown">

  </button>

        <input id="CheckboxHunting" type="checkbox" runat="server" />
        Hunting

        <input id="CheckboxFarming" type="checkbox" runat="server" />
        Farming

        <input id="checkAll" type="checkbox" />
        Hunting

            <input id="Checkbox2" name="checkbox-2" type="checkbox" runat="server" />
            Hunting

            <input id="Checkbox3" name="checkbox-3" type="checkbox" runat="server" />
            Farming

Body:
Try with this

$("#checkAll").click(function() {
  $(this).closest("li").find("input[id^='Checkbox']").prop('checked', $(this).prop('checked'));
});

This will take the closest li of $("#checkAll") and then find all inputs that starts with Checkbox (id^='Checkbox')

var options = [];

$('.dropdown-menu a').on('click', function(event) {

  var $target = $(event.currentTarget),
    val = $target.attr('data-value'),
    $inp = $target.find('input'),
    idx;

  if ((idx = options.indexOf(val)) > -1) {
    options.splice(idx, 1);
    setTimeout(function() {
      $inp.prop('checked', false)
    }, 0);
  } else {
    options.push(val);
    setTimeout(function() {
      $inp.prop('checked', true)
    }, 0);
  }

  $(event.target).blur();

  console.log(options);
  return false;
});

$("#checkAll").click(function() {
  $(this).closest("li").find("input[id^='Checkbox']").prop('checked', $(this).prop('checked'));
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js">
</script>

<div class="btn-group btn-group-sm">
  <input id="btnZatwierdz" class="btn btn-default btn-sm dropdown-toggle" type="submit" value="Filtruj" aria-haspopup="true" aria-expanded="false" onserverclick="btnZatwierdzClick" runat="server"></input>
  <button type="button" class="btn btn-default btn-sm dropdown-toggle" data-toggle="dropdown">
    <span class="glyphicon glyphicon-cog"></span>
    <span class="caret"></span>
  </button>
  <ul class="dropdown-menu">
    <li>
      <a href="#" class="small" data-value="option1" tabindex="-1">
        <input id="CheckboxHunting" type="checkbox" runat="server" />&nbsp; Hunting
      </a>
    </li>
    <li>
      <a href="#" class="small" data-value="option2" tabindex="-1">
        <input id="CheckboxFarming" type="checkbox" runat="server" />&nbsp; Farming
      </a>
    </li>
    <li class="dropdown-submenu">
      <a href="#" class="small" data-value="option1" tabindex="-1">
        <input id="checkAll" type="checkbox" />&nbsp; Hunting
      </a>
      <ul class="dropdown-menu">
        <li>
          <a href="#" class="check" data-value="option1" tabindex="-1">
            <input id="Checkbox2" name="checkbox-2" type="checkbox" runat="server" />&nbsp; Hunting
          </a>
        </li>
        <li>
          <a href="#" class="check" data-value="option2" tabindex="-1">
            <input id="Checkbox3" name="checkbox-3" type="checkbox" runat="server" />&nbsp; Farming
          </a>
        </li>
      </ul>
    </li>
  </ul>
</div>


问:
Zend findDependentRowset An error occurred
I have three two classess

```<code>class Application_Model_Accounts extends Zend_Db_Table_Abstract
{
    protected $_name            = 'accounts';
    protected $_dependentTables = array('Application_Model_Bugs');
}
</code>```

And

```<code>class Application_Model_Bugs extends Zend_Db_Table_Abstract
{
    protected $_name            = 'bugs';

    protected $_dependentTables = array('Application_Model_BugsProducts');

    protected $_referenceMap    = array(
        'Reporter' => array(
            'columns'           => 'reported_by',
            'refTableClass'     => 'Application_Model_Accounts',
            'refColumns'        => 'account_name'
        ),
        'Engineer' => array(
            'columns'           => 'assigned_to',
            'refTableClass'     => 'Application_Model_Accounts',
            'refColumns'        => 'account_name'
        ),
        'Verifier' => array(
            'columns'           => array('verified_by'),
            'refTableClass'     => 'Application_Model_Accounts',
            'refColumns'        => array('account_name')
        )
    );

}
</code>```

in index controll i am trying to run this code.

```<code>public function indexAction()
    {

      $accountsTable = new Application_Model_Accounts();
      $accountsRowset = $accountsTable->find(1234);
      $user1234 = $accountsRowset->current();
      $bugsReportedByUser = $user1234->findDependentRowset('Application_Model_Bugs');
}
</code>```

and on line

```<code>$bugsReportedByUser = $user1234->findDependentRowset('Application_Model_Bugs');
</code>```

I am getting this error

```<code>An error occurred
Application error
</code>```

I am unable to findout the problem. How to fix this problem. and is there a way to get more developer friendly error in Zend rather then just getting this message "An error occured".

答:
I figure out the solution for this problem.
in .Htaccess file
enable the development mode by adding this line on top

```<code>SetEnv APPLICATION_ENV "development"
</code>```

This will show the complete error trace.
Sorted

full working example of bugs code including db available here
http://phphints.wordpress.com/2010/06/25/zend-framework-finddependentrowset-and-findparentrow-demo/

Body:
I have three two classess

class Application_Model_Accounts extends Zend_Db_Table_Abstract
{
    protected $_name            = 'accounts';
    protected $_dependentTables = array('Application_Model_Bugs');
}

And

class Application_Model_Bugs extends Zend_Db_Table_Abstract
{
    protected $_name            = 'bugs';

    protected $_dependentTables = array('Application_Model_BugsProducts');

    protected $_referenceMap    = array(
        'Reporter' => array(
            'columns'           => 'reported_by',
            'refTableClass'     => 'Application_Model_Accounts',
            'refColumns'        => 'account_name'
        ),
        'Engineer' => array(
            'columns'           => 'assigned_to',
            'refTableClass'     => 'Application_Model_Accounts',
            'refColumns'        => 'account_name'
        ),
        'Verifier' => array(
            'columns'           => array('verified_by'),
            'refTableClass'     => 'Application_Model_Accounts',
            'refColumns'        => array('account_name')
        )
    );

}

in index controll i am trying to run this code.

public function indexAction()
    {

      $accountsTable = new Application_Model_Accounts();
      $accountsRowset = $accountsTable->find(1234);
      $user1234 = $accountsRowset->current();
      $bugsReportedByUser = $user1234->findDependentRowset('Application_Model_Bugs');
}

and on line

$bugsReportedByUser = $user1234->findDependentRowset('Application_Model_Bugs');

I am getting this error

An error occurred
Application error

I am unable to findout the problem. How to fix this problem. and is there a way to get more developer friendly error in Zend rather then just getting this message "An error occured".

Body:
I figure out the solution for this problem.
in .Htaccess file
enable the development mode by adding this line on top

SetEnv APPLICATION_ENV "development"

This will show the complete error trace.
Sorted

full working example of bugs code including db available here
http://phphints.wordpress.com/2010/06/25/zend-framework-finddependentrowset-and-findparentrow-demo/


问:
UIActivityViewController not showing body text in gmail
I'm using uiactivityviewcontroller for showing sharing option. Everything working except when user selects the Gmail sharing option. If user chooses email then it shows the content properly. But if i choose gmail then nothing is displayed in the body text.

Here is the code:

```<code> NSString *str = [NSString stringWithFormat:@"%@",@"Check the application"];
 NSArray* dataToShare = @[str];  // ...or whatever pieces of data you want to share.

UIActivityViewController* activityViewController = [[UIActivityViewController alloc] initWithActivityItems:dataToShare applicationActivities:nil];
[activityViewController setValue:@"Check it out" forKey:@"subject"];

if(SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(@"8.0")) {
    activityViewController.popoverPresentationController.sourceView = self.view;
    activityViewController.popoverPresentationController.sourceRect = CGRectMake(0,self.view.frame.size.height, self.view.frame.size.width, 400);

}

[self presentViewController:activityViewController animated:YES completion:nil];

[activityViewController setCompletionHandler:^(NSString *activityType, BOOL completed) {
    if(completed){

    }
}];
}

- (NSString *)activityViewController:(UIActivityViewController *)activityViewController subjectForActivityType:(NSString *)activityType{
    return @"Check it out";
}
</code>```

答:
It's a bit tricky in Swift 3 and iOS 9+.

First, you need to add googlegmail to LSApplicationQueriesSchemes in Info.plist

Second, here's how my UIActivity subclass looks like:

It's a bit tricky in Swift 3 and iOS 9+.

First, you need to add googlegmail to LSApplicationQueriesSchemes in Info.plist

Second, here's how my UIActivity subclass looks like:

```<code>final class GmailNewEmailShareActivity: UIActivity {

    private let urlScheme = "googlegmail:"
    private var activityItems: [Any]? = nil

    override class var activityCategory: UIActivityCategory {
        return .share
    }

    override var activityType: UIActivityType? {
        return UIActivityType(rawValue: "googlemail")
    }

    override var activityTitle: String? {
        return "Gmail"
    }

    override var activityViewController: UIViewController? {
        return nil
    }

    override func canPerform(withActivityItems activityItems: [Any]) -> Bool {
        guard let url = URL(string: urlScheme) else {
            return false
        }
        return UIApplication.shared.canOpenURL(url)
    }

    override func prepare(withActivityItems activityItems: [Any]) {
        // At this point I store incoming activity items to use them later in `perform()`
        self.activityItems = activityItems
    }

    override var activityImage: UIImage? {
        // 60x60, 120x120 and 180x180
        return nil
    }

    override func perform() {
        guard let body = activityItems?.first as? String, let encodedBody = body.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed) else {
            activityDidFinish(false)
            return
        }
        let urlString = "\(urlScheme)///co?body=\(encodedBody)"
        guard let url = URL(string: urlString) else {
            activityDidFinish(false)
            return
        }
        UIApplication.shared.openURL(url)
        activityDidFinish(true)
    }

}
</code>```

Body:
I'm using uiactivityviewcontroller for showing sharing option. Everything working except when user selects the Gmail sharing option. If user chooses email then it shows the content properly. But if i choose gmail then nothing is displayed in the body text.

Here is the code:

 NSString *str = [NSString stringWithFormat:@"%@",@"Check the application"];
 NSArray* dataToShare = @[str];  // ...or whatever pieces of data you want to share.

UIActivityViewController* activityViewController = [[UIActivityViewController alloc] initWithActivityItems:dataToShare applicationActivities:nil];
[activityViewController setValue:@"Check it out" forKey:@"subject"];

if(SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(@"8.0")) {
    activityViewController.popoverPresentationController.sourceView = self.view;
    activityViewController.popoverPresentationController.sourceRect = CGRectMake(0,self.view.frame.size.height, self.view.frame.size.width, 400);

}

[self presentViewController:activityViewController animated:YES completion:nil];

[activityViewController setCompletionHandler:^(NSString *activityType, BOOL completed) {
    if(completed){

    }
}];
}

- (NSString *)activityViewController:(UIActivityViewController *)activityViewController subjectForActivityType:(NSString *)activityType{
    return @"Check it out";
}

Body:
It's a bit tricky in Swift 3 and iOS 9+.

First, you need to add googlegmail to LSApplicationQueriesSchemes in Info.plist

Second, here's how my UIActivity subclass looks like:

It's a bit tricky in Swift 3 and iOS 9+.

First, you need to add googlegmail to LSApplicationQueriesSchemes in Info.plist

Second, here's how my UIActivity subclass looks like:

final class GmailNewEmailShareActivity: UIActivity {

    private let urlScheme = "googlegmail:"
    private var activityItems: [Any]? = nil

    override class var activityCategory: UIActivityCategory {
        return .share
    }

    override var activityType: UIActivityType? {
        return UIActivityType(rawValue: "googlemail")
    }

    override var activityTitle: String? {
        return "Gmail"
    }

    override var activityViewController: UIViewController? {
        return nil
    }

    override func canPerform(withActivityItems activityItems: [Any]) -> Bool {
        guard let url = URL(string: urlScheme) else {
            return false
        }
        return UIApplication.shared.canOpenURL(url)
    }

    override func prepare(withActivityItems activityItems: [Any]) {
        // At this point I store incoming activity items to use them later in `perform()`
        self.activityItems = activityItems
    }

    override var activityImage: UIImage? {
        // 60x60, 120x120 and 180x180
        return nil
    }

    override func perform() {
        guard let body = activityItems?.first as? String, let encodedBody = body.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed) else {
            activityDidFinish(false)
            return
        }
        let urlString = "\(urlScheme)///co?body=\(encodedBody)"
        guard let url = URL(string: urlString) else {
            activityDidFinish(false)
            return
        }
        UIApplication.shared.openURL(url)
        activityDidFinish(true)
    }

}


问:
MYSQL / PHP TWO Multiselect Dropdown Filters (PDO)
The errors I am getting are the following: (Also i am echoing the query statement)

Notice: Array to string conversion in /home/fanati10/public_html/wp-content/themes/digital-pro/page-nflwranalyzer.php on line 75

Notice: Array to string conversion in /home/fanati10/public_html/wp-content/themes/digital-pro/page-nflwranalyzer.php on line 79

*SELECT * FROM WR_TeamAnalyzer WHERE TMID = ? AND WKID = ?*

HERE IS MY php file

```<code>  if(isset($_POST['submit']))
  {
      require_once( get_stylesheet_directory() . '/config/config.php' );
      if(isset($_POST['check'])) {
        $nflposs = "";
        foreach($_POST['check'] as $val => $text_field) {
          $nflposs.=$text_field.", ";
       }
          $nflpossint = rtrim($nflposs, ', ');
          $nflposs = explode(',', $nflpossint);
          $placeholders = rtrim(str_repeat('?, ', count($nflposs)), ', ');
          $filter[] = "TMID = $placeholders";
          $values[] = $nflpossint;
      }
       if(isset($_POST['wk'])) {
        $wkid = "";
        foreach($_POST['wk'] as $val => $text_field) {
          $wkid.=$text_field.", ";
       }
          $wkidint = rtrim($wkid, ', ');
          $wkid = explode(',', $wkidint);
          $placeholders2 = rtrim(str_repeat('?, ', count($wkid)), ', ');
          $filter[] = "WKID = $placeholders2";
          $values[] = $wkidint;
      }
      $sql="SELECT * FROM WR_TeamAnalyzer WHERE " . implode(' AND ', $filter);
      echo ($sql);
      $selectStmt = $dbcon->prepare($sql);
      $selectStmt->execute($values);
      $rows = $selectStmt->fetchAll();
  $tableContent = '';
  foreach ($rows as $row){
    $tableContent = $tableContent.'<tr>'.
</code>```

答:
When you use = in a query it will expect a string. But you are passing an Array (values) in parameters. I'm not sure what you are trying to achieve here but if you want to check in an Array, change these two lines in your code as below:

```<code>TMID IN $placeholders
WKID IN $placeholders2
</code>```

Your final query should look like this:

```<code>SELECT * FROM WR_TeamAnalyzer WHERE TMID IN (?) AND WKID IN (?)
</code>```

Body:
The errors I am getting are the following: (Also i am echoing the query statement)

Notice: Array to string conversion in /home/fanati10/public_html/wp-content/themes/digital-pro/page-nflwranalyzer.php on line 75

Notice: Array to string conversion in /home/fanati10/public_html/wp-content/themes/digital-pro/page-nflwranalyzer.php on line 79

*SELECT * FROM WR_TeamAnalyzer WHERE TMID = ? AND WKID = ?*

HERE IS MY php file

  if(isset($_POST['submit']))
  {
      require_once( get_stylesheet_directory() . '/config/config.php' );
      if(isset($_POST['check'])) {
        $nflposs = "";
        foreach($_POST['check'] as $val => $text_field) {
          $nflposs.=$text_field.", ";
       }
          $nflpossint = rtrim($nflposs, ', ');
          $nflposs = explode(',', $nflpossint);
          $placeholders = rtrim(str_repeat('?, ', count($nflposs)), ', ');
          $filter[] = "TMID = $placeholders";
          $values[] = $nflpossint;
      }
       if(isset($_POST['wk'])) {
        $wkid = "";
        foreach($_POST['wk'] as $val => $text_field) {
          $wkid.=$text_field.", ";
       }
          $wkidint = rtrim($wkid, ', ');
          $wkid = explode(',', $wkidint);
          $placeholders2 = rtrim(str_repeat('?, ', count($wkid)), ', ');
          $filter[] = "WKID = $placeholders2";
          $values[] = $wkidint;
      }
      $sql="SELECT * FROM WR_TeamAnalyzer WHERE " . implode(' AND ', $filter);
      echo ($sql);
      $selectStmt = $dbcon->prepare($sql);
      $selectStmt->execute($values);
      $rows = $selectStmt->fetchAll();
  $tableContent = '';
  foreach ($rows as $row){
    $tableContent = $tableContent.'
'.

Body:
When you use = in a query it will expect a string. But you are passing an Array (values) in parameters. I'm not sure what you are trying to achieve here but if you want to check in an Array, change these two lines in your code as below:

TMID IN $placeholders
WKID IN $placeholders2

Your final query should look like this:

SELECT * FROM WR_TeamAnalyzer WHERE TMID IN (?) AND WKID IN (?)


问:
how can i enable both SPI for beaglebone black in QNX
By default spi0 is available. It works fine.

Now I want both spi port works as dev/spi0 and dev/spi1.

I rebuilt the image after modifying the build file.

```<code>#######################################################################
## SPI driver
## SPI 0 ioport 0x48030100 irq 65
## SPI 1 ioport 0x481a0100 irq 125
#######################################################################
display_msg Starting SPI driver...
#  SPI0
#spi-master -d am335x base=0x48030100,irq=65,edma=1,edmairq=529,edmachannel=17
#  SPI1
# spi-master -d am335x base=0x481A0100,irq=125,edma=1,edmairq=555,edmachannel=43
spi-master -d am335x base=0x481A0100,irq=125
spi-master -u1 am335x base=0x48030100,irq=65
</code>```

However, spi1 does not work.   only spi0 appears in the /dev folder

答:
I think there is something wrong with the command line. you missed the -d before the library. Please try - </p>

```<code>spi-master -u 1 -d am335x base=0x48030100,irq=65
</code>```

Body:
By default spi0 is available. It works fine.

Now I want both spi port works as dev/spi0 and dev/spi1.

I rebuilt the image after modifying the build file.

#######################################################################
## SPI driver
## SPI 0 ioport 0x48030100 irq 65
## SPI 1 ioport 0x481a0100 irq 125
#######################################################################
display_msg Starting SPI driver...
#  SPI0
#spi-master -d am335x base=0x48030100,irq=65,edma=1,edmairq=529,edmachannel=17
#  SPI1
# spi-master -d am335x base=0x481A0100,irq=125,edma=1,edmairq=555,edmachannel=43
spi-master -d am335x base=0x481A0100,irq=125
spi-master -u1 am335x base=0x48030100,irq=65

However, spi1 does not work.   only spi0 appears in the /dev folder

Body:
I think there is something wrong with the command line. you missed the -d before the library. Please try -

spi-master -u 1 -d am335x base=0x48030100,irq=65


问:
Publishing Webservice looses file (reference), locally it works
I have a project which includes a webService W, a core project C, a plugin P and a thirdparty tool T from nuget. P references C and T.

In the webservice C and P are referenced. If I publish the webservice and try to use it in an Iis 7 I get a FileNotFoundException (File or on of its dependencies not found. Module not found.) for T, despite the T.dll being in the same folder as all other dlls. Same if I also reference T or just T and not P.

If I loose both the references to P and T, Service compiles and works (but obvoiusly not for the intended task).

I also tried the latter and adding P.dll and T.dll manually to the folder to no avail.

If I start the WebService from VS all works as expected.

I have no clue where to look for further information or what to try next. Please give me a hint.

Edit

The Exact errormessage is as follows:

```<code>[FileNotFoundException: Die Datei oder Assembly "TTT.dll" oder eine Abhängigkeit davon wurde nicht gefunden. Das angegebene Modul wurde nicht gefunden.]
   System.Reflection.RuntimeAssembly._nLoad(AssemblyName fileName, String codeBase, Evidence assemblySecurity, RuntimeAssembly locationHint, StackCrawlMark& stackMark, IntPtr pPrivHostBinder, Boolean throwOnFileNotFound, Boolean forIntrospection, Boolean suppressSecurityChecks) +0
   System.Reflection.RuntimeAssembly.nLoad(AssemblyName fileName, String codeBase, Evidence assemblySecurity, RuntimeAssembly locationHint, StackCrawlMark& stackMark, IntPtr pPrivHostBinder, Boolean throwOnFileNotFound, Boolean forIntrospection, Boolean suppressSecurityChecks) +36
   System.Reflection.RuntimeAssembly.InternalLoadAssemblyName(AssemblyName assemblyRef, Evidence assemblySecurity, RuntimeAssembly reqAssembly, StackCrawlMark& stackMark, IntPtr pPrivHostBinder, Boolean throwOnFileNotFound, Boolean forIntrospection, Boolean suppressSecurityChecks) +152
   System.Reflection.RuntimeAssembly.InternalLoad(String assemblyString, Evidence assemblySecurity, StackCrawlMark& stackMark, IntPtr pPrivHostBinder, Boolean forIntrospection) +77
   System.Reflection.RuntimeAssembly.InternalLoad(String assemblyString, Evidence assemblySecurity, StackCrawlMark& stackMark, Boolean forIntrospection) +21
   System.Reflection.Assembly.Load(String assemblyString) +28
   System.Web.Configuration.CompilationSection.LoadAssemblyHelper(String assemblyName, Boolean starDirective) +38

[ConfigurationErrorsException: Die Datei oder Assembly "TTT.dll" oder eine Abhängigkeit davon wurde nicht gefunden. Das angegebene Modul wurde nicht gefunden.]
   System.Web.Configuration.CompilationSection.LoadAssemblyHelper(String assemblyName, Boolean starDirective) +738
   System.Web.Configuration.CompilationSection.LoadAllAssembliesFromAppDomainBinDirectory() +217
   System.Web.Configuration.CompilationSection.LoadAssembly(AssemblyInfo ai) +130
   System.Web.Compilation.BuildManager.GetReferencedAssemblies(CompilationSection compConfig) +170
   System.Web.Compilation.BuildManager.GetPreStartInitMethodsFromReferencedAssemblies() +92
   System.Web.Compilation.BuildManager.CallPreStartInitMethods(String preStartInitListPath, Boolean& isRefAssemblyLoaded) +290
   System.Web.Compilation.BuildManager.ExecutePreAppStart() +157
   System.Web.Hosting.HostingEnvironment.Initialize(ApplicationManager appManager, IApplicationHost appHost, IConfigMapPathFactory configMapPathFactory, HostingEnvironmentParameters hostingParameters, PolicyLevel policyLevel, Exception appDomainCreationException) +531

[HttpException (0x80004005): Die Datei oder Assembly "TTT.dll" oder eine Abhängigkeit davon wurde nicht gefunden. Das angegebene Modul wurde nicht gefunden.]
   System.Web.HttpRuntime.FirstRequestInit(HttpContext context) +9946132
   System.Web.HttpRuntime.EnsureFirstRequestInit(HttpContext context) +90
   System.Web.HttpRuntime.ProcessRequestNotificationPrivate(IIS7WorkerRequest wr, HttpContext context) +261
</code>```

答: Found out the third party tool (T) needed the Visual C++ Redistributable Packages.</p>

Body:
I have a project which includes a webService W, a core project C, a plugin P and a thirdparty tool T from nuget. P references C and T.

In the webservice C and P are referenced. If I publish the webservice and try to use it in an Iis 7 I get a FileNotFoundException (File or on of its dependencies not found. Module not found.) for T, despite the T.dll being in the same folder as all other dlls. Same if I also reference T or just T and not P.

If I loose both the references to P and T, Service compiles and works (but obvoiusly not for the intended task).

I also tried the latter and adding P.dll and T.dll manually to the folder to no avail.

If I start the WebService from VS all works as expected.

I have no clue where to look for further information or what to try next. Please give me a hint.

Edit

The Exact errormessage is as follows:

[FileNotFoundException: Die Datei oder Assembly "TTT.dll" oder eine Abhängigkeit davon wurde nicht gefunden. Das angegebene Modul wurde nicht gefunden.]
   System.Reflection.RuntimeAssembly._nLoad(AssemblyName fileName, String codeBase, Evidence assemblySecurity, RuntimeAssembly locationHint, StackCrawlMark& stackMark, IntPtr pPrivHostBinder, Boolean throwOnFileNotFound, Boolean forIntrospection, Boolean suppressSecurityChecks) +0
   System.Reflection.RuntimeAssembly.nLoad(AssemblyName fileName, String codeBase, Evidence assemblySecurity, RuntimeAssembly locationHint, StackCrawlMark& stackMark, IntPtr pPrivHostBinder, Boolean throwOnFileNotFound, Boolean forIntrospection, Boolean suppressSecurityChecks) +36
   System.Reflection.RuntimeAssembly.InternalLoadAssemblyName(AssemblyName assemblyRef, Evidence assemblySecurity, RuntimeAssembly reqAssembly, StackCrawlMark& stackMark, IntPtr pPrivHostBinder, Boolean throwOnFileNotFound, Boolean forIntrospection, Boolean suppressSecurityChecks) +152
   System.Reflection.RuntimeAssembly.InternalLoad(String assemblyString, Evidence assemblySecurity, StackCrawlMark& stackMark, IntPtr pPrivHostBinder, Boolean forIntrospection) +77
   System.Reflection.RuntimeAssembly.InternalLoad(String assemblyString, Evidence assemblySecurity, StackCrawlMark& stackMark, Boolean forIntrospection) +21
   System.Reflection.Assembly.Load(String assemblyString) +28
   System.Web.Configuration.CompilationSection.LoadAssemblyHelper(String assemblyName, Boolean starDirective) +38

[ConfigurationErrorsException: Die Datei oder Assembly "TTT.dll" oder eine Abhängigkeit davon wurde nicht gefunden. Das angegebene Modul wurde nicht gefunden.]
   System.Web.Configuration.CompilationSection.LoadAssemblyHelper(String assemblyName, Boolean starDirective) +738
   System.Web.Configuration.CompilationSection.LoadAllAssembliesFromAppDomainBinDirectory() +217
   System.Web.Configuration.CompilationSection.LoadAssembly(AssemblyInfo ai) +130
   System.Web.Compilation.BuildManager.GetReferencedAssemblies(CompilationSection compConfig) +170
   System.Web.Compilation.BuildManager.GetPreStartInitMethodsFromReferencedAssemblies() +92
   System.Web.Compilation.BuildManager.CallPreStartInitMethods(String preStartInitListPath, Boolean& isRefAssemblyLoaded) +290
   System.Web.Compilation.BuildManager.ExecutePreAppStart() +157
   System.Web.Hosting.HostingEnvironment.Initialize(ApplicationManager appManager, IApplicationHost appHost, IConfigMapPathFactory configMapPathFactory, HostingEnvironmentParameters hostingParameters, PolicyLevel policyLevel, Exception appDomainCreationException) +531

[HttpException (0x80004005): Die Datei oder Assembly "TTT.dll" oder eine Abhängigkeit davon wurde nicht gefunden. Das angegebene Modul wurde nicht gefunden.]
   System.Web.HttpRuntime.FirstRequestInit(HttpContext context) +9946132
   System.Web.HttpRuntime.EnsureFirstRequestInit(HttpContext context) +90
   System.Web.HttpRuntime.ProcessRequestNotificationPrivate(IIS7WorkerRequest wr, HttpContext context) +261


答:
Here the problem is that in java double literals end with a d if you didn't put d it will consider as an integer, hence integer no too large error will throw.

In this case you are missing d, so add d for the numbers which dont have a precision..

eg double no = 1555760766d;

Title: integer number too large in arraylist

Body:
My ArrayList is like this, but I get an error "integer number too large".

testNet.setTrainSet(new double[][] {

                { 1555760766,0.18 },{ 1555760766,0.3 },
               { 1555760766,0.6 }, { 1555760766,0.6},

                { 2076569012,0.45 }, { 2076569012,0.64},
                { 2076569012,0.78 }, { 2076569012,0.98 },
                {2076569012,0.98 } ,  { 3265731800,0.1 },

                });

what is the solution?


问:
Create a CSV File for a user in PHP
I have data in a MySQL database. I am sending the user a URL to get their data out as a CSV file.

I have the e-mailing of the link, MySQL query, etc. covered.

How can I, when they click the link, have a pop-up to download a CVS with the record from MySQL?

I have all the information to get the record already. I just don't see how to have PHP create the CSV file and let them download a file with a .csv extension.

答:
Writing your own CSV code is probably a waste of your time, just use a package such as league/csv - it deals with all the difficult stuff for you, the documentation is good and it's very stable / reliable:

http://csv.thephpleague.com/

You'll need to be using composer. If you don't know what composer is I highly recommend you have a look: https://getcomposer.org/

OwnerDisplayName: Jason

Title: Create a CSV File for a user in PHP


答:
The <input type="submit"> will reach the action attribute of your <form> when clicked, or will refresh the page if the action is empty.

You can use a <button> element and assign it a function on the click event, for example:

```<code><!-- There is no form needed if you don't need to submit -->
<div id="form">
    <input type="number" id="myNumber">
    <input type="number" id="myOtherNumber">
    <button type="button" id="submit">Calculation</button>
</div>
</code>```

JS part:

```<code>window.onload = function () {
    /* get elements */
    var num_1 = document.getElementById('myNumber'),
        num_2 = document.getElementById('myOtherNumber'),
        btn = document.getElementById('submit');

    /* do what you want with your number
       when the button is clicked */
    btn.onclick = function () {
        window.console.log(num_1.value + num_2.value);
    };
};
</code>```

Title: Keep user input after press input type="submit" without using JQuery or Ajax

Body:
The <input type="submit"> will reach the action attribute of your <form> when clicked, or will refresh the page if the action is empty.

You can use a <button> element and assign it a function on the click event, for example:

<!-- There is no form needed if you don't need to submit -->
<div id="form">
    <input type="number" id="myNumber">
    <input type="number" id="myOtherNumber">
    <button type="button" id="submit">Calculation</button>
</div>

JS part:

window.onload = function () {
    /* get elements */
    var num_1 = document.getElementById('myNumber'),
        num_2 = document.getElementById('myOtherNumber'),
        btn = document.getElementById('submit');

    /* do what you want with your number
       when the button is clicked */
    btn.onclick = function () {
        window.console.log(num_1.value + num_2.value);
    };
};


问:
Correctly defining this data relation in Django models
I'm working on a Django project, where I have amongst others, two models that have a relationship.

The first model describes a dish in general. It has a name and some other basic information, for instance:

```<code>dish(models.Model):
    name = models.CharField(max_length=100)
    short_desc = models.CharField(max_lenght=255)
    vegetarian = models.BooleanField(default=False)
    vegan = models.BooleanField(default=False)
</code>```

The second model is related to the dish, I assume in form of a one-to-one relationship. This model contains the preparation and the ingredients. This data may change over time for the dish (e.g. preparation text is adjusted). Old versions of this text are still stored, but not connected to the dish. So  the dish gets a new field, which points to the current preparation text.

```<code>    preparation = models.???(???)
</code>```

So, whenever the preparation description is changed a new entry is created for the preparation and the dish's reference to the preparation is updated.

The preparation itself looks like this:

```<code>preparation(models.Model):
    prep_test = models.TextField()
    ingredients = models.TextField()
    last_update = models.DateTimeField()
</code>```

As stated before, I believe that a one-to-one relation would be reasonable between the dish and the preparation.

Is my assumption with the one-to-one relation correct and if so, how do I correctly define it?

答:
If you have multiple preparations for the dish, you don't have a one-to-one relationship by definition.

The way to define this is a ForeignKey from Preparation to Dish. (Note, Python style is that classes start with an upper case letter.)

```<code>class Preparation(models.Model):
    ...
    dish = models.ForeignKey('Dish')
</code>```

Now you can do my_dish.preparation_set.latest('last_update') to get the latest preparation for a dish. If you add an inner Meta class to Preparation and define get_latest_by = 'last_update'), you can leave out the parameter to the latest() call.

Body:
I'm working on a Django project, where I have amongst others, two models that have a relationship.

The first model describes a dish in general. It has a name and some other basic information, for instance:

dish(models.Model):
    name = models.CharField(max_length=100)
    short_desc = models.CharField(max_lenght=255)
    vegetarian = models.BooleanField(default=False)
    vegan = models.BooleanField(default=False)

The second model is related to the dish, I assume in form of a one-to-one relationship. This model contains the preparation and the ingredients. This data may change over time for the dish (e.g. preparation text is adjusted). Old versions of this text are still stored, but not connected to the dish. So  the dish gets a new field, which points to the current preparation text.

    preparation = models.???(???)

So, whenever the preparation description is changed a new entry is created for the preparation and the dish's reference to the preparation is updated.

The preparation itself looks like this:

preparation(models.Model):
    prep_test = models.TextField()
    ingredients = models.TextField()
    last_update = models.DateTimeField()

As stated before, I believe that a one-to-one relation would be reasonable between the dish and the preparation.

Is my assumption with the one-to-one relation correct and if so, how do I correctly define it?

Body:
If you have multiple preparations for the dish, you don't have a one-to-one relationship by definition.

The way to define this is a ForeignKey from Preparation to Dish. (Note, Python style is that classes start with an upper case letter.)

class Preparation(models.Model):
    ...
    dish = models.ForeignKey('Dish')

Now you can do my_dish.preparation_set.latest('last_update') to get the latest preparation for a dish. If you add an inner Meta class to Preparation and define get_latest_by = 'last_update'), you can leave out the parameter to the latest() call.


问:
C# writeline cap
I am writing a program that writes to a file that requires specific positions:

it looks something like:

```<code>writer.WriteLine("{0,-3}{1,-5}{2,-30}", data1, data2, data3);
</code>```

The positions that it starts is correct however, if data1 exceeds 3 character, it pushes the format by the exceeded amount,

Is there a way to make data1 cap at 3 characters and ignore any excess characters using the writeline format?

答:
You can't solve this with formatting alone, but you can implement a (extension) method:

```<code>   public static string ToLength(this object value, int length) {
     if (length == 0)
       return "";
     else if (null == value)
       return new string(' ', Math.Abs(length));

     string v = value.ToString();

     if (v.Length >= Math.Abs(length))
       return v.Substring(0, Math.Abs(length));
     else if (length < 0)
       return v.PadRight(-length);
     else
       return v.PadLeft(length);
   }
</code>```

Then use it

```<code>   writer.WriteLine("{0}{1}{2}",
     data1.ToLength(-3),
     data2.ToLength(-5),
     data3.ToLength(-30));
</code>```

I've implemented extension method for object, not string since you may want to put any object to stream.

Title: C# writeline cap

Body:
I am writing a program that writes to a file that requires specific positions:

it looks something like:

writer.WriteLine("{0,-3}{1,-5}{2,-30}", data1, data2, data3);

The positions that it starts is correct however, if data1 exceeds 3 character, it pushes the format by the exceeded amount,

Is there a way to make data1 cap at 3 characters and ignore any excess characters using the writeline format?

Body:
You can't solve this with formatting alone, but you can implement a (extension) method:

   public static string ToLength(this object value, int length) {
     if (length == 0)
       return "";
     else if (null == value)
       return new string(' ', Math.Abs(length));

     string v = value.ToString();

     if (v.Length >= Math.Abs(length))
       return v.Substring(0, Math.Abs(length));
     else if (length < 0)
       return v.PadRight(-length);
     else
       return v.PadLeft(length);
   }

Then use it

   writer.WriteLine("{0}{1}{2}",
     data1.ToLength(-3),
     data2.ToLength(-5),
     data3.ToLength(-30));

I've implemented extension method for object, not string since you may want to put any object to stream.


问:
Angular adds a day when displaying the date (dd/MM/yyyy)
I have a datepicker where the user picks the date without choosing the time, the date is saved correctly in my data base but when I display it, it shows one day ahaid, when I looked up the issue it turns out that it's a timezone issue that lots of people face but i didn't quite understand how to fix it in my code :

```<code><tbody>
   <tr ng-repeat="ft in ftListesorted">
      <td>{{ft.NomProjet}}</td>
      <td>{{ft.NomTache}}</td>
      <td>{{ft.Datefeuillestemps |  date : 'dd/MM/yyyy' }}</td>
   </tr>
</tbody>
</code>```

I get the "ft.Datefeuillestemps" from my database where the default time is always set to T00:00:00.

For example here's how my date is stored in the data base : 2017-05-17 00:00:00.0000000 and this is what I get in my view : 18/05/2017 so a day is added.

How can I solve this issue ?

答:
```<code>$scope.passdate = function (dt) {
    var targetTime = new Date(dt);
    var timeZoneFromDB = -7.00; //time zone value from database
    //get the timezone offset from local time in minutes
    var tzDifference = timeZoneFromDB * 60 + targetTime.getTimezoneOffset();
    //convert the offset to milliseconds, add to targetTime, and make a new Date
    var offsetTime = new Date(targetTime.getTime() + tzDifference * 60 * 1000);
    $scope.ISODateString(offsetTime);
}
</code>```

check this if helps

Body:
I have a datepicker where the user picks the date without choosing the time, the date is saved correctly in my data base but when I display it, it shows one day ahaid, when I looked up the issue it turns out that it's a timezone issue that lots of people face but i didn't quite understand how to fix it in my code :

      {{ft.NomProjet}}
      {{ft.NomTache}}
      {{ft.Datefeuillestemps |  date : 'dd/MM/yyyy' }}

I get the "ft.Datefeuillestemps" from my database where the default time is always set to T00:00:00.

For example here's how my date is stored in the data base : 2017-05-17 00:00:00.0000000 and this is what I get in my view : 18/05/2017 so a day is added.

How can I solve this issue ?

Body:
$scope.passdate = function (dt) {
    var targetTime = new Date(dt);
    var timeZoneFromDB = -7.00; //time zone value from database
    //get the timezone offset from local time in minutes
    var tzDifference = timeZoneFromDB * 60 + targetTime.getTimezoneOffset();
    //convert the offset to milliseconds, add to targetTime, and make a new Date
    var offsetTime = new Date(targetTime.getTime() + tzDifference * 60 * 1000);
    $scope.ISODateString(offsetTime);
}

check this if helps


问:
How to show product title in browser url use angular 4?
currently I am show my single blog in pram id, but I needed show present viewing blog title in url supposes:
http://localhost:4200/blogs/viewsingleblog/1
to
http://localhost:4200/blogs/viewsingleblog/Exclusive-T-shirt-For-You

blog json data is:

```<code>blogs = [
        {
            id: 2,
            title: 'Exclusive T-shirt For You ..!',
            discription:"Lorem ipsum ......",
            postDate: '02-05-2017',
            author: 'admin',
            thambnils: '/src/app/images/t-shirt1.jpg',
            public: true,
            like: false
        }
]

**app route is:**
          {
            path:'blogs',
            children: [
              {
                path: '', component:BlogComponent
              },
              {
                path: 'viewsingleblog/:title',
                component: SingleblogComponent
              }
            ]
        }
</code>```

blog services

```<code>getBlog(title:any):Promise<Blog>{

    title= title.replace(new RegExp('-', 'gi'), '+');
// for replace blank space to "-" to show url

    const singleBlog= `${this.url}/?${title}`;
    console.log("Your Log Url => " + singleBlog);
        return this.http.get(singleBlog)
            .toPromise()
            .then(response => response.json().data as Blog)
            .catch(this.handleError)
    }
  private handleError(error: any): Promise<any>{
    console.log(error);
    return Promise.reject(error.message || error);
  }
</code>```

And My single blog component is:

```<code>import { Component, OnInit } from '@angular/core';
import { ActivatedRoute, Params , Router }   from '@angular/router';
import { Location }                 from '@angular/common';
import 'rxjs/add/operator/switchMap';

import { Blog } from '../../class/blog';
import { BlogService } from '../../service/blog.service';

@Component({
  selector: 'app-singleblog',
  templateUrl: './singleblog.component.html',
  styleUrls: ['./singleblog.component.css']
})
export class SingleblogComponent implements OnInit {
    blog:Blog;
    recentBlog:Blog[];
    constructor(
        private _blogService: BlogService,
        private location: Location,
        private route:ActivatedRoute,
        private router: Router
        ) { }
    getBlog():void {
        this.route.params
        .switchMap((params: Params) =>
            this._blogService.getBlog(this.route.snapshot.params.title))
        .subscribe(blog => this.blog = blog);
        console.log(this.blog);
    }

    getRecentBlogs():void {
        this._blogService.getBlogs().then(recentBlog=> this.recentBlog = recentBlog);
    }
    ngOnInit() {
        this.getBlog();
        this.getRecentBlogs();
    }
    backnow() { this.location.back(); }
    changeBlog(id:number){ this.router.navigate(['/viewsingleblog', id]); }
}
</code>```

答:
You need to subscribe. </p>

```<code> title: string;

  private sub: any;

  constructor(private route: ActivatedRoute) {...}

  ngOnInit() {
    this.sub = this.route.params.subscribe(params => {
       this.title = params['title'];
    });
  }

  ngOnDestroy() {
    this.sub.unsubscribe();
  }
</code>```

ContentLicense: CC BY-SA 4.0

Body:
currently I am show my single blog in pram id, but I needed show present viewing blog title in url supposes:
http://localhost:4200/blogs/viewsingleblog/1
to
http://localhost:4200/blogs/viewsingleblog/Exclusive-T-shirt-For-You

blog json data is:

blogs = [
        {
            id: 2,
            title: 'Exclusive T-shirt For You ..!',
            discription:"Lorem ipsum ......",
            postDate: '02-05-2017',
            author: 'admin',
            thambnils: '/src/app/images/t-shirt1.jpg',
            public: true,
            like: false
        }
]

**app route is:**
          {
            path:'blogs',
            children: [
              {
                path: '', component:BlogComponent
              },
              {
                path: 'viewsingleblog/:title',
                component: SingleblogComponent
              }
            ]
        }

blog services

getBlog(title:any):Promise<Blog>{

    title= title.replace(new RegExp('-', 'gi'), '+');
// for replace blank space to "-" to show url

    const singleBlog= `${this.url}/?${title}`;
    console.log("Your Log Url => " + singleBlog);
        return this.http.get(singleBlog)
            .toPromise()
            .then(response => response.json().data as Blog)
            .catch(this.handleError)
    }
  private handleError(error: any): Promise<any>{
    console.log(error);
    return Promise.reject(error.message || error);
  }

And My single blog component is:

import { Component, OnInit } from '@angular/core';
import { ActivatedRoute, Params , Router }   from '@angular/router';
import { Location }                 from '@angular/common';
import 'rxjs/add/operator/switchMap';

import { Blog } from '../../class/blog';
import { BlogService } from '../../service/blog.service';

@Component({
  selector: 'app-singleblog',
  templateUrl: './singleblog.component.html',
  styleUrls: ['./singleblog.component.css']
})
export class SingleblogComponent implements OnInit {
    blog:Blog;
    recentBlog:Blog[];
    constructor(
        private _blogService: BlogService,
        private location: Location,
        private route:ActivatedRoute,
        private router: Router
        ) { }
    getBlog():void {
        this.route.params
        .switchMap((params: Params) =>
            this._blogService.getBlog(this.route.snapshot.params.title))
        .subscribe(blog => this.blog = blog);
        console.log(this.blog);
    }

    getRecentBlogs():void {
        this._blogService.getBlogs().then(recentBlog=> this.recentBlog = recentBlog);
    }
    ngOnInit() {
        this.getBlog();
        this.getRecentBlogs();
    }
    backnow() { this.location.back(); }
    changeBlog(id:number){ this.router.navigate(['/viewsingleblog', id]); }
}

Body:
You need to subscribe.

 title: string;

  private sub: any;

  constructor(private route: ActivatedRoute) {...}

  ngOnInit() {
    this.sub = this.route.params.subscribe(params => {
       this.title = params['title'];
    });
  }

  ngOnDestroy() {
    this.sub.unsubscribe();
  }


问:
Profiling a Scala Spark application
I would like to profile my sSpark scala applications to figure out the parts of the code which i have to optimize. I enabled -Xprof in --driver-java-options but this is not of much help to me as it gives lot of granular details. I am just interested to know how much time each function call in my application is taking time.
As is other Stack Overflow questions, many people suggested YourKit but it is not inexpensive. So i would like to use something which is not costly in fact free of cost.

Are there any better ways to solve this ?

答:
I've written an article and a script recently, that wraps spark-submit, and generates a flame graph after executing a Spark application.

Here's the article: https://www.linkedin.com/pulse/profiling-spark-applications-one-click-michael-spector

Here's the script: https://raw.githubusercontent.com/spektom/spark-flamegraph/master/spark-submit-flamegraph

Just use it instead of regular spark-submit.

Title: Profiling a Scala Spark application


问:
How to update foreign key in EF 6 - Code First - One to many relationship
Based on the solution provided in this question : How to update foreign key in EF 6 - Code First, I'm able to update my foreign key using the id field.

But now, I get an exception when getting entities from the database. Using this code :

```<code>// Retrieve data first
using (var db = new TestDbContext())
{
    var p2 = db.Persons.First();
}
</code>```

I get the following SqlException : "Invalid column name 'Country_Id1'."

Does anyone have any clues to be able to retrieve data and to update the foreign key ?
Asked in another way, is it possible to use both the navigation property to ease the use of my entity and the id of the foreign key to be able to update my dependent entity ?

My entities

```<code>public class Person
{
    public int Id { get; set; }
    public string Name { get; set; }
    public virtual Country Country { get; set; }
    public int Country_Id { get; set; }
}

public class Country
{
    public int Id { get; set; }
    public string Name { get; set; }
}
</code>```

答:
That might be because entity framework is trying to create new foreign key based on navigation property Country in Person entity.

I think you should annotate Country_Id property with ForeignKey attribute as below.

```<code>public class Person
{
    public int Id { get; set; }
    public string Name { get; set; }
    [ForeignKey("Country_Id")]
    public virtual Country Country { get; set; }
    public int Country_Id { get; set; }
}
</code>```

However if you follow the ef naming convention for naming property as below, you  don't need to annotate it.

Any property with the same data type as the principal primary key
  property and with a name that follows one of the following formats
  represents a foreign key for the relationship: '', '', or ''

You may read more from here

```<code>public class Person
{
    public int Id { get; set; }
    public string Name { get; set; }
    public virtual Country Country { get; set; }
    public int CountryId { get; set; }
}
</code>```

Note: you might need to run database migration or need to recreate database.

Body:
Based on the solution provided in this question : How to update foreign key in EF 6 - Code First, I'm able to update my foreign key using the id field.

But now, I get an exception when getting entities from the database. Using this code :

// Retrieve data first
using (var db = new TestDbContext())
{
    var p2 = db.Persons.First();
}

I get the following SqlException : "Invalid column name 'Country_Id1'."

Does anyone have any clues to be able to retrieve data and to update the foreign key ?
Asked in another way, is it possible to use both the navigation property to ease the use of my entity and the id of the foreign key to be able to update my dependent entity ?

My entities

public class Person
{
    public int Id { get; set; }
    public string Name { get; set; }
    public virtual Country Country { get; set; }
    public int Country_Id { get; set; }
}

public class Country
{
    public int Id { get; set; }
    public string Name { get; set; }
}

Body:
That might be because entity framework is trying to create new foreign key based on navigation property Country in Person entity.

I think you should annotate Country_Id property with ForeignKey attribute as below.

public class Person
{
    public int Id { get; set; }
    public string Name { get; set; }
    [ForeignKey("Country_Id")]
    public virtual Country Country { get; set; }
    public int Country_Id { get; set; }
}

However if you follow the ef naming convention for naming property as below, you  don't need to annotate it.

Any property with the same data type as the principal primary key
  property and with a name that follows one of the following formats
  represents a foreign key for the relationship: '', '', or ''

You may read more from here

public class Person
{
    public int Id { get; set; }
    public string Name { get; set; }
    public virtual Country Country { get; set; }
    public int CountryId { get; set; }
}

Note: you might need to run database migration or need to recreate database.


问:
error on sql script with 'openrowset'
I'm having a problem with my SQL script:

```<code>SELECT
  SP.[MobileNumber],
  SP.[LastName],
  SP.[FirstName]
FROM SampleTable1 SP
INNER JOIN OPENROWSET
(
  'Microsoft.Jet.OLEDB.4.0',
  'Excel 8.0;Database=C:\devpc11\sample.xls;',
  'SELECT
     MobileNumber,
     LastName,
     FirstName
   FROM [SampleData$]') T
ON SP.[MobileNumber] = T.[MobileNumber]
GO
</code>```

when i try to execute this, it generates this error:

Msg 7357, Level 16, State 2, Line 1
Cannot process the object "SELECT
     MobileNumber,
     LastName,
  FirstName
   FROM [SampleData$]". The OLE DB provider "Microsoft.Jet.OLEDB.4.0" for linked server "(null)" indicates that either the object has no columns or the current user does not have permissions on that object.

Is there any solution for this? i really can't find any in the past 3 hours.. Basically, i just want to manipulate data from an excel file, then save it to sql server 2005 database, but for now, i want to retrieve data from the excel file to the sql server.. thanks for the help..

答:
I got this to work with a spreadsheet locally. forget OPENROWSET

Create a named range in your excel spreadheet. Tio do this, highlight the columns (including headers) you want, right-click and select 'Name a range'. Give this a name, this will be your table name.

http://www.homeandlearn.co.uk/me/mes9p2.html

Save and close your spreadsheet. SQL Server wont be able to access it if you hve it open.

Add a linked server. Follow the instructions in Section E in the following which tells you how to add a linked server for Excel Spreadsheets:

http://msdn.microsoft.com/en-us/library/ms190479.aspx

You should be able to query the DS quite happily, again following the instructions.

Here is the code that works for me:

```<code>EXEC sp_addlinkedserver 'ExcelSource4',
   'Jet 4.0',
   'Microsoft.Jet.OLEDB.4.0',
   'c:\sqlss.xls',
   NULL,
   'Excel 5.0';
GO

SELECT *
   FROM ExcelSource4...MyTable2;
</code>```

And finally. Start accepting some answers and voting up any helpful ones. This is the lifeblood of StackOverflow.

Title: error on sql script with 'openrowset'

Body:
I'm having a problem with my SQL script:

SELECT
  SP.[MobileNumber],
  SP.[LastName],
  SP.[FirstName]
FROM SampleTable1 SP
INNER JOIN OPENROWSET
(
  'Microsoft.Jet.OLEDB.4.0',
  'Excel 8.0;Database=C:\devpc11\sample.xls;',
  'SELECT
     MobileNumber,
     LastName,
     FirstName
   FROM [SampleData$]') T
ON SP.[MobileNumber] = T.[MobileNumber]
GO

when i try to execute this, it generates this error:

Msg 7357, Level 16, State 2, Line 1
Cannot process the object "SELECT
     MobileNumber,
     LastName,
  FirstName
   FROM [SampleData$]". The OLE DB provider "Microsoft.Jet.OLEDB.4.0" for linked server "(null)" indicates that either the object has no columns or the current user does not have permissions on that object.

Is there any solution for this? i really can't find any in the past 3 hours.. Basically, i just want to manipulate data from an excel file, then save it to sql server 2005 database, but for now, i want to retrieve data from the excel file to the sql server.. thanks for the help..

Body:
I got this to work with a spreadsheet locally. forget OPENROWSET

Create a named range in your excel spreadheet. Tio do this, highlight the columns (including headers) you want, right-click and select 'Name a range'. Give this a name, this will be your table name.

http://www.homeandlearn.co.uk/me/mes9p2.html

Save and close your spreadsheet. SQL Server wont be able to access it if you hve it open.

Add a linked server. Follow the instructions in Section E in the following which tells you how to add a linked server for Excel Spreadsheets:

http://msdn.microsoft.com/en-us/library/ms190479.aspx

You should be able to query the DS quite happily, again following the instructions.

Here is the code that works for me:

EXEC sp_addlinkedserver 'ExcelSource4',
   'Jet 4.0',
   'Microsoft.Jet.OLEDB.4.0',
   'c:\sqlss.xls',
   NULL,
   'Excel 5.0';
GO

SELECT *
   FROM ExcelSource4...MyTable2;

And finally. Start accepting some answers and voting up any helpful ones. This is the lifeblood of StackOverflow.


问:
How to prevent element from exceeding his container borders
I have a square, when clicked it appears in a random location and it also change size (so for example if I have a 30px box but it is 10px from the left border I still get 10px outside the gamespace).

sometimes the square exceed his container border

How can I make sure that the square will never exceed his container?

function position() {
  var positionTop = Math.random() * 100;
  var positionLeft = Math.random() * 100;
  var position = "position:relative;top:" + positionTop + "%;left:" + positionLeft + "%;"
  return position;
}

document.getElementById("shape").onclick = function() {
  document.getElementById("shape").style.cssText = position();
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#gameSpace {
  width: 100%;
  height: 470px;
  background: blue;
  margin: 0;
  padding-top: 30px;
}

#playSpace {
  width: 90%;
  height: 90%;
  margin: 0 auto;
  margin-top: 10px;
  border: 1px black solid;
}

#shape {
  width: 100px;
  height: 100px;
  background-color: red;
}</code>```

```

答:
You can use a specify the range (min/max) in Math.random function and then use this function Math.floor(Math.random() * (max - min + 1)) + min; to limit the returned value of the random function between min and max.

maxTop : height of the container - height of shape

maxLeft : width of the container - width of shape

minTop : 0

minLeft : 0

You need to use position:absolute and px value on shape for this to work

See code snippet:

function position() {

  var minTop = 0;
  var maxTop = document.getElementById("playSpace").clientHeight - document.getElementById("shape").clientHeight;
  var minLeft = 0;
  var maxLeft = document.getElementById("playSpace").clientWidth - document.getElementById("shape").clientWidth ;

  var positionTop = Math.floor(Math.random() * (maxTop - minTop + 1) + minTop);
  var positionLeft = Math.floor(Math.random() * (maxLeft - minLeft + 1) + minLeft);

  var position = "position:absolute;top:" + positionTop + "px;left:" + positionLeft + "px;"
  return position;

}

document.getElementById("shape").onclick = function() {

  document.getElementById("shape").style.cssText = position();

}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#gameSpace {
  width: 100%;
  height: 470px;
  background: blue;
  margin: 0;
  padding-top: 30px;
  text-align:center;
}

#playSpace {
  width: 90%;
  height: 90%;
  border: 1px black solid;
  position:relative;
  display:inline-block;
}

#shape {
  width: 100px;
  height: 100px;
  background-color: red;
}</code>```

```

Body:
I have a square, when clicked it appears in a random location and it also change size (so for example if I have a 30px box but it is 10px from the left border I still get 10px outside the gamespace).

sometimes the square exceed his container border

How can I make sure that the square will never exceed his container?

function position() {
  var positionTop = Math.random() * 100;
  var positionLeft = Math.random() * 100;
  var position = "position:relative;top:" + positionTop + "%;left:" + positionLeft + "%;"
  return position;
}

document.getElementById("shape").onclick = function() {
  document.getElementById("shape").style.cssText = position();
}

#gameSpace {
  width: 100%;
  height: 470px;
  background: blue;
  margin: 0;
  padding-top: 30px;
}

#playSpace {
  width: 90%;
  height: 90%;
  margin: 0 auto;
  margin-top: 10px;
  border: 1px black solid;
}

#shape {
  width: 100px;
  height: 100px;
  background-color: red;
}

Body:
You can use a specify the range (min/max) in Math.random function and then use this function Math.floor(Math.random() * (max - min + 1)) + min; to limit the returned value of the random function between min and max.

maxTop : height of the container - height of shape

maxLeft : width of the container - width of shape

minTop : 0

minLeft : 0

You need to use position:absolute and px value on shape for this to work

See code snippet:

function position() {

  var minTop = 0;
  var maxTop = document.getElementById("playSpace").clientHeight - document.getElementById("shape").clientHeight;
  var minLeft = 0;
  var maxLeft = document.getElementById("playSpace").clientWidth - document.getElementById("shape").clientWidth ;

  var positionTop = Math.floor(Math.random() * (maxTop - minTop + 1) + minTop);
  var positionLeft = Math.floor(Math.random() * (maxLeft - minLeft + 1) + minLeft);

  var position = "position:absolute;top:" + positionTop + "px;left:" + positionLeft + "px;"
  return position;

}

document.getElementById("shape").onclick = function() {

  document.getElementById("shape").style.cssText = position();

}

#gameSpace {
  width: 100%;
  height: 470px;
  background: blue;
  margin: 0;
  padding-top: 30px;
  text-align:center;
}

#playSpace {
  width: 90%;
  height: 90%;
  border: 1px black solid;
  position:relative;
  display:inline-block;
}

#shape {
  width: 100px;
  height: 100px;
  background-color: red;
}

<div id="gameSpace">
  <div id="playSpace">
    <!-- here we put the shape -->
    <div id="shape"></div>
  </div>
</div>


问:
Is it possible to see where a .DLL is searching for a file?
I get a "File not found." message from a .DLL I am using, but I am not sure which path it tries to find the file in. It might as well be hard-coded, and I would like to find out.

Is there any method or tool I could use?

Thank you in advance

答:
See here https://blogs.msdn.microsoft.com/suzcook/2003/05/29/debugging-assembly-loading-failures/

May be it is a problem installing the DLL in the GAC.

a Tool like Reshaper gives more information in these situations, you can try also http://www.dependencywalker.com/