问:
Swift: Simplify menu button logic
I have a game in Swift where each of my levels is a separate class inherited from the base GameScene class (it's a lot easier this way for what I'm doing, don't judge me).
I also have a menu which has a button for each level. This is how the buttons loads the level:

```<code>override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
  if let t = touches.first {
    let node = atPoint(t.location(in: self))
    if let name = node.name {
      let newScene: GameScene!
      switch Int(name)! {
      case 1:
        newScene = Level1(size: frame.size)
      case 2:
        newScene = Level2(size: frame.size)
      case 3:
        newScene = Level3(size: frame.size)
      case 4:
        newScene = Level4(size: frame.size)
      case 5:
        newScene = Level5(size: frame.size)
      case 6:
        newScene = Level6(size: frame.size)
      case 7:
        newScene = Level7(size: frame.size)
      default:
        newScene = Level1(size: frame.size)
      }
      view?.presentScene(newScene, transition: .crossFade(withDuration: 0.5))
    }
  }
}
</code>```

To me, this switch looks incredibly ugly and pointless, but I can't think of a way to avoid it. I was hoping someone here could help me out with this, I just can't think of a better alternative.

答:
You can do this instead:</p>

```<code>    var newScene: GameScene!

    //Level1 is repeating on 0 and 1'st index

    let arrScene : [GameScene] = [Level1(size: frame.size),Level1(size: frame.size),Level2(size: frame.size),Level3(size: frame.size),Level4(size: frame.size),Level5(size: frame.size),Level6(size: frame.size),Level7(size: frame.size)]

    if Int(name)! <=7 && Int(name)! > 0{

    newScene  = arrScene[Int(name)!]

    }else{

    //Default level1
    newScene  = arrScene[0]

    }
</code>```

Title: Swift: Simplify menu button logic

Body:
I have a game in Swift where each of my levels is a separate class inherited from the base GameScene class (it's a lot easier this way for what I'm doing, don't judge me).
I also have a menu which has a button for each level. This is how the buttons loads the level:

override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
  if let t = touches.first {
    let node = atPoint(t.location(in: self))
    if let name = node.name {
      let newScene: GameScene!
      switch Int(name)! {
      case 1:
        newScene = Level1(size: frame.size)
      case 2:
        newScene = Level2(size: frame.size)
      case 3:
        newScene = Level3(size: frame.size)
      case 4:
        newScene = Level4(size: frame.size)
      case 5:
        newScene = Level5(size: frame.size)
      case 6:
        newScene = Level6(size: frame.size)
      case 7:
        newScene = Level7(size: frame.size)
      default:
        newScene = Level1(size: frame.size)
      }
      view?.presentScene(newScene, transition: .crossFade(withDuration: 0.5))
    }
  }
}

To me, this switch looks incredibly ugly and pointless, but I can't think of a way to avoid it. I was hoping someone here could help me out with this, I just can't think of a better alternative.

Body:
You can do this instead:

    var newScene: GameScene!

    //Level1 is repeating on 0 and 1'st index

    let arrScene : [GameScene] = [Level1(size: frame.size),Level1(size: frame.size),Level2(size: frame.size),Level3(size: frame.size),Level4(size: frame.size),Level5(size: frame.size),Level6(size: frame.size),Level7(size: frame.size)]

    if Int(name)! <=7 && Int(name)! > 0{

    newScene  = arrScene[Int(name)!]

    }else{

    //Default level1
    newScene  = arrScene[0]

    }


来源: stackexchange

问:
How to validate console command prompt inputs
Following console command I'm prompting for input. I would like to validate the user input. How can I do that?

I have check the this plugin. But it looks like validating arguments & options. Not the interactive inputs.

CreateClient.php

```<code>namespace App\Console\Commands;

use Illuminate\Console\Command;

class CreateClient extends Command {
    ...

    public function handle() {
        $name   = $this->ask('Enter name ');
        $email  = $this->ask('Enter email ');
        $date   = $this->ask('Enter date [Eg: 2016-01-01 00:00:00] ');

        // Validate user input
        $this->info('Validating user inputs');

       // How to validate email & date format ?
    }
}
</code>```

Update

Yes I'm aware of Validator, but the concern is the validation stops the user journey. User have restart from the beginning. Is it possible to attach a validation to each question, so the validation will be immediate and prompt to enter again.

Below is something I notice when I doesn't enter any value, I'm wondering how can I provide more validation rule.

Thanks in advance.

答:
Create a Validator instance and setup your corresponding rules.

https://laravel.com/api/5.4/Illuminate/Contracts/Validation/Validator.html

Specifically, see the make() method.

https://laravel.com/api/5.4/Illuminate/Contracts/Validation/Factory.html

```<code>public function handle()
{
    $name = $this->ask('Enter name ');
    $validator = \Validator::make(['name' => $name], ['name' => 'required|string']);
    if ($validator->fails()) {
        $message = $validator->messages();
    }
    $email = $this->ask('Enter email ');
    $validator = \Validator::make(['email' => $email], ['email' => 'required|email']);
    if ($validator->fails()) {
        $message = $validator->messages();
    }
    $date = $this->ask('Enter date [Eg: 2016-01-01 00:00:00] ');
    $validator = \Validator::make(['date' => $date], ['date' => 'required|datetime']);
    if ($validator->fails()) {
        $message = $validator->messages();
    }

    // so something with $message
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Following console command I'm prompting for input. I would like to validate the user input. How can I do that?

I have check the this plugin. But it looks like validating arguments & options. Not the interactive inputs.

CreateClient.php

namespace App\Console\Commands;

use Illuminate\Console\Command;

class CreateClient extends Command {
    ...

    public function handle() {
        $name   = $this->ask('Enter name ');
        $email  = $this->ask('Enter email ');
        $date   = $this->ask('Enter date [Eg: 2016-01-01 00:00:00] ');

        // Validate user input
        $this->info('Validating user inputs');

       // How to validate email & date format ?
    }
}

Update

Yes I'm aware of Validator, but the concern is the validation stops the user journey. User have restart from the beginning. Is it possible to attach a validation to each question, so the validation will be immediate and prompt to enter again.

Below is something I notice when I doesn't enter any value, I'm wondering how can I provide more validation rule.

Thanks in advance.

Body:
Create a Validator instance and setup your corresponding rules.

https://laravel.com/api/5.4/Illuminate/Contracts/Validation/Validator.html

Specifically, see the make() method.

https://laravel.com/api/5.4/Illuminate/Contracts/Validation/Factory.html

public function handle()
{
    $name = $this->ask('Enter name ');
    $validator = \Validator::make(['name' => $name], ['name' => 'required|string']);
    if ($validator->fails()) {
        $message = $validator->messages();
    }
    $email = $this->ask('Enter email ');
    $validator = \Validator::make(['email' => $email], ['email' => 'required|email']);
    if ($validator->fails()) {
        $message = $validator->messages();
    }
    $date = $this->ask('Enter date [Eg: 2016-01-01 00:00:00] ');
    $validator = \Validator::make(['date' => $date], ['date' => 'required|datetime']);
    if ($validator->fails()) {
        $message = $validator->messages();
    }

    // so something with $message
}


问:
How to implement FFT algorithm in python?
I am trying to implement a function in python3, but I couldn't figure out the error in the argument.Following is my code and the error:

```<code>def FFT1(A,n,w):

    if n==1:
        return A
    AEven=[]
    for k in range(0,n,2):
        key1= A[k]
        AEven.append(key1)
    AOdd=[]
    for l in range(1,n,2):
        key2=A[l]
        AOdd.append(key2)
    VE=FFT1(AEven, n/2, w**2)
    VO=FFT1(AOdd, n/2, w**2)
    mult= complex(-1,1)
    V=[]*n
    for i in range(0,(n-2)/2):
        V[i]=VE[i]+(w**mult)*VO[i]
        V[n/2+i]=VE[i]-(w**mult)*VO[i]
    return V

FFT1(coeff, degree, rootunit)
</code>```

causes:

```<code>Traceback (most recent call last):
  File "<pyshell#45>", line 1, in <module>
    FFT1(coeff, degree, rootunit)
  File "<pyshell#44>", line 12, in FFT1
    VE=FFT1(AEven, n/2, w**2)
  File "<pyshell#44>", line 5, in FFT1
    for k in range(0,n,2):
TypeError: 'float' object cannot be interpreted as an integer
</code>```

答: Change n to int(n) within range if n has to remain a float. If n can be an int, call the recursive functions with n//2 and not n/2

Body:
I am trying to implement a function in python3, but I couldn't figure out the error in the argument.Following is my code and the error:

def FFT1(A,n,w):

    if n==1:
        return A
    AEven=[]
    for k in range(0,n,2):
        key1= A[k]
        AEven.append(key1)
    AOdd=[]
    for l in range(1,n,2):
        key2=A[l]
        AOdd.append(key2)
    VE=FFT1(AEven, n/2, w**2)
    VO=FFT1(AOdd, n/2, w**2)
    mult= complex(-1,1)
    V=[]*n
    for i in range(0,(n-2)/2):
        V[i]=VE[i]+(w**mult)*VO[i]
        V[n/2+i]=VE[i]-(w**mult)*VO[i]
    return V

FFT1(coeff, degree, rootunit)

causes:

Traceback (most recent call last):
  File "<pyshell#45>", line 1, in <module>
    FFT1(coeff, degree, rootunit)
  File "<pyshell#44>", line 12, in FFT1
    VE=FFT1(AEven, n/2, w**2)
  File "<pyshell#44>", line 5, in FFT1
    for k in range(0,n,2):
TypeError: 'float' object cannot be interpreted as an integer


问:
C#.NET Getting User Name of machine using Windows Service
I am having difficulty getting the User Name of a person logged into a machine using a windows service.

When using both System.Environment.UserName or WindowsIdentity.GetCurrent().UserName I get NTAUTHORITY\SYSTEM but when this application gets pushed I need to be able to map to the UserID of the person logged in to the system.  The operating system this will be used on will be Windows XP.

Any help would be very appreciated.

答:
Try this:</p>

```<code>var connectionOptions = new ConnectionOptions();
var scope = new System.Management.ManagementScope("\\\\localhost", connectionOptions);
var query = new System.Management.ObjectQuery("select * from Win32_ComputerSystem");
var searcher = new ManagementObjectSearcher(scope, query);
foreach (var row in searcher.Get())
{
    Console.WriteLine(row["UserName"].ToString().ToLower());
}
</code>```

ContentLicense: CC BY-SA 2.5

Body:
Try this:

var connectionOptions = new ConnectionOptions();
var scope = new System.Management.ManagementScope("\\\\localhost", connectionOptions);
var query = new System.Management.ObjectQuery("select * from Win32_ComputerSystem");
var searcher = new ManagementObjectSearcher(scope, query);
foreach (var row in searcher.Get())
{
    Console.WriteLine(row["UserName"].ToString().ToLower());
}


问:
How to redraw or refresh in OnRender?
I want to draw something dynamically. Following code shows my OnRender. I'm setting DrawItem somewhere in my program where I need it. But when I'm calling DrawItem =5; what do I have to call, so that OnRender gets called?

```<code>protected override void OnRender(DrawingContext drawingContext)
{
    switch (DrawItem)
    {
        case 1:
            //Draw Item
            break;
        case 2:
            //Draw Item
            break;
        case 3:
            //Draw Item
            break;
        case 4:
            //Draw Item
            break;
        case 5:
            //Draw Item
            break;
    }
    base.OnRender(drawingContext)
}

public int DrawItem { get; set; }
</code>```

答:
If the size of your control changes, you can use InvalidateVisual(), however keep in mind this causes a fairly expensive re-layout of your UI. If the size of your control is staying the same, you shouldn't call InvalidateVisual().

A more efficient way to update your UI is to create a DrawingGroup "backing store" and add it to the DrawingContext during OnRender(). You can then update it whenever you like, using DrawingGroup.Open(), and WPF will update your UI.

If this sounds confusing, remember that WPF is a retained drawing system. That means OnRender() might better be called AccumulateDrawingObjects(). It's actually accumulating a tree of live drawing objects, some of which (like DrawingGroup, RenderTargetBitmap, and WriteableBitmap) can be updated later.

This is what it looks like:

```<code>DrawingGroup backingStore = new DrawingGroup();

protected override void OnRender(DrawingContext drawingContext) {
    base.OnRender(drawingContext);

    Render(); // put content into our backingStore
    drawingContext.DrawDrawing(backingStore);
}

// I can call this anytime, and it'll update my visual drawing
// without ever triggering layout or OnRender()
private void Render() {
    var drawingContext = backingStore.Open();
    Render(drawingContext);
    drawingContext.Close();
}
</code>```

Title: How to redraw or refresh in OnRender?

Body:
I want to draw something dynamically. Following code shows my OnRender. I'm setting DrawItem somewhere in my program where I need it. But when I'm calling DrawItem =5; what do I have to call, so that OnRender gets called?

protected override void OnRender(DrawingContext drawingContext)
{
    switch (DrawItem)
    {
        case 1:
            //Draw Item
            break;
        case 2:
            //Draw Item
            break;
        case 3:
            //Draw Item
            break;
        case 4:
            //Draw Item
            break;
        case 5:
            //Draw Item
            break;
    }
    base.OnRender(drawingContext)
}

public int DrawItem { get; set; }

Body:
If the size of your control changes, you can use InvalidateVisual(), however keep in mind this causes a fairly expensive re-layout of your UI. If the size of your control is staying the same, you shouldn't call InvalidateVisual().

A more efficient way to update your UI is to create a DrawingGroup "backing store" and add it to the DrawingContext during OnRender(). You can then update it whenever you like, using DrawingGroup.Open(), and WPF will update your UI.

If this sounds confusing, remember that WPF is a retained drawing system. That means OnRender() might better be called AccumulateDrawingObjects(). It's actually accumulating a tree of live drawing objects, some of which (like DrawingGroup, RenderTargetBitmap, and WriteableBitmap) can be updated later.

This is what it looks like:

DrawingGroup backingStore = new DrawingGroup();

protected override void OnRender(DrawingContext drawingContext) {
    base.OnRender(drawingContext);

    Render(); // put content into our backingStore
    drawingContext.DrawDrawing(backingStore);
}

// I can call this anytime, and it'll update my visual drawing
// without ever triggering layout or OnRender()
private void Render() {
    var drawingContext = backingStore.Open();
    Render(drawingContext);
    drawingContext.Close();
}


问:
Adding option in launching option of eclipse .product file to suppress SVN process
I am developing eclipse application which consists of svn plugins also. On launching my application it process for SVN Update Cache in background whose indication is shown in bottom right corner of my application. Manually I can change the the SVN settings from Preference > Team > SVN. But I want to do it during building/launching my application.

There is tab in application's .product file under Launching tab where I can add VM arguments.
I want to add following entries under that:

```<code>org.eclipse.team.svn.ui/preference.decoration.compute.deep=false
org.eclipse.team.svn.ui/preference.decoration.precise.enablements=false
org.eclipse.team.svn.ui/preference.decoration.enable.cache=false
org.eclipse.team.svn.ui/preference.decoration.enable.persistent.ssh=false
</code>```

When I added these under VM arguments, it is throwing error during launching of applcation:

```<code>Error: Could not find or load main class org.eclipse.team.svn.ui.preference.decoration.compute.deep=false
</code>```

How should i add these entries?

答:
VM arguments that are for system properties follow the syntax shown at http://docs.oracle.com/javase/7/docs/technotes/tools/windows/java.html :

-Dproperty=value

Sets a system property value.

```<code>If value is a string that contains spaces, then you must enclose the string
in double quotation marks:

java -Dmydir="some string" SomeClass
</code>```

So try (because, remember, there are other kinds of VM arguments):

```<code>-Dorg.eclipse.team.svn.ui/preference.decoration.compute.deep=false
-Dorg.eclipse.team.svn.ui/preference.decoration.precise.enablements=false
-Dorg.eclipse.team.svn.ui/preference.decoration.enable.cache=false
-Dorg.eclipse.team.svn.ui/preference.decoration.enable.persistent.ssh=false
</code>```

Body:
I am developing eclipse application which consists of svn plugins also. On launching my application it process for SVN Update Cache in background whose indication is shown in bottom right corner of my application. Manually I can change the the SVN settings from Preference > Team > SVN. But I want to do it during building/launching my application.

There is tab in application's .product file under Launching tab where I can add VM arguments.
I want to add following entries under that:

org.eclipse.team.svn.ui/preference.decoration.compute.deep=false
org.eclipse.team.svn.ui/preference.decoration.precise.enablements=false
org.eclipse.team.svn.ui/preference.decoration.enable.cache=false
org.eclipse.team.svn.ui/preference.decoration.enable.persistent.ssh=false

When I added these under VM arguments, it is throwing error during launching of applcation:

Error: Could not find or load main class org.eclipse.team.svn.ui.preference.decoration.compute.deep=false

How should i add these entries?

Body:
VM arguments that are for system properties follow the syntax shown at http://docs.oracle.com/javase/7/docs/technotes/tools/windows/java.html :

-Dproperty=value

Sets a system property value.

If value is a string that contains spaces, then you must enclose the string
in double quotation marks:

java -Dmydir="some string" SomeClass

So try (because, remember, there are other kinds of VM arguments):

-Dorg.eclipse.team.svn.ui/preference.decoration.compute.deep=false
-Dorg.eclipse.team.svn.ui/preference.decoration.precise.enablements=false
-Dorg.eclipse.team.svn.ui/preference.decoration.enable.cache=false
-Dorg.eclipse.team.svn.ui/preference.decoration.enable.persistent.ssh=false


问:
what is the data type that i want to use when merging Array when i merge String array and Integer Array into merge Array
I have an String Array and Integer Array,

```<code>String[] strArray={"a","b","c"};
Integer[] intArray={1,2,3};
</code>```

I want two merge them into another array.What is the data type of merge Array?and how i implement merge Array?

答:
You can use System.arraycopy();

```<code>String[] strArray={"a","b","c"};
Integer[] intArray={1,2,3};
Object[] objArray = new Object[strArray.length + intArray.length];

System.arraycopy( strArray, 0, objArray, 0, strArray.length );
System.arraycopy( intArray, 0, objArray, strArray.length, intArray.length );
</code>```

Rather than type Object, you can change to desired type like String.

Body:
I have an String Array and Integer Array,

String[] strArray={"a","b","c"};
Integer[] intArray={1,2,3};

I want two merge them into another array.What is the data type of merge Array?and how i implement merge Array?

Body:
You can use System.arraycopy();

String[] strArray={"a","b","c"};
Integer[] intArray={1,2,3};
Object[] objArray = new Object[strArray.length + intArray.length];

System.arraycopy( strArray, 0, objArray, 0, strArray.length );
System.arraycopy( intArray, 0, objArray, strArray.length, intArray.length );

Rather than type Object, you can change to desired type like String.


问:
div size increases after drag and drop
Here is my jsfiddle: My fiddle

After I drag and drop the "rule/event" class to "layout" class, I want the size of "rule/event" to be the same as in "rule-body/event-body" class.

It is multiplying in size when dropped into the "layout" class.

Is it because "rule-body/event-body" and "layout" classes have heights in different percentages(%)?

```<code>.rule-body, .event-body{
    height: 85%;
    margin-top: 5%;
    overflow-y: scroll;
}

.layout{
    height: 100%;
    background-color: #ececec;
}
</code>```

What is the fix for this?

Any help would be much appreciated. Thanks!

答:
Since you are using height: 8%; width: 50%; those rules are related to the parent height/width, after drag and drop the parent changed, therefore, you have a different result of height/width.

Use fixed width/height or use vw/vh

Solution:  https://jsfiddle.net/dalinhuang/0tdnmghr/

```<code>.rule{
    height: 25px;
    width: 100px;
    background-color: #aaa;
    text-align: center;
    margin-bottom: 5%;
    border: 1px solid black;
}
.event {
    height: 25px;
    width: 100px;
    background-color: #aaa;
    text-align: center;
    margin-bottom: 5%;
    border: 1px solid black;
}
</code>```

Title: div size increases after drag and drop

Body:
Here is my jsfiddle: My fiddle

After I drag and drop the "rule/event" class to "layout" class, I want the size of "rule/event" to be the same as in "rule-body/event-body" class.

It is multiplying in size when dropped into the "layout" class.

Is it because "rule-body/event-body" and "layout" classes have heights in different percentages(%)?

.rule-body, .event-body{
    height: 85%;
    margin-top: 5%;
    overflow-y: scroll;
}

.layout{
    height: 100%;
    background-color: #ececec;
}

What is the fix for this?

Any help would be much appreciated. Thanks!

Body:
Since you are using height: 8%; width: 50%; those rules are related to the parent height/width, after drag and drop the parent changed, therefore, you have a different result of height/width.

Use fixed width/height or use vw/vh

Solution:  https://jsfiddle.net/dalinhuang/0tdnmghr/

.rule{
    height: 25px;
    width: 100px;
    background-color: #aaa;
    text-align: center;
    margin-bottom: 5%;
    border: 1px solid black;
}
.event {
    height: 25px;
    width: 100px;
    background-color: #aaa;
    text-align: center;
    margin-bottom: 5%;
    border: 1px solid black;
}


问:
Insert Array of values into columns of the table in SQL Server
I have an array

```<code>(1,2,3,4;5,6,7,8;9,10,11,12;13,14,15,16;)
</code>```

I want to insert this array of values into the table like

```<code>Column1 |  Column2 | Column3 | Column4
-----------------------------------------
    1   |   2      |   3     |    4
    5   |   6      |   7     |    8
    9   |  10      |  11     |   12
   13   |  14      |  15     |   16
</code>```

Body:
I have an array

(1,2,3,4;5,6,7,8;9,10,11,12;13,14,15,16;)

I want to insert this array of values into the table like

Column1 |  Column2 | Column3 | Column4
-----------------------------------------
    1   |   2      |   3     |    4
    5   |   6      |   7     |    8
    9   |  10      |  11     |   12
   13   |  14      |  15     |   16

Body:
Try this:

INSERT INTO TableName (Column1,Column2,Column3,Column4)
VALUES (1,2,3,4),(5,6,7,8),(9,10,11,12),(13,14,15,16)


问:
Can I use reserved word as parameter of a function in javascript?
```<code>var myName = 'John';
function greet(name) {
  console.log('Hello, ' + name);
}
greet(myName);
</code>```

Here I'm using 'name' as a parameter of the greet(). Since we know that we can't use javascript reserved word as a variable name, could we use them as the param? Or are they restricted for anywhere in the script to be used as an identifier?

Thanks in advance :)

答:
You cannot use reserved keywords for any purpose other than how they are intended in the grammar of JavaScript. That is, they cannot be used as identifiers anywhere, even as property names in object literals, they must be escaped with quotes.

Here is a list of reserved keywords as of ECMAScript 2015:

break

case

catch

class

const

continue

debugger

default

delete

do

else

export

extends

finally

for

function

if

import

in

instanceof

new

return

super

switch

this

throw

try

typeof

var

void

while

with

yield

Body:
var myName = 'John';
function greet(name) {
  console.log('Hello, ' + name);
}
greet(myName);

Here I'm using 'name' as a parameter of the greet(). Since we know that we can't use javascript reserved word as a variable name, could we use them as the param? Or are they restricted for anywhere in the script to be used as an identifier?

Thanks in advance :)


问:
Windows Phone 7 sniffer
Does any know some good http (at least) sniffer which works under Windows Phone 7 OS?
Currently I use wireshark/fiddler + windows phone 7 emulator for testing, but anyway I want to test my app using real phone + some win 7 phone sniffer too.
I'll appreciate any help.</p>

答: The current Windows Phone platform SDK does not expose access to the network stack or the radio interface at all, so in the current incarnation there is no way to create a sniffer for the platform.</p>

Title: Windows Phone 7 sniffer


问:
How do I Add http headers to Robot Franework script?
I am writing a Robot Framework script and need to setup an ADD header and a MODIFY header in the robot script.
I am using the library httplibrary.http and using the keywords Setup Request Header within the Test Case section as below.

```<code>Set Request Header  ${HeaderName}    ${HeaderValue}
Set Request Header  ${HeaderName1}   ${HeaderValue1}
</code>```

I asked someone who mentioned that i need to define the variables within robot but am uncertain how to.

I have these setup in Chrome and Firefox using the Modify headers extensions as with following values.

```<code>Add      bypassblockingtbbmicrosite              true
Modify   X-Akamai-Edgescape                      country_code=CA
</code>```

答:
First, you need to set header then create http context and then you can make get/post call as per your requirement.

For example:

```<code>set request header  bypassblockingtbbmicrosite  true
set request header  X-Akamai-Edgescape  country_code=CA
Create Http Context google.com  http
get [url]
</code>```

Body:
I am writing a Robot Framework script and need to setup an ADD header and a MODIFY header in the robot script.
I am using the library httplibrary.http and using the keywords Setup Request Header within the Test Case section as below.

Set Request Header  ${HeaderName}    ${HeaderValue}
Set Request Header  ${HeaderName1}   ${HeaderValue1}

I asked someone who mentioned that i need to define the variables within robot but am uncertain how to.

I have these setup in Chrome and Firefox using the Modify headers extensions as with following values.

Add      bypassblockingtbbmicrosite              true
Modify   X-Akamai-Edgescape                      country_code=CA

Body:
First, you need to set header then create http context and then you can make get/post call as per your requirement.

For example:

set request header  bypassblockingtbbmicrosite  true
set request header  X-Akamai-Edgescape  country_code=CA
Create Http Context google.com  http
get [url]


问:
.htaccess for one url only
I am trying to redirect one specific url, let's say /admin, from my domain to http, while the others all should redirect to https. Example:

```<code>Works:

http://example.com -> https://example.com
http://example.com/with-url -> https://example.com/with-url
https://example.com/admin -> http://example.com/admin

Does not work:

What I get (redirects from https to http, if under /admin):
    https://example.com/admin/anything-below-here -> http://example.com/admin/anything-below-here

What I want (to stay on https):
    https://example.com/admin/anything-below-here -> https://example.com/admin/anything-below-here
</code>```

This is what I got so far:

```<code>RewriteEngine On

# force https:// for all except /admin
RewriteCond %{HTTPS} off
RewriteCond %{THE_REQUEST} !/admin [NC]
RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

# force http:// for /admin URLs
RewriteCond %{HTTPS} on
RewriteCond %{THE_REQUEST} /admin [NC]
RewriteRule ^ http://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

# all the others
RewriteBase /
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php?/$1 [L]
</code>```

Could anyone tell me what I am missing here? Thanks a lot!

答:
Your regexp is greedy, so /admin/something matches /admin, hence the redirect from https to http once inside admin.

Try using /admin[/]*$ instead to specify only /admin and /admin/ should redirect to http, but not /admin/something

In order to check that the actual request URI ends after admin, you'll also need to switch to %{REQUEST_URI} instead of %{THE_REQUEST} which contains data AFTER the URI (for example, HTTP/1.1).

Try that:

```<code>RewriteCond %{REQUEST_URI} ^/admin[/]*$ [NC]
</code>```

You don't need to change the other one check if /admin is not in %{THE_REQUEST} as it remains valid.

The complete code would then look like:

```<code># force https:// for all except /admin
RewriteCond %{HTTPS} off
RewriteCond %{REQUEST_URI} !^/admin[/]*$ [NC]
RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

# force http:// for /admin URLs
RewriteCond %{HTTPS} on
RewriteCond %{REQUEST_URI} ^/admin[/]*$ [NC]
RewriteRule ^ http://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

# all the others
RewriteBase /
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php?/$1 [L]
</code>```

Title: .htaccess for one url only

Body:
I am trying to redirect one specific url, let's say /admin, from my domain to http, while the others all should redirect to https. Example:

Works:

http://example.com -> https://example.com
http://example.com/with-url -> https://example.com/with-url
https://example.com/admin -> http://example.com/admin

Does not work:

What I get (redirects from https to http, if under /admin):
    https://example.com/admin/anything-below-here -> http://example.com/admin/anything-below-here

What I want (to stay on https):
    https://example.com/admin/anything-below-here -> https://example.com/admin/anything-below-here

This is what I got so far:

RewriteEngine On

# force https:// for all except /admin
RewriteCond %{HTTPS} off
RewriteCond %{THE_REQUEST} !/admin [NC]
RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

# force http:// for /admin URLs
RewriteCond %{HTTPS} on
RewriteCond %{THE_REQUEST} /admin [NC]
RewriteRule ^ http://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

# all the others
RewriteBase /
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php?/$1 [L]

Could anyone tell me what I am missing here? Thanks a lot!

Body:
Your regexp is greedy, so /admin/something matches /admin, hence the redirect from https to http once inside admin.

Try using /admin[/]*$ instead to specify only /admin and /admin/ should redirect to http, but not /admin/something

In order to check that the actual request URI ends after admin, you'll also need to switch to %{REQUEST_URI} instead of %{THE_REQUEST} which contains data AFTER the URI (for example, HTTP/1.1).

Try that:

RewriteCond %{REQUEST_URI} ^/admin[/]*$ [NC]

You don't need to change the other one check if /admin is not in %{THE_REQUEST} as it remains valid.

The complete code would then look like:

# force https:// for all except /admin
RewriteCond %{HTTPS} off
RewriteCond %{REQUEST_URI} !^/admin[/]*$ [NC]
RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

# force http:// for /admin URLs
RewriteCond %{HTTPS} on
RewriteCond %{REQUEST_URI} ^/admin[/]*$ [NC]
RewriteRule ^ http://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

# all the others
RewriteBase /
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php?/$1 [L]


问:
Groovy Execute Bash Script in Jenkins
I am trying to run a bash script from Groovy in Jenkins but I am not able to find the lucky commands.

I can run this and it creates my "RJ" directory:

```<code>process = "mkdir /app/jenkins/workspace/TEST/RJ"
println process.execute()
</code>```

But when I try to run my bash it is not creating my output file.  I am able to run this bash script on the server directly and it is creating my expected output file.

```<code>process = "/app/jenkins/workspace/TEST/info_file.sh"
println process.execute()
</code>```

答:
why run it through groovy and not directly via a ssh command. </p>

<p>If you do want to do via groovy, you'll need to add a ssh libray, and do the whole connection, auth, execute. process.execute won't run a linux box. </p>

Title: Groovy Execute Bash Script in Jenkins

Body:
I am trying to run a bash script from Groovy in Jenkins but I am not able to find the lucky commands.

I can run this and it creates my "RJ" directory:

process = "mkdir /app/jenkins/workspace/TEST/RJ"
println process.execute()

But when I try to run my bash it is not creating my output file.  I am able to run this bash script on the server directly and it is creating my expected output file.

process = "/app/jenkins/workspace/TEST/info_file.sh"
println process.execute()

Body:
why run it through groovy and not directly via a ssh command.

If you do want to do via groovy, you'll need to add a ssh libray, and do the whole connection, auth, execute. process.execute won't run a linux box.


问:
need flexbox children to display normally
How to make flexbox children behave like the bad children they are.  This means their default layout.</p>

```<code>.wrapper {
  this is the row
}
.column {
  all equal heights
  display:flex;
}
.child {
  back to normal display....uneven heights and widths.  Currently it seems like the children want to display as flex (equal heights) also.
}
</code>```

答:
Since you posted no HTML markup I'm going to assume the structure you have is similar to this:

```<code><div class="wrapper">
    <div class="column">
        <div class="child"></div>
    </div>
    <div class="column">
        <div class="child"></div>
    </div>
</div><!-- /.wrapper -->
</code>```

In your example, it makes sense that the .child elements are displaying as flex items, because their parent, in this case .column, is set to display flex. What you are probably after is setting the .wrapper to display flex, so the .column is the flex child.

Something like this:
https://jsfiddle.net/disinfor/rd2npn4v/

The first example in the fiddle is what you have, and the second is setting the .wrapper to display flex.

Hopefully this is what you are looking for.

Body:
How to make flexbox children behave like the bad children they are.  This means their default layout.

.wrapper {
  this is the row
}
.column {
  all equal heights
  display:flex;
}
.child {
  back to normal display....uneven heights and widths.  Currently it seems like the children want to display as flex (equal heights) also.
}

Body:
Since you posted no HTML markup I'm going to assume the structure you have is similar to this:

<div class="wrapper">
    <div class="column">
        <div class="child"></div>
    </div>
    <div class="column">
        <div class="child"></div>
    </div>
</div><!-- /.wrapper -->

In your example, it makes sense that the .child elements are displaying as flex items, because their parent, in this case .column, is set to display flex. What you are probably after is setting the .wrapper to display flex, so the .column is the flex child.

Something like this:
https://jsfiddle.net/disinfor/rd2npn4v/

The first example in the fiddle is what you have, and the second is setting the .wrapper to display flex.

Hopefully this is what you are looking for.


问:
Check if Timer is running
I have been trying to refill in game lives with a timer, but whenever I leave a view and return, the timer duplicates and becomes faster. I have tried to address this with the Timer?.isValid function to only run the timer when it is invalid so it never duplicates, but it cannot seem to check is the timer is invalid in an if statement.

This is the if statement that I have been using so far:

```<code>if (myTimer?.isValid){
} else{
//start timer
}
</code>```

Any help would be appreciated, thanks.

答:
I recommend to use self-checking startTimer() and stopTimer() functions, the timer will be started only if it's not currently running, the stop function sets the timer variable reliably to nil.

```<code>var timer : Timer?

func startTimer()
{
    if timer == nil {
        timer = Timer.scheduledTimer...
    }
}

func stopTimer()
{
    if timer != nil {
       timer!.invalidate()
       timer = nil
    }
}
</code>```

Title: Check if Timer is running

Body:
I have been trying to refill in game lives with a timer, but whenever I leave a view and return, the timer duplicates and becomes faster. I have tried to address this with the Timer?.isValid function to only run the timer when it is invalid so it never duplicates, but it cannot seem to check is the timer is invalid in an if statement.

This is the if statement that I have been using so far:

if (myTimer?.isValid){
} else{
//start timer
}

Any help would be appreciated, thanks.

Body:
I recommend to use self-checking startTimer() and stopTimer() functions, the timer will be started only if it's not currently running, the stop function sets the timer variable reliably to nil.

var timer : Timer?

func startTimer()
{
    if timer == nil {
        timer = Timer.scheduledTimer...
    }
}

func stopTimer()
{
    if timer != nil {
       timer!.invalidate()
       timer = nil
    }
}


答:
Please check here for a list of JavaScript reserved words: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Lexical_grammar#keywords

You cannot use reserved words for  variables, functions, methods, or object identifiers. Function parameters will be treated as variables inside its function, hence it cannot be used.

Title: Can I use reserved word as parameter of a function in javascript?

ContentLicense: CC BY-SA 4.0


问:
How to store a list in a db column
I would like to store an object FOO in a database.
Lets say FOO contains three integers and a list of "Fruits".

The list can have any length, the only thing I know is that the all the fruits allowed are stored in another table.

Can I store the fruit list in a column?

答:
In a normalized relational database, such a situation is unacceptable. You should have a junction table that stores one row for each distinct ID of the FOO object and the ID of the Fruit. Existence of such a row means the fruit is in that list for the FOO.

```<code>CREATE TABLE FOO (
  id int primary key not null,
  int1 int,
  int2 int,
  int3 int
)

CREATE TABLE Fruits (
  id int primary key not null,
  name varchar(30)
)

CREATE TABLE FOOFruits (
  FruitID int references Fruits (ID),
  FooID int references FOO(id),
  constraint pk_FooFruits primary key (FruitID, FooID)
)
</code>```

To add Apple fruit to the list of a specific FOO object with ID=5, you would:

```<code>INSERT FOOFruits(FooID, FruitID)
SELECT 5, ID FROM Fruits WHERE name = 'Apple'
</code>```

OwnerDisplayName: Stumproot

Title: How to store a list in a db column

Body:
In a normalized relational database, such a situation is unacceptable. You should have a junction table that stores one row for each distinct ID of the FOO object and the ID of the Fruit. Existence of such a row means the fruit is in that list for the FOO.

CREATE TABLE FOO (
  id int primary key not null,
  int1 int,
  int2 int,
  int3 int
)

CREATE TABLE Fruits (
  id int primary key not null,
  name varchar(30)
)

CREATE TABLE FOOFruits (
  FruitID int references Fruits (ID),
  FooID int references FOO(id),
  constraint pk_FooFruits primary key (FruitID, FooID)
)

To add Apple fruit to the list of a specific FOO object with ID=5, you would:

INSERT FOOFruits(FooID, FruitID)
SELECT 5, ID FROM Fruits WHERE name = 'Apple'

OwnerDisplayName: Mehrdad Afshari

LastEditorDisplayName: Mehrdad Afshari


问:
Phalcon View not found exception
I have recently upgraded phalcon from 2.0.10 to 3.1.2 and PHP to version 7. Everything worked well before but seems its now broken after the upgrade

In index.php, i have set the partial directory like this-

```<code> $di->set('partials', function() {
     $partials = new View();
     $partials->setPartialsDir('../apps/common/views/');
     return $partials;
 });
</code>```

And in index.phtml, the partial is called like this

```<code>$this->partials->partial("header");
</code>```

header.phtml exist in ../apps/common/views directory.

When I run the site, it gives following error.

Fatal error: Uncaught Phalcon\Mvc\View\Exception: View
  '../apps/common/views/header' was not found in any of the views
  directory in
  D:\server\www\booktickets.com\frontend\apps\modules\books\views\index.phtml

The partial header.phtml is partial directory. Can anybody shed light on this??

答:
Finally I found the solution

I have to changed my code to -

```<code>$di->set('partials', function() {
    $partials = new View();
    $partials->setViewsDir('../apps/common/views'); // absolute path to views dir
    $partials->setPartialsDir('./'); // relative path to partials dir within
    return $partials;
 });
</code>```

I got an answer from offical phalcon forum. Here is the link

Title: Phalcon View not found exception

Body:
I have recently upgraded phalcon from 2.0.10 to 3.1.2 and PHP to version 7. Everything worked well before but seems its now broken after the upgrade

In index.php, i have set the partial directory like this-

 $di->set('partials', function() {
     $partials = new View();
     $partials->setPartialsDir('../apps/common/views/');
     return $partials;
 });

And in index.phtml, the partial is called like this

$this->partials->partial("header");

header.phtml exist in ../apps/common/views directory.

When I run the site, it gives following error.

Fatal error: Uncaught Phalcon\Mvc\View\Exception: View
  '../apps/common/views/header' was not found in any of the views
  directory in
  D:\server\www\booktickets.com\frontend\apps\modules\books\views\index.phtml

The partial header.phtml is partial directory. Can anybody shed light on this??

Body:
Finally I found the solution

I have to changed my code to -

$di->set('partials', function() {
    $partials = new View();
    $partials->setViewsDir('../apps/common/views'); // absolute path to views dir
    $partials->setPartialsDir('./'); // relative path to partials dir within
    return $partials;
 });

I got an answer from offical phalcon forum. Here is the link


答:
It is not possible to join two arrays of difference types. But I want to recommend you to use instances java.util.ArrayList instead of array. For example you can join these two different arrays.</p>

```<code>ArrayList<Character> strArr= new ArrayList<Character>();
strArr.add(new Character('a'));
strArr.add(new Character('b'));
strArr.add(new Character('c'));
ArrayList<Character> intArr= new ArrayList<Character>();
intArr.add(new Character('1'));
intArr.add(new Character('2'));
intArr.add(new Character('3'));
//merge two arrays
strArr.addAll(intArr);
</code>```

Title: what is the data type that i want to use when merging Array when i merge String array and Integer Array into merge Array

Body:
I have an String Array and Integer Array,

String[] strArray={"a","b","c"};
Integer[] intArray={1,2,3};

I want two merge them into another array.What is the data type of merge Array?and how i implement merge Array?

Body:
It is not possible to join two arrays of difference types. But I want to recommend you to use instances java.util.ArrayList instead of array. For example you can join these two different arrays.

ArrayList<Character> strArr= new ArrayList<Character>();
strArr.add(new Character('a'));
strArr.add(new Character('b'));
strArr.add(new Character('c'));
ArrayList<Character> intArr= new ArrayList<Character>();
intArr.add(new Character('1'));
intArr.add(new Character('2'));
intArr.add(new Character('3'));
//merge two arrays
strArr.addAll(intArr);


问:
Autowired class from the jar file outside the classes
How can the Class in a jar file get scanned by the <context:component-scan base-package="" />. I am getting the below error for my autowired class.

SEVERE [localhost-startStop-1] org.apache.catalina.core.ApplicationContext.log StandardWrapper.Throwable
 org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'myController': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: org.quartz.Scheduler com.path.controller.MyController.scheduler; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [org.quartz.Scheduler] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}

code:

```<code>package com.path.controller;
import org.quartz.Scheduler;

@Controller
public class MyController{

   @Autowired
   Scheduler scheduler;
}
</code>```

This scheduler is inside the jar file quartz-oracle-2.1.6.jar and is under WEB-INF\lib. This lib is outside the classes folder of the deployment package. In the applicationcontext.xml i have the below entry,

<context:component-scan base-package="com.path" />

答: When you export the jar file using the export utility in eclipse there is a option called Add directory entries. Check this option and export the jar file, this will solve the problem</p>

Body:
How can the Class in a jar file get scanned by the <context:component-scan base-package="" />. I am getting the below error for my autowired class.

SEVERE [localhost-startStop-1] org.apache.catalina.core.ApplicationContext.log StandardWrapper.Throwable
 org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'myController': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: org.quartz.Scheduler com.path.controller.MyController.scheduler; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [org.quartz.Scheduler] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}

code:

package com.path.controller;
import org.quartz.Scheduler;

@Controller
public class MyController{

   @Autowired
   Scheduler scheduler;
}

This scheduler is inside the jar file quartz-oracle-2.1.6.jar and is under WEB-INF\lib. This lib is outside the classes folder of the deployment package. In the applicationcontext.xml i have the below entry,

<context:component-scan base-package="com.path" />


问:
CSVHelper mandatory fields
When parsing a csv file, how do i define that a specific field is mandatory. Essentially, I want to make sure that a given field is never empty, and if it is then I would like an exception thrown. Here is the mapping class:

```<code>public sealed class DataMapper : CsvClassMap<DataType>
{
    public DataMapper()
    {
        Map(m => m.Field1).Name("FirstField");
        Map(m => m.Field2).Name("SecondField");
        Map(m => m.Field3).Name("ThirdField"); // this field should be mandatory
    }
}
</code>```

and the usage:

```<code>List<DataType> data;
using (var sr = new StreamReader(localFilePath))
{
    var reader = new CsvReader(sr);
    reader.Configuration.RegisterClassMap<DataMapper>();
    data = reader.GetRecords<DataType>().ToList();
}
</code>```

Currently I am just checking the results in the data list as follows:

```<code>var numberOfInvalidRecords = data.Count(data => string.IsNullOrEmpty(data.Field3));
if (nullAccountHolderRecords > 0)
{
    //handle
}
</code>```

I was unable to find a built-in feature in the CSVHelper documentation. Am I missing something?

答:
Here is a solution that extends the API:

```<code>public static class CsvHelperExtensions
{
    public static CsvPropertyMap Required<T>(this CsvPropertyMap map, string columnName)
    {
        return map.Name(columnName).ConvertUsing(row =>
        {
            if (string.IsNullOrEmpty(row.GetField(columnName)))
                throw new CsvParserException($"{columnName} is required, but missing from row {row.Row}");
            return row.GetField<T>(columnName);
        });
    }
}
</code>```

Usage:

```<code>public CsvPersonMap()
{
    Map(m => m.FirstName).Required<string>("First");
    Map(m => m.LastName).Name("Last");
    Map(m => m.MiddleName).Required<string>("Middle");
}
</code>```

Title: CSVHelper mandatory fields

Body:
When parsing a csv file, how do i define that a specific field is mandatory. Essentially, I want to make sure that a given field is never empty, and if it is then I would like an exception thrown. Here is the mapping class:

public sealed class DataMapper : CsvClassMap<DataType>
{
    public DataMapper()
    {
        Map(m => m.Field1).Name("FirstField");
        Map(m => m.Field2).Name("SecondField");
        Map(m => m.Field3).Name("ThirdField"); // this field should be mandatory
    }
}

and the usage:

List<DataType> data;
using (var sr = new StreamReader(localFilePath))
{
    var reader = new CsvReader(sr);
    reader.Configuration.RegisterClassMap<DataMapper>();
    data = reader.GetRecords<DataType>().ToList();
}

Currently I am just checking the results in the data list as follows:

var numberOfInvalidRecords = data.Count(data => string.IsNullOrEmpty(data.Field3));
if (nullAccountHolderRecords > 0)
{
    //handle
}

I was unable to find a built-in feature in the CSVHelper documentation. Am I missing something?

Body:
Here is a solution that extends the API:

public static class CsvHelperExtensions
{
    public static CsvPropertyMap Required<T>(this CsvPropertyMap map, string columnName)
    {
        return map.Name(columnName).ConvertUsing(row =>
        {
            if (string.IsNullOrEmpty(row.GetField(columnName)))
                throw new CsvParserException($"{columnName} is required, but missing from row {row.Row}");
            return row.GetField<T>(columnName);
        });
    }
}

Usage:

public CsvPersonMap()
{
    Map(m => m.FirstName).Required<string>("First");
    Map(m => m.LastName).Name("Last");
    Map(m => m.MiddleName).Required<string>("Middle");
}


问:
Quickblox login is not working using 3.3.1 sdk
I have integrated QuickBlox, everything is working fine, suddenly I am getting this error. I have tried to get why it is coming but didn't get any solution.

My code:

```<code>ChatHelper.getInstance().login(user, new QBEntityCallback<Void>() {
            @Override
            public void onSuccess(Void result, Bundle bundle) {
                if(progressDialog!=null)
                    progressDialog.dismiss();
                loginToChat();
                android.util.Log.e(TAG, "QB Chat Login successfully");
            }

            @Override
            public void onError(QBResponseException e) {
                android.util.Log.e(TAG, "Error Login in Home Screen>>>" +e);
                if(progressDialog!=null)
                    progressDialog.dismiss();

            }
        });

private void loginToChat() {
        if(SharedPrefsHelper.getInstance().getQbUser()!=null){
            final QBUser user = SharedPrefsHelper.getInstance().getQbUser();
            ChatHelper.getInstance().loginToChat(user, new QBEntityCallback<Void>() {
                @Override
                public void onSuccess(Void result, Bundle bundle) {
                    android.util.Log.v(TAG, "Chat login onSuccess()");

                }

                @Override
                public void onError(QBResponseException e) {

                    android.util.Log.w(TAG, "Chat login onError(): " + e);

                }
            });
        }
    }
</code>```

Log cat:

```<code> > D/QBASDK: *********************************************************
    >                                                            *** RESPONSE *** b4c54adf-b802-4327-b74b-96cc3fc5314d ***
    >                                                            STATUS : 201
    >                                                            HEADERS
    >                                                                X-Runtime=0.012808
    >                                                                Cache-Control=max-age=0, private, must-revalidate
    >                                                                QuickBlox-REST-API-Version=0.1.1
    >                                                                X-Android-Selected-Protocol=http/1.1
    >                                                                QB-Token-ExpirationDate=2017-06-07 13:56:00 UTC
    >                                                                Status=201 Created
    >                                                                X-Request-Id=4a8acb4c-6166-42c0-b85a-a038d61af56b
    >                                                                X-Android-Response-Source=NETWORK 201
    >                                                                Connection=Close
    >                                                                X-Android-Sent-Millis=1496836559559
    >                                                                Content-Type=application/json; charset=utf-8
    >                                                                Date=Wed, 07 Jun 2017 11:56:00 GMT
    >                                                                X-Content-Type-Options=nosniff
    >                                                                Server=openresty/1.9.15.1
    >                                                                ETag=W/"c74341ada523f27d4d495a2443d502a6"
    >                                                                Content-Length=239
    >                                                                Strict-Transport-Security=max-age=31536000max-age=15768000;
    >                                                                X-XSS-Protection=1; mode=block
    >                                                                X-Frame-Options=SAMEORIGIN
    >                                                                X-Android-Received-Millis=1496836559866
    >                                                                Access-Control-Allow-Origin=*
    >                                                            BODY
    >                                                                '{"session":{"application_id":52126,"created_at":"2017-06-07T11:56:00Z","id":170143275,"nonce":-982948609,"token":"76c7ad273008bd4d1a3b87fd80551e046b00cb9e","ts":1496836558,"updated_at":"2017-06-07T11:56:00Z","user_id":0,"_id":"170143275"}}'
    > 06-07 17:25:59.937 4348-4348/com.talktotherapist D/AndroidRuntime:
    > Shutting down VM
    >
    >
    >                                                                    [ 06-07 17:25:59.937  2014: 4508 D/         ]
    >                                                                     x = 0.110770,  y = 0.138312,  z = 10.251881 06-07 17:25:59.958 4348-4451/com.talktotherapist D/SettingsInterface:  from settings
    > cache , name = android_id , value = 8dc776344146c84 06-07 17:26:00.119
    > 4348-4451/com.talktotherapist D/SettingsInterface:  from settings
    > cache , name = android_id , value = 8dc776344146c84 06-07 17:26:00.123
    > 4348-4451/com.talktotherapist D/SettingsInterface:  from settings
    > cache , name = android_id , value = 8dc776344146c84 06-07 17:26:00.123
    > 4348-4451/com.talktotherapist D/SettingsInterface:  from settings
    > cache , name = android_id , value = 8dc776344146c84 06-07 17:26:00.123
    > 4348-4451/com.talktotherapist D/SettingsInterface:  from settings
    > cache , name = android_id , value = 8dc776344146c84 06-07 17:26:00.123
    > 4348-4451/com.talktotherapist D/SettingsInterface:  from settings
    > cache , name = android_id , value = 8dc776344146c84 06-07 17:26:00.124
    > 4348-4451/com.talktotherapist D/SettingsInterface:  from settings
    > cache , name = android_id , value = 8dc776344146c84
    >
    >                                                                       --------- beginning of crash 06-07 17:26:00.127 4348-4348/com.talktotherapist E/AndroidRuntime: FATAL EXCEPTION: main
    >                                                                    Process: com.talktotherapist, PID: 4348
    >                                                                    java.lang.NullPointerException: Attempt to invoke virtual method 'long
    > java.util.Date.getTime()' on a null object reference
    >                                                                        at java.util.Calendar.setTime(Calendar.java:1197)
    >                                                                        at java.text.SimpleDateFormat.formatImpl(SimpleDateFormat.java:527)
    >                                                                        at java.text.SimpleDateFormat.format(SimpleDateFormat.java:829)
    >                                                                        at java.text.DateFormat.format(DateFormat.java:314)
    >                                                                        at
    > com.google.gson.DefaultDateTypeAdapter.write(DefaultDateTypeAdapter.java:88)
    >                                                                        at
    > com.google.gson.DefaultDateTypeAdapter.write(DefaultDateTypeAdapter.java:40)
    >                                                                        at
    > com.google.gson.internal.bind.TypeAdapterRuntimeTypeWrapper.write(TypeAdapterRuntimeTypeWrapper.java:69)
    >                                                                        at
    > com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$1.write(ReflectiveTypeAdapterFactory.java:125)
    >                                                                        at
    > com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$Adapter.write(ReflectiveTypeAdapterFactory.java:243)
    >                                                                        at com.google.gson.Gson.toJson(Gson.java:669)
    >                                                                        at com.google.gson.Gson.toJson(Gson.java:648)
    >                                                                        at com.google.gson.Gson.toJson(Gson.java:603)
    >                                                                        at com.google.gson.Gson.toJson(Gson.java:583)
    >                                                                        at com.quickblox.auth.session.b.save(Unknown Source)
    >                                                                        at
    > com.quickblox.auth.session.QBSessionManager.setActiveSession(Unknown
    > Source)
    >                                                                        at
    > com.quickblox.auth.session.QBSessionJsonParser.extractEntity(Unknown
    > Source)
    >                                                                        at
    > com.quickblox.auth.session.QBSessionJsonParser.extractEntity(Unknown
    > Source)
    >                                                                        at com.quickblox.core.parser.QBJsonParser.parse(Unknown Source)
    >                                                                        at
    > com.quickblox.auth.session.Query$VersionEntityCallback.completedWithResponse(Unknown
    > Source)
    >                                                                        at com.quickblox.auth.session.Query.completedWithResponse(Unknown
    > Source)
    >                                                                        at
    > com.quickblox.core.server.HttpRequestRunnable$1.handleMessage(Unknown
    > Source)
    >                                                                        at android.os.Handler.dispatchMessage(Handler.java:111)
    >                                                                        at android.os.Looper.loop(Looper.java:207)
    >                                                                        at android.app.ActivityThread.main(ActivityThread.java:5736)
    >                                                                        at java.lang.reflect.Method.invoke(Native Method)
    >                                                                        at
    > com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:910)
    >                                                                        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:771) 06-07
    > 17:26:00.152 4348-4455/com.talktotherapist D/OpenGLRenderer:
    > ~CanvasContext() 0x7f983cd000 06-07 17:26:00.154
    > 4348-4455/com.talktotherapist D/OpenGLRenderer: ~CanvasContext()
    > 0x7f85c49000
</code>```

Please guide me how to resolve login issues.

答:
Please try to follow this steps, it works for me perfectly!
Hope it will helpful to you!

First you need to sign in quickblox.

```<code>QBUser user = new QBUser("username", "password");
QBUsers.signIn(user).performAsync(new QBEntityCallback<QBUser>() {
    @Override
    public void onSuccess(QBUser qbUser, Bundle bundle) {
        Log.e("LOGIN ", "myID =" + qbUser.getId());
    }

    @Override
    public void onError(QBResponseException e) {
        Log.e("LOGIN Error", "error..SIGN IN*****");
    }
});
</code>```

then use that user object to create session and then login to chat service.

here's code:

```<code>final QBChatService chatService = QBChatService.getInstance();
final QBUser qbuser = new QBUser("username", "password");
QBAuth.createSession(qbuser).performAsync(new QBEntityCallback<QBSession>() {
    @Override
    public void onSuccess(QBSession qbSession, Bundle bundle) {
        user.setId(qbSession.getUserId());
        chatService.login(qbuser, new QBEntityCallback() {
            @Override
            public void onSuccess(Object o, Bundle bundle) {

            }

            @Override
            public void onError(QBResponseException e) {

            }
        });
    }

    @Override
    public void onError(QBResponseException e) {

    }
});
</code>```

Body:
I have integrated QuickBlox, everything is working fine, suddenly I am getting this error. I have tried to get why it is coming but didn't get any solution.

My code:

ChatHelper.getInstance().login(user, new QBEntityCallback<Void>() {
            @Override
            public void onSuccess(Void result, Bundle bundle) {
                if(progressDialog!=null)
                    progressDialog.dismiss();
                loginToChat();
                android.util.Log.e(TAG, "QB Chat Login successfully");
            }

            @Override
            public void onError(QBResponseException e) {
                android.util.Log.e(TAG, "Error Login in Home Screen>>>" +e);
                if(progressDialog!=null)
                    progressDialog.dismiss();

            }
        });

private void loginToChat() {
        if(SharedPrefsHelper.getInstance().getQbUser()!=null){
            final QBUser user = SharedPrefsHelper.getInstance().getQbUser();
            ChatHelper.getInstance().loginToChat(user, new QBEntityCallback<Void>() {
                @Override
                public void onSuccess(Void result, Bundle bundle) {
                    android.util.Log.v(TAG, "Chat login onSuccess()");

                }

                @Override
                public void onError(QBResponseException e) {

                    android.util.Log.w(TAG, "Chat login onError(): " + e);

                }
            });
        }
    }

Log cat:

 > D/QBASDK: *********************************************************
    >                                                            *** RESPONSE *** b4c54adf-b802-4327-b74b-96cc3fc5314d ***
    >                                                            STATUS : 201
    >                                                            HEADERS
    >                                                                X-Runtime=0.012808
    >                                                                Cache-Control=max-age=0, private, must-revalidate
    >                                                                QuickBlox-REST-API-Version=0.1.1
    >                                                                X-Android-Selected-Protocol=http/1.1
    >                                                                QB-Token-ExpirationDate=2017-06-07 13:56:00 UTC
    >                                                                Status=201 Created
    >                                                                X-Request-Id=4a8acb4c-6166-42c0-b85a-a038d61af56b
    >                                                                X-Android-Response-Source=NETWORK 201
    >                                                                Connection=Close
    >                                                                X-Android-Sent-Millis=1496836559559
    >                                                                Content-Type=application/json; charset=utf-8
    >                                                                Date=Wed, 07 Jun 2017 11:56:00 GMT
    >                                                                X-Content-Type-Options=nosniff
    >                                                                Server=openresty/1.9.15.1
    >                                                                ETag=W/"c74341ada523f27d4d495a2443d502a6"
    >                                                                Content-Length=239
    >                                                                Strict-Transport-Security=max-age=31536000max-age=15768000;
    >                                                                X-XSS-Protection=1; mode=block
    >                                                                X-Frame-Options=SAMEORIGIN
    >                                                                X-Android-Received-Millis=1496836559866
    >                                                                Access-Control-Allow-Origin=*
    >                                                            BODY
    >                                                                '{"session":{"application_id":52126,"created_at":"2017-06-07T11:56:00Z","id":170143275,"nonce":-982948609,"token":"76c7ad273008bd4d1a3b87fd80551e046b00cb9e","ts":1496836558,"updated_at":"2017-06-07T11:56:00Z","user_id":0,"_id":"170143275"}}'
    > 06-07 17:25:59.937 4348-4348/com.talktotherapist D/AndroidRuntime:
    > Shutting down VM
    >
    >
    >                                                                    [ 06-07 17:25:59.937  2014: 4508 D/         ]
    >                                                                     x = 0.110770,  y = 0.138312,  z = 10.251881 06-07 17:25:59.958 4348-4451/com.talktotherapist D/SettingsInterface:  from settings
    > cache , name = android_id , value = 8dc776344146c84 06-07 17:26:00.119
    > 4348-4451/com.talktotherapist D/SettingsInterface:  from settings
    > cache , name = android_id , value = 8dc776344146c84 06-07 17:26:00.123
    > 4348-4451/com.talktotherapist D/SettingsInterface:  from settings
    > cache , name = android_id , value = 8dc776344146c84 06-07 17:26:00.123
    > 4348-4451/com.talktotherapist D/SettingsInterface:  from settings
    > cache , name = android_id , value = 8dc776344146c84 06-07 17:26:00.123
    > 4348-4451/com.talktotherapist D/SettingsInterface:  from settings
    > cache , name = android_id , value = 8dc776344146c84 06-07 17:26:00.123
    > 4348-4451/com.talktotherapist D/SettingsInterface:  from settings
    > cache , name = android_id , value = 8dc776344146c84 06-07 17:26:00.124
    > 4348-4451/com.talktotherapist D/SettingsInterface:  from settings
    > cache , name = android_id , value = 8dc776344146c84
    >
    >                                                                       --------- beginning of crash 06-07 17:26:00.127 4348-4348/com.talktotherapist E/AndroidRuntime: FATAL EXCEPTION: main
    >                                                                    Process: com.talktotherapist, PID: 4348
    >                                                                    java.lang.NullPointerException: Attempt to invoke virtual method 'long
    > java.util.Date.getTime()' on a null object reference
    >                                                                        at java.util.Calendar.setTime(Calendar.java:1197)
    >                                                                        at java.text.SimpleDateFormat.formatImpl(SimpleDateFormat.java:527)
    >                                                                        at java.text.SimpleDateFormat.format(SimpleDateFormat.java:829)
    >                                                                        at java.text.DateFormat.format(DateFormat.java:314)
    >                                                                        at
    > com.google.gson.DefaultDateTypeAdapter.write(DefaultDateTypeAdapter.java:88)
    >                                                                        at
    > com.google.gson.DefaultDateTypeAdapter.write(DefaultDateTypeAdapter.java:40)
    >                                                                        at
    > com.google.gson.internal.bind.TypeAdapterRuntimeTypeWrapper.write(TypeAdapterRuntimeTypeWrapper.java:69)
    >                                                                        at
    > com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$1.write(ReflectiveTypeAdapterFactory.java:125)
    >                                                                        at
    > com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$Adapter.write(ReflectiveTypeAdapterFactory.java:243)
    >                                                                        at com.google.gson.Gson.toJson(Gson.java:669)
    >                                                                        at com.google.gson.Gson.toJson(Gson.java:648)
    >                                                                        at com.google.gson.Gson.toJson(Gson.java:603)
    >                                                                        at com.google.gson.Gson.toJson(Gson.java:583)
    >                                                                        at com.quickblox.auth.session.b.save(Unknown Source)
    >                                                                        at
    > com.quickblox.auth.session.QBSessionManager.setActiveSession(Unknown
    > Source)
    >                                                                        at
    > com.quickblox.auth.session.QBSessionJsonParser.extractEntity(Unknown
    > Source)
    >                                                                        at
    > com.quickblox.auth.session.QBSessionJsonParser.extractEntity(Unknown
    > Source)
    >                                                                        at com.quickblox.core.parser.QBJsonParser.parse(Unknown Source)
    >                                                                        at
    > com.quickblox.auth.session.Query$VersionEntityCallback.completedWithResponse(Unknown
    > Source)
    >                                                                        at com.quickblox.auth.session.Query.completedWithResponse(Unknown
    > Source)
    >                                                                        at
    > com.quickblox.core.server.HttpRequestRunnable$1.handleMessage(Unknown
    > Source)
    >                                                                        at android.os.Handler.dispatchMessage(Handler.java:111)
    >                                                                        at android.os.Looper.loop(Looper.java:207)
    >                                                                        at android.app.ActivityThread.main(ActivityThread.java:5736)
    >                                                                        at java.lang.reflect.Method.invoke(Native Method)
    >                                                                        at
    > com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:910)
    >                                                                        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:771) 06-07
    > 17:26:00.152 4348-4455/com.talktotherapist D/OpenGLRenderer:
    > ~CanvasContext() 0x7f983cd000 06-07 17:26:00.154
    > 4348-4455/com.talktotherapist D/OpenGLRenderer: ~CanvasContext()
    > 0x7f85c49000

Please guide me how to resolve login issues.

Body:
Please try to follow this steps, it works for me perfectly!
Hope it will helpful to you!

First you need to sign in quickblox.

QBUser user = new QBUser("username", "password");
QBUsers.signIn(user).performAsync(new QBEntityCallback<QBUser>() {
    @Override
    public void onSuccess(QBUser qbUser, Bundle bundle) {
        Log.e("LOGIN ", "myID =" + qbUser.getId());
    }

    @Override
    public void onError(QBResponseException e) {
        Log.e("LOGIN Error", "error..SIGN IN*****");
    }
});

then use that user object to create session and then login to chat service.

here's code:

final QBChatService chatService = QBChatService.getInstance();
final QBUser qbuser = new QBUser("username", "password");
QBAuth.createSession(qbuser).performAsync(new QBEntityCallback<QBSession>() {
    @Override
    public void onSuccess(QBSession qbSession, Bundle bundle) {
        user.setId(qbSession.getUserId());
        chatService.login(qbuser, new QBEntityCallback() {
            @Override
            public void onSuccess(Object o, Bundle bundle) {

            }

            @Override
            public void onError(QBResponseException e) {

            }
        });
    }

    @Override
    public void onError(QBResponseException e) {

    }
});


问:
Missing Info.plist key

I need to internationalize those tips, but i got this!Any idea?

答:
If you want to internationalize tips here is the good Stack overflow answer

in short after adding info.plist string file for respective language, you can localize just like this.Add your respective permisstion key with appropriate description.

NSLocationAlwaysUsageDescription = "请打开【定位服务】允许 Your App 确定您的位置。";

Title: Missing Info.plist key


问:
I'm trying to automate a code using Selenium. I'm unable to handle the dialog box elements
The code opens the dialog box but is not handling the dialog box elements. I've tried switching to the window but its not working.</p>

答: I got the solution. Use xpath of the dialog box elements to access it and use .sendKeys to enter text. Switching Windows didn't work for me. Using xpath worked!</p>


问:
How can I add loop in after function?
My javascript is like this :

```<code>$('#thumbnail-view').after(` for(i=0;i<5;i++){ <div>....</div }`);
</code>```

I want to add loop in after like that

How can I do it?

答:
What you really need is to create a variable that has all the elements you want. then pass that variable to the after. Do not create a function inside of after. There is no need for it.

```<code>$(document).ready(function(){
  var divvs = '';
  for(var i=0;i<5;i++){
    divvs+= '<div>hello</div>'
  }
  $('.block').after(divvs);
});
</code>```

Here is the fiddle for reference http://jsbin.com/biluqanupo/edit?html,js,output

Title: How can I add loop in after function?

Body:
My javascript is like this :

$('#thumbnail-view').after(` for(i=0;i<5;i++){ <div>....</div }`);

I want to add loop in after like that

How can I do it?

Body:
What you really need is to create a variable that has all the elements you want. then pass that variable to the after. Do not create a function inside of after. There is no need for it.

$(document).ready(function(){
  var divvs = '';
  for(var i=0;i<5;i++){
    divvs+= '<div>hello</div>'
  }
  $('.block').after(divvs);
});

Here is the fiddle for reference http://jsbin.com/biluqanupo/edit?html,js,output


问:
How to implement FFT algorithm in python?
I am trying to implement a function in python3, but I couldn't figure out the error in the argument.Following is my code and the error:

```<code>def FFT1(A,n,w):

    if n==1:
        return A
    AEven=[]
    for k in range(0,n,2):
        key1= A[k]
        AEven.append(key1)
    AOdd=[]
    for l in range(1,n,2):
        key2=A[l]
        AOdd.append(key2)
    VE=FFT1(AEven, n/2, w**2)
    VO=FFT1(AOdd, n/2, w**2)
    mult= complex(-1,1)
    V=[]*n
    for i in range(0,(n-2)/2):
        V[i]=VE[i]+(w**mult)*VO[i]
        V[n/2+i]=VE[i]-(w**mult)*VO[i]
    return V

FFT1(coeff, degree, rootunit)
</code>```

causes:

```<code>Traceback (most recent call last):
  File "<pyshell#45>", line 1, in <module>
    FFT1(coeff, degree, rootunit)
  File "<pyshell#44>", line 12, in FFT1
    VE=FFT1(AEven, n/2, w**2)
  File "<pyshell#44>", line 5, in FFT1
    for k in range(0,n,2):
TypeError: 'float' object cannot be interpreted as an integer
</code>```

答: The Python range() function does not accept a floating value as a step. Try converting all the floats to integers with the int() function. Basically anywhere you might be passing something like n/k replace that with int(n/k) of course this might give some unexpected results.</p>

Body:
I am trying to implement a function in python3, but I couldn't figure out the error in the argument.Following is my code and the error:

def FFT1(A,n,w):

    if n==1:
        return A
    AEven=[]
    for k in range(0,n,2):
        key1= A[k]
        AEven.append(key1)
    AOdd=[]
    for l in range(1,n,2):
        key2=A[l]
        AOdd.append(key2)
    VE=FFT1(AEven, n/2, w**2)
    VO=FFT1(AOdd, n/2, w**2)
    mult= complex(-1,1)
    V=[]*n
    for i in range(0,(n-2)/2):
        V[i]=VE[i]+(w**mult)*VO[i]
        V[n/2+i]=VE[i]-(w**mult)*VO[i]
    return V

FFT1(coeff, degree, rootunit)

causes:

Traceback (most recent call last):
  File "<pyshell#45>", line 1, in <module>
    FFT1(coeff, degree, rootunit)
  File "<pyshell#44>", line 12, in FFT1
    VE=FFT1(AEven, n/2, w**2)
  File "<pyshell#44>", line 5, in FFT1
    for k in range(0,n,2):
TypeError: 'float' object cannot be interpreted as an integer


问:
Why AlertDialog displays blank message?
I'm developing a simple game. I'm using SQLite to save data and I am trying to display the data in an AlertDialog popup. It seems that the text is being placed where it should be, but it's not showing. There's a blank space where the text should be.
These are the methods I use to make the AlertDialog and add text to it:

```<code>public void viewAll() {

    allGames.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Cursor res = myDb.getAllData();
            if (res.getCount() == 0) {
                //show message
                showMessage("Error", "No data found");
                return;
            }
            StringBuffer buffer = new StringBuffer();
            while (res.moveToNext()) {
                buffer.append("Name : " + res.getString(0)+ "\n");
                buffer.append("Tries : " + res.getString(1)+ "\n");
                buffer.append("Difficulty : " + res.getString(2)+ "\n\n");
            }
            showMessage("Data", buffer.toString());
        }
    });
}

public void showMessage(String title, String Message) {
    AlertDialog.Builder builder = new AlertDialog.Builder(this);
    builder.setCancelable(true);
    builder.setTitle(title);
    builder.setMessage(Message);
    builder.show();
}
</code>```

Before the database was populated, and before the text was added to the Alert Dialog

After text was added to it

As you can see, the AlertDialog gets bigger when I add text to it. Please let me know if you see any error in my code or is you want to see more of it.

答:
Try below answer which will work in all version:-</p>

```<code>AlertDialog.Builder builder;
if(Build.VERSION.SDK_INT >= 21)
    builder = new AlertDialog.Builder(this, android.R.style.Theme_Material_Light_Dialog_Alert);
else
    builder = new AlertDialog.Builder(this);
builder.setCancelable(true);
builder.setTitle(title);
builder.setMessage(Message);
builder.create().show();
</code>```

Title: Why AlertDialog displays blank message?

Body:
I'm developing a simple game. I'm using SQLite to save data and I am trying to display the data in an AlertDialog popup. It seems that the text is being placed where it should be, but it's not showing. There's a blank space where the text should be.
These are the methods I use to make the AlertDialog and add text to it:

public void viewAll() {

    allGames.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Cursor res = myDb.getAllData();
            if (res.getCount() == 0) {
                //show message
                showMessage("Error", "No data found");
                return;
            }
            StringBuffer buffer = new StringBuffer();
            while (res.moveToNext()) {
                buffer.append("Name : " + res.getString(0)+ "\n");
                buffer.append("Tries : " + res.getString(1)+ "\n");
                buffer.append("Difficulty : " + res.getString(2)+ "\n\n");
            }
            showMessage("Data", buffer.toString());
        }
    });
}

public void showMessage(String title, String Message) {
    AlertDialog.Builder builder = new AlertDialog.Builder(this);
    builder.setCancelable(true);
    builder.setTitle(title);
    builder.setMessage(Message);
    builder.show();
}

Before the database was populated, and before the text was added to the Alert Dialog

After text was added to it

As you can see, the AlertDialog gets bigger when I add text to it. Please let me know if you see any error in my code or is you want to see more of it.

Body:
Try below answer which will work in all version:-

AlertDialog.Builder builder;
if(Build.VERSION.SDK_INT >= 21)
    builder = new AlertDialog.Builder(this, android.R.style.Theme_Material_Light_Dialog_Alert);
else
    builder = new AlertDialog.Builder(this);
builder.setCancelable(true);
builder.setTitle(title);
builder.setMessage(Message);
builder.create().show();


问:
Replace Object Fields
I have an object that looks like this:

PetForm

```<code>{
name:"Bobo",
type:"Golden Retriever",
food:null,
toys:null,
....
}
</code>```

I want to replace the fields with the values of null to an empty string like this:

Result:

```<code>{
name:"Bobo",
type:"Golden Retriever",
food:"",
toys:"",
....
}
</code>```

I did the following:

```<code>Object.keys(PetForm).forEach((key) => (PetForm[key] === null) && PetForm[key] == "");
</code>```

Am I missing something in this method?

答:
In case you want to keep the petform map and return a new object, you can use reduce function.

var petform = {
  name:"Bobo",
  type:"Golden Retriever",
  food:null,
  toys:null,
}

var res = Object.keys(petform).reduce((acc, curr) => { acc[curr] = petform[curr] ? petform[curr] : '' ; return acc; }, {});

console.log(res)```

Title: Replace Object Fields

Body:
I have an object that looks like this:

PetForm

{
name:"Bobo",
type:"Golden Retriever",
food:null,
toys:null,
....
}

I want to replace the fields with the values of null to an empty string like this:

Result:

{
name:"Bobo",
type:"Golden Retriever",
food:"",
toys:"",
....
}

I did the following:

Object.keys(PetForm).forEach((key) => (PetForm[key] === null) && PetForm[key] == "");

Am I missing something in this method?


答:
That code is not complete. Why did you leave out the declarations all the variables? Because they "aren't important?"

Note that those declarations ARE IMPORTANT.

I can't tell but I predict that d is not set to 0 and is picking up 0xFFFFFFFF from the stack. Which is Not A Number in floating point. A NaN value in a calculation always results in NaN results.

Title: -1.#Q0 shows up randomly

Body:
I have the following code:

float w[n][n] = {
    {0, 0, 0.5, -1, 0, 0, 0},
    {0, 0, 1.5, -2, 0, 0, 0},
    {0, 0, 0, 0, 1, -1, 0},
    {0, 0, 0, 0, 3, -4, 0},
    {0, 0, 0, 0, 0, 0, 1},
    {0, 0, 0, 0, 0, 0, -3}
};
float x[ne] = {2, -1};
float d = 1;
float alpha = 0.1;
float in[n];
float delta[n];
float a[n];
float sum;

for(j = ne; j <= n; j++) {
    for(i = 0; i <= n; i++) {
        in[j] += w[i][j] * a[i];
    }
    a[j] = g(in[j]);
}

for(i = 0; i < n; i++) {
    printf("a[%d] = %.3f\n", i+1, a[i]);
}

delta[n-1] = d - a[n-1];

for(i = n-2; i >= ne; i--) {
    for(j = 0; j <= n; j++) {
        sum += w[i][j] * delta[j];
    }
    delta[i] = g(in[i]) * (1 - g(in[i])) * sum;
    printf("delta[%d] = %.3f\n", i+1, delta[i]);
    sum = 0;
 }

printf("\n\n");

for(i = 0; i < n; i++) {
    for(j = 0; j < n; j++) {
        if (w[i][j] != 0) {
            w[i][j] = w[i][j] + alpha * a[i] * delta[j];
            printf("w[%d][%d] = %.3f\n", i+1, j+1, w[i][j]);
        }
    }
}

I keep getting some variation of this output:

a[1] = 2.000
a[2] = -1.000
a[3] = 0.378
a[4] = 0.500
a[5] = 0.867
a[6] = 0.085
a[7] = 0.649

delta[6] = -1.#QO
delta[5] = -1.#QO
delta[4] = -1.#QO
delta[3] = -1.#QO

w[1][3] = -1.#QO
w[1][4] = -1.#QO
w[2][3] = -1.#QO
w[2][4] = -1.#QO
w[3][5] = -1.#QO
w[3][6] = -1.#QO
w[4][5] = -1.#QO
w[4][6] = -1.#QO
w[5][7] = 1.030
w[6][7] = -2.997

It shows up in different places everytime I compile, knowing that the first time it was giving me the right answer, I'm not sure what went wrong?


问:
Learning COBOL Without Access to Mainframe
I am a graduate student majoring in Computer Science.  My department teaches the majority of its courses using Java (though I did take one course on system architecture that used C to demonstrate processor scheduling, memory management, etc....but I digress).

I want to learn more about COBOL, but I don't have access to a mainframe system.  Can anyone please recommend a free COBOL compiler for Windows that would enable me to get through some basic COBOL tutorials?

Disclaimer:  yes, I've Googled this already, so hoping for some experienced individuals to give some further info.

Thanks!

答:
Other posters have suggested Tiny COBOL, but have a look at OpenCOBOL too. OpenCOBOL
is a cross compiler to C and has a fairly active development community.

COBOL is not a difficult language to learn. Unless you are tying to work your way into a mainframe shop,
spending a lot of time studying COBOL may not have much career payback.

As belisarius pointed out, it is not the language as much as the environment that needs to be learned.
By analogy, there isn't very much to learn about the C language either. However,
just knowing C will not get you very far - you need to work with the
huge standard library that comes with it. COBOL is similar in that
respect. The difference is that COBOL does not come with a huge standard library, it is part of a package
that often includes: CICS, DB/2, MQ-Series and an array of other library services (LE Services in an IBM environment).

COBOL can be found outside of a mainframe environment but the mainframe
is its "real home". As a generalization, "mainframe" implies an IBM mainframe running Z/OS
(many may take exception to this statement). This publication: Introduction to the Mainframe - z/OS
is a good place to get a feel for what an IBM mainframe environment is like.

The things I find characterize COBOL are:

COBOL is a procedural language. Some vendors have added OO extensions
and new COBOL language standards include OO extensions, but this is largely window dressing.
COBOL is fundamentally a procedural language.

Data declaration. The PICTURE/USAGE thing is a bit of a mind bender. Data declaration combines
internal data representation (binary, packed decimal, floating point, character, etc.) with presentation
(number of digits, leading zeros, sign, etc.) into a single declaration.

REDEFINES used to provide different views of the same underlying memory.

Hierarchical data declarations. Data hierarchy is defined using level numbers. Level 1 defines the top of the
hierarchy and increasing numbers define lower levels. Levels 66 (in conjunction with RENAMES), 77, 88 have special meanings.

Flow of control. Many programmers (even some veteran COBOL programmers) view SECTION/PARAGRAPH
in a manner similar to a procedure call. They are completely different. SECTION/PARAGRAPH do
not follow normal stack oriented call/return semantics. COBOL uses a unique mechanism to manage
return from PERFORMed sections/paragraphs.

Monolithic programs with tons of global variables. It is not uncommon to find COBOL source files
running into thousands of lines with several hundred global variables.
COBOL doesn't have to be written this way - I believe this is a legacy dating back to a time when
procedure calls were considered costly but PERFORMing a SECTION/PARAGRAPH was very efficient. The habit
seems to have stuck and newer COBOL programs tend to be written as monolithic monsters too.

String handling nightmare. COBOL does financial calculations very well. It does not do
string handling very well at all. The string handling verbs INSPECT, STRING and UNSTRING can do
a number of interesting things, but manage to be quite aggravating too.

COPY/REPLACING and REPLACE compiler directives need to be understood. They behave somewhat
differently than file inclusion in most other languages. Most shops use COPY only for common record or
data declaration, others use them for common procedural code too (with REPLACING and or REPLACE).

Given a working knowledge of C, you should be able to pick up on COBOL without much difficulty.


问:
Swift 3 - Reload UICollectionView inside the UITableViewCell
I have a UICollectionView inside a UITableViewCell. You may refer the image at here

I would like to reload the collectionView if any update happen.

I have done some research and found this :

how to reload a collectionview that is inside a tableviewcell

Reloading collection view inside a table view cell happens after all cells in table view have been loaded

UICollectionView not updating inside UITableViewCell

I called the @IBOutlet weak var collectionView: UICollectionView! from UITableViewCell to UITableViewController at cellForRowAt.

Here is the code:

```<code>var refreshNow: Bool = false

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: Storyboard.allCardCell, for: indexPath) as! AllCardTableViewCell

        if refreshNow {
          cell.collectionView.reloadData()
          refreshNow = false
        }

        cell.collectionView.collectionViewLayout.invalidateLayout()
        return cell
    }
</code>```

If the user click Ok on UIAlertAction :

```<code>let alert = UIAlertController(title: "Success", message: "Card successfully added", preferredStyle: .alert)
                let action = UIAlertAction(title: "Ok", style: .default) { (action) in
                    self.refreshNow = true
                    self.tableView.reloadData()
                }
                alert.addAction(action)
                self.present(alert, animated: true, completion: nil)
</code>```

The reason why I put the refreshNow is to prevent the apps from lagging and slow. But still did not update if any changes happen.

The problem is the collectionView did not refresh. But when I debug, it was went through the cell.collectionView.reloadData().

The update/changes only happen when I restart the apps. I want it to be so called real-times update.

Any help is really appreciated and many thanks.

Image credit: How to use StoryBoard quick build a collectionView inside UITableViewCell

答:
In your case, you should assign tag to your collection view in order to get access outside the cellForRowAt function.

This is how your function should look like:

```<code>override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: Storyboard.allCardCell, for: indexPath) as! AllCardTableViewCell

    cell.collectionView.tag = 1234
    return cell
}
</code>```

and the action will reload it will access the collectionView by using the tag

```<code>let action = UIAlertAction(title: "Ok", style: .default) { (action) in
    let collectionView = self.tableView.viewWithTag(1234) as! UICollectionView
    collectionView.reloadData()
}
</code>```

Also take note that cellForRowAt will keep reload the content based what you added inside it every time the cell appear. So, keep updating your data outside the cellForRowAt function.

Body:
I have a UICollectionView inside a UITableViewCell. You may refer the image at here

I would like to reload the collectionView if any update happen.

I have done some research and found this :

how to reload a collectionview that is inside a tableviewcell

Reloading collection view inside a table view cell happens after all cells in table view have been loaded

UICollectionView not updating inside UITableViewCell

I called the @IBOutlet weak var collectionView: UICollectionView! from UITableViewCell to UITableViewController at cellForRowAt.

Here is the code:

var refreshNow: Bool = false

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: Storyboard.allCardCell, for: indexPath) as! AllCardTableViewCell

        if refreshNow {
          cell.collectionView.reloadData()
          refreshNow = false
        }

        cell.collectionView.collectionViewLayout.invalidateLayout()
        return cell
    }

If the user click Ok on UIAlertAction :

let alert = UIAlertController(title: "Success", message: "Card successfully added", preferredStyle: .alert)
                let action = UIAlertAction(title: "Ok", style: .default) { (action) in
                    self.refreshNow = true
                    self.tableView.reloadData()
                }
                alert.addAction(action)
                self.present(alert, animated: true, completion: nil)

The reason why I put the refreshNow is to prevent the apps from lagging and slow. But still did not update if any changes happen.

The problem is the collectionView did not refresh. But when I debug, it was went through the cell.collectionView.reloadData().

The update/changes only happen when I restart the apps. I want it to be so called real-times update.

Any help is really appreciated and many thanks.

Image credit: How to use StoryBoard quick build a collectionView inside UITableViewCell

Body:
In your case, you should assign tag to your collection view in order to get access outside the cellForRowAt function.

This is how your function should look like:

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: Storyboard.allCardCell, for: indexPath) as! AllCardTableViewCell

    cell.collectionView.tag = 1234
    return cell
}

and the action will reload it will access the collectionView by using the tag

let action = UIAlertAction(title: "Ok", style: .default) { (action) in
    let collectionView = self.tableView.viewWithTag(1234) as! UICollectionView
    collectionView.reloadData()
}

Also take note that cellForRowAt will keep reload the content based what you added inside it every time the cell appear. So, keep updating your data outside the cellForRowAt function.


问:
How to put array in an I18n in html.erb
I am working with a t('footer.card.type.name') where I want to replace name with the array list. t('footer.card.type.name') by the way, is to show different languages in different I18n.

Currently I am stuck with placing |type| into t('footer.card_type.%{type}'). This I am sure it does not work. I am just experimenting on ways to making it work.

```<code>      <%= link_to t('footer.card_type.all'), credit_cards_path %>
      <% ['cash_back', 'islamic', 'petrol', 'reward', 'travel', 'no_annual_fee', 'premium', 'balance_transfer', 'promo'].each do |type| %>
        <%= link_to t('footer.card_type.%{type}'), credit_card_type_path(sub_type: type.gsub('_','-')) %>
      <% end %>
</code>```

答:
I have found a work around by adding .concat(type) after the t('footer.card_type.'). It successfully returns the translation of both languages. Hope this code can help someone.

```<code>   <% ['cash_back', 'islamic', 'petrol', 'reward', 'travel', 'no_annual_fee', 'premium', 'balance_transfer', 'promo'].each do |type| %>
        <%= link_to t('footer.card_type.'.concat(type)), credit_card_type_path(sub_type: type.gsub('_','-')) %>
   <% end %>
</code>```

Title: How to put array in an I18n in html.erb

Body:
I am working with a t('footer.card.type.name') where I want to replace name with the array list. t('footer.card.type.name') by the way, is to show different languages in different I18n.

Currently I am stuck with placing |type| into t('footer.card_type.%{type}'). This I am sure it does not work. I am just experimenting on ways to making it work.

      <%= link_to t('footer.card_type.all'), credit_cards_path %>
      <% ['cash_back', 'islamic', 'petrol', 'reward', 'travel', 'no_annual_fee', 'premium', 'balance_transfer', 'promo'].each do |type| %>
        <%= link_to t('footer.card_type.%{type}'), credit_card_type_path(sub_type: type.gsub('_','-')) %>
      <% end %>

Body:
I have found a work around by adding .concat(type) after the t('footer.card_type.'). It successfully returns the translation of both languages. Hope this code can help someone.

   <% ['cash_back', 'islamic', 'petrol', 'reward', 'travel', 'no_annual_fee', 'premium', 'balance_transfer', 'promo'].each do |type| %>
        <%= link_to t('footer.card_type.'.concat(type)), credit_card_type_path(sub_type: type.gsub('_','-')) %>
   <% end %>


问:
Can I use reserved word as parameter of a function in javascript?
```<code>var myName = 'John';
function greet(name) {
  console.log('Hello, ' + name);
}
greet(myName);
</code>```

Here I'm using 'name' as a parameter of the greet(). Since we know that we can't use javascript reserved word as a variable name, could we use them as the param? Or are they restricted for anywhere in the script to be used as an identifier?

Thanks in advance :)

答:
The example you provided will work. - name is not a reserved word.

However, to answer your question:  No - if you were to try to use a reserved word such as const or var you would get an error.

Body:
var myName = 'John';
function greet(name) {
  console.log('Hello, ' + name);
}
greet(myName);

Here I'm using 'name' as a parameter of the greet(). Since we know that we can't use javascript reserved word as a variable name, could we use them as the param? Or are they restricted for anywhere in the script to be used as an identifier?

Thanks in advance :)