问:
Enum and Switch statement C++
```<code>int a, b;
cin >> a >> b;
enum operation {add, sub, mul, div};
        operation d;
        switch (d)
        {
        case add : cout << "addition of two numbers is: " << a + b << endl;
            break;
        case sub : cout << "subtraction of two numbers is " << a - b << endl;
            break;
        case mul : cout << "multiplication of the two numbers is " << a * b << endl;
            break;
        case div : cout << "division of the two numbers is " << a / b << endl;
        default: cout << "invalid parameters" << endl;
        }
</code>```

when I build this, I get the error "uninitialized local variable d used", but when I initialize the variable to one from the defined list, I cannot choose any other switch case other than the one defined.
I know I'm missing something, I googled a lot but couldn't get help. I'd really appreciate if anyone would help. Thank you!

答:
I think what you are trying to do is making your code dynamic. Unfortunately, you are doing it completely wrong. Please first clear your concept on enum.

If this is the case, then you can try this-

```<code>int a, b;
char op;

cin >> a >> op >> b;

switch(op)
{
    case '+': cout << "addition of two numbers is: " << a + b << endl; break;
    case '-': cout << "subtraction of two numbers is " << a - b << endl; break;
    case '*': cout << "multiplication of the two numbers is " << a * b << endl; break;
    case '/': cout << "division of the two numbers is " << a / b << endl; break;
    default: cout << "invalid operator" << endl;
}
</code>```

Title: Enum and Switch statement C++

Body:
int a, b;
cin >> a >> b;
enum operation {add, sub, mul, div};
        operation d;
        switch (d)
        {
        case add : cout << "addition of two numbers is: " << a + b << endl;
            break;
        case sub : cout << "subtraction of two numbers is " << a - b << endl;
            break;
        case mul : cout << "multiplication of the two numbers is " << a * b << endl;
            break;
        case div : cout << "division of the two numbers is " << a / b << endl;
        default: cout << "invalid parameters" << endl;
        }

when I build this, I get the error "uninitialized local variable d used", but when I initialize the variable to one from the defined list, I cannot choose any other switch case other than the one defined.
I know I'm missing something, I googled a lot but couldn't get help. I'd really appreciate if anyone would help. Thank you!

Body:
I think what you are trying to do is making your code dynamic. Unfortunately, you are doing it completely wrong. Please first clear your concept on enum.

If this is the case, then you can try this-

int a, b;
char op;

cin >> a >> op >> b;

switch(op)
{
    case '+': cout << "addition of two numbers is: " << a + b << endl; break;
    case '-': cout << "subtraction of two numbers is " << a - b << endl; break;
    case '*': cout << "multiplication of the two numbers is " << a * b << endl; break;
    case '/': cout << "division of the two numbers is " << a / b << endl; break;
    default: cout << "invalid operator" << endl;
}


来源: stackexchange

问:
Fitting comparison plot_Algorithm for several dependent variables in R
I have several dependent variables in my dataset and I want to find the best fit between x and each y. How can I modify the following code (loop function) to have the plot of x and all ys at the same time. Instead of running the code for each dependent variable separately, I want to run a code and have three plots for (x,y) (x,y1) and (x,y2)</p>

```<code>fit1 <- read.table(header=TRUE,text="
x    y   y1 y2
1 0 2.36 3  5
2 1 1.10 3  6
3 2 0.81 4  7
4 3 0.69 1.3  8
5 4 0.64 2.3  9
6 5 0.61 4.3  15")
Various fits:

library(ggplot2)
ggplot(fit1,aes(x,y))+geom_point()+
    geom_smooth(method="glm",se=FALSE,
                method.args=list(family=gaussian(link="log")))+
    geom_smooth(method="nls",se=FALSE,
                formula=y~a+b*exp(-c*x),
                method.args=list(start=list(a=0.6,b=1.5,c=1)),
                colour="red")+
    geom_smooth(method="lm",se=FALSE,
                formula=y~exp(-x),
                colour="purple")
</code>```

答:
You can use facet_grid after you melt your data</p>

```<code>fit1_melt <- melt(fit1, id = "x")
ggplot(fit1_melt, aes(x=x,y=value)) +
geom_point() +
facet_grid(~variable)
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have several dependent variables in my dataset and I want to find the best fit between x and each y. How can I modify the following code (loop function) to have the plot of x and all ys at the same time. Instead of running the code for each dependent variable separately, I want to run a code and have three plots for (x,y) (x,y1) and (x,y2)

fit1 <- read.table(header=TRUE,text="
x    y   y1 y2
1 0 2.36 3  5
2 1 1.10 3  6
3 2 0.81 4  7
4 3 0.69 1.3  8
5 4 0.64 2.3  9
6 5 0.61 4.3  15")
Various fits:

library(ggplot2)
ggplot(fit1,aes(x,y))+geom_point()+
    geom_smooth(method="glm",se=FALSE,
                method.args=list(family=gaussian(link="log")))+
    geom_smooth(method="nls",se=FALSE,
                formula=y~a+b*exp(-c*x),
                method.args=list(start=list(a=0.6,b=1.5,c=1)),
                colour="red")+
    geom_smooth(method="lm",se=FALSE,
                formula=y~exp(-x),
                colour="purple")

Body:
You can use facet_grid after you melt your data

fit1_melt <- melt(fit1, id = "x")
ggplot(fit1_melt, aes(x=x,y=value)) +
geom_point() +
facet_grid(~variable)


问:
Changing the color of individual characters in a glyph
As I understand it, a string contains glyphs and a glyph might consist of individual characters. For me this is a problem, as I would like to change the color of some diacritics in a string.

Let's say we have the following string:

วาีม

For this string I would like to make the consonants a different color as it's diacritic. I.e.: I want a different color for วาม and ี.

From my tests it seems that I am only able to color individual glyphs. It seems I can not change the color at a character (diacritic) level. Some example code:

```<code>let text = NSMutableAttributedString(string: "วาีม")
text.addAttribute(NSForegroundColorAttributeName, value: UIColor.blue, range: NSMakeRange(0, 1))
text.addAttribute(NSForegroundColorAttributeName, value: UIColor.red, range: NSMakeRange(1, 1))
text.addAttribute(NSForegroundColorAttributeName, value: UIColor.green, range: NSMakeRange(2, 1))
text.addAttribute(NSForegroundColorAttributeName, value: UIColor.orange, range: NSMakeRange(3, 1))
label.attributedText = text
</code>```

The above would render as follows:

As can be seen the diacritic is not rendered with a green color.

Does anyone know if there is some way to achieve the result I want?

答:
An alternative is to put two labels on top of one another; one containing the text with the diacritics in the colour you want for the diacritics; one on top of it with the same text but without the diacritics, in the colour you want for the text.

When rendering, the identical bits of the text should cancel out exactly, leaving you with text and diacritics in the right colours.

Body:
As I understand it, a string contains glyphs and a glyph might consist of individual characters. For me this is a problem, as I would like to change the color of some diacritics in a string.

Let's say we have the following string:

วาีม

For this string I would like to make the consonants a different color as it's diacritic. I.e.: I want a different color for วาม and ี.

From my tests it seems that I am only able to color individual glyphs. It seems I can not change the color at a character (diacritic) level. Some example code:

let text = NSMutableAttributedString(string: "วาีม")
text.addAttribute(NSForegroundColorAttributeName, value: UIColor.blue, range: NSMakeRange(0, 1))
text.addAttribute(NSForegroundColorAttributeName, value: UIColor.red, range: NSMakeRange(1, 1))
text.addAttribute(NSForegroundColorAttributeName, value: UIColor.green, range: NSMakeRange(2, 1))
text.addAttribute(NSForegroundColorAttributeName, value: UIColor.orange, range: NSMakeRange(3, 1))
label.attributedText = text

The above would render as follows:

As can be seen the diacritic is not rendered with a green color.

Does anyone know if there is some way to achieve the result I want?


问:
Value of Rd (Destination Register) in load/store instruction (mips pipeline)
Architecture of Pipeline MIPS Processor

I'm working with a Pipeline MIPS Processor and I have the following program:

# $a0 = 0x 805F E371
# $t0 = 0x 8007 4821

lw $t0, ($a0)
```

The load instruction is running in ID phase. In ID/EX register there are many saved register. One of this register is called Register Destination (Rd). I know that Rs register contains the value of $a0, Rt contains the value of $t0.

The question is: What's inside Rd? I suppose 0 cause it's not in use, but I'm not sure. Could it be 0 for another reason? Could it be a different value from 0?

答:
lw is an I-type instruction it use two register operands and one immediate operand.

```<code>   31-26     25-21   20-16      15-0
 |  op    |  rs    |  rt    |    imm   |
  6 bits    5 bits   5 bits     16 bits
</code>```

rs and imm are always used as source operand.

rt is used as destination register and you know what it contains.

You are maybe confusing this with R-type which use rd as destination operand.

This is R-type.

```<code>   31-26    25-21    20-16    15-11   10-6    5-0
|   op    |  rs    |  rt    |  rd   | shamt | funct |
  6 bits    5 bits   5 bits  5 bits  5 bits  6 bits
</code>```

Body:
Architecture of Pipeline MIPS Processor

I'm working with a Pipeline MIPS Processor and I have the following program:

# $a0 = 0x 805F E371
# $t0 = 0x 8007 4821

lw $t0, ($a0)

The load instruction is running in ID phase. In ID/EX register there are many saved register. One of this register is called Register Destination (Rd). I know that Rs register contains the value of $a0, Rt contains the value of $t0.

The question is: What's inside Rd? I suppose 0 cause it's not in use, but I'm not sure. Could it be 0 for another reason? Could it be a different value from 0?

Body:
lw is an I-type instruction it use two register operands and one immediate operand.

   31-26     25-21   20-16      15-0
 |  op    |  rs    |  rt    |    imm   |
  6 bits    5 bits   5 bits     16 bits

rs and imm are always used as source operand.

rt is used as destination register and you know what it contains.

You are maybe confusing this with R-type which use rd as destination operand.

This is R-type.

   31-26    25-21    20-16    15-11   10-6    5-0
|   op    |  rs    |  rt    |  rd   | shamt | funct |
  6 bits    5 bits   5 bits  5 bits  5 bits  6 bits


问:
Build time for aws-sdk-ios on CI with Carthage
I am using Carthage and aws-sdk-ios. I use just 2 projects from aws, but Carthage needs to build all the other 20+ libraries.

On BuddyBuild this means 40 minutes to build. It's impossible to work like this in a team.

This is in the Cartfile:
github "aws/aws-sdk-ios"

Is there a solution to this?

答: Tools like Rome are super useful to speed up CI builds by storing the results in S3.</p>


问:
TypeError: Python thinks that I passed a function 2 arguments but I only passed it 1
I work on something in Seattle Repy which is a restricted subset of Python. Anyway, I wanted to implement my own Queue that derives from a list:

```<code>class Queue(list):
    job_count = 0

    def __init__(self):
        list.__init__(self)

    def appendleft(item):
        item.creation_time = getruntime()
        item.current_count = self.job_count
        self.insert(0, item)

    def pop():
        item = self.pop()
        item.pop_time = getruntime()
        return item
</code>```

Now I call this in my main server, where I use my own Job class to pass Jobs to the Queue:

```<code>mycontext['queue'] = Queue()
# ...
job = Job(str(ip), message)
mycontext['queue'].appendleft(job)
</code>```

The last line raises the following exception:

Exception (with type 'exceptions.TypeError'): appendleft() takes exactly 1 argument (2 given)

I'm relatively new to Python, so could anyone explain to me why it would think that I gave appendleft() two arguments when there obviously was only one?

答:
Python passes the object itself as the first argument to it's methods. You need to modify your class methods to take the mandatory first argument, conventionally (a strong convention that is) named self.

Read this - http://docs.python.org/tutorial/classes.html

ContentLicense: CC BY-SA 2.5

Body:
I work on something in Seattle Repy which is a restricted subset of Python. Anyway, I wanted to implement my own Queue that derives from a list:

class Queue(list):
    job_count = 0

    def __init__(self):
        list.__init__(self)

    def appendleft(item):
        item.creation_time = getruntime()
        item.current_count = self.job_count
        self.insert(0, item)

    def pop():
        item = self.pop()
        item.pop_time = getruntime()
        return item

Now I call this in my main server, where I use my own Job class to pass Jobs to the Queue:

mycontext['queue'] = Queue()
# ...
job = Job(str(ip), message)
mycontext['queue'].appendleft(job)

The last line raises the following exception:

Exception (with type 'exceptions.TypeError'): appendleft() takes exactly 1 argument (2 given)

I'm relatively new to Python, so could anyone explain to me why it would think that I gave appendleft() two arguments when there obviously was only one?


问:
how to create layer-list drawable programmatically?
I want to draw a shape like my icon.xml programmatically, but I can't embed the second circle into the first circle this is my code :

icon.xml

```<code><?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<item android:id="@+id/ok">
<shape
    android:shape="oval">
    <solid android:color="#ffffff" />
    <size android:width="33px" android:height="33px"/>
    <stroke android:width="4px"
        android:color="#ff0000"/>
    <padding android:bottom="8px"
        android:left="8px"
        android:right="8px"
        android:top="8px"/>
</shape>
</item>
<item>
<shape android:shape="oval">
    <solid android:color="#ccff0000"/>
</shape>
</item>

</layer-list>
</code>```

MainActivity.java

```<code>    GradientDrawable layer1 = new GradientDrawable();
    layer1.setShape(GradientDrawable.OVAL);
    layer1.setSize(33,33);
    layer1.setColor(Color.WHITE);
    layer1.setStroke(4,Color.RED);

    GradientDrawable layer2 = new GradientDrawable();
    layer2.setShape(GradientDrawable.OVAL);
    layer2.setColor(Color.BLUE);

    InsetDrawable insetLayer2 = new InsetDrawable(layer1, 8, 8, 8, 8);

    LayerDrawable layerDrawable = new LayerDrawable(new Drawable[]
    {insetLayer2,layer2});
    button.setBackground(layerDrawable);
</code>```

What's wrong ?

thank you in advance

答:
Finally I got the answer. My problem was how to set padding for out Circle,
however we can set padding programmatically using setLayerInset(int index, int l, int t, int r, int b) for two gradients separately.

Body:
I want to draw a shape like my icon.xml programmatically, but I can't embed the second circle into the first circle this is my code :

icon.xml

<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<item android:id="@+id/ok">
<shape
    android:shape="oval">
    <solid android:color="#ffffff" />
    <size android:width="33px" android:height="33px"/>
    <stroke android:width="4px"
        android:color="#ff0000"/>
    <padding android:bottom="8px"
        android:left="8px"
        android:right="8px"
        android:top="8px"/>
</shape>
</item>
<item>
<shape android:shape="oval">
    <solid android:color="#ccff0000"/>
</shape>
</item>

</layer-list>

MainActivity.java

    GradientDrawable layer1 = new GradientDrawable();
    layer1.setShape(GradientDrawable.OVAL);
    layer1.setSize(33,33);
    layer1.setColor(Color.WHITE);
    layer1.setStroke(4,Color.RED);

    GradientDrawable layer2 = new GradientDrawable();
    layer2.setShape(GradientDrawable.OVAL);
    layer2.setColor(Color.BLUE);

    InsetDrawable insetLayer2 = new InsetDrawable(layer1, 8, 8, 8, 8);

    LayerDrawable layerDrawable = new LayerDrawable(new Drawable[]
    {insetLayer2,layer2});
    button.setBackground(layerDrawable);

What's wrong ?

thank you in advance


问:
inserting a row of data in sql server 2014 in javafx
i want to insert a row of data into my USERS table...
this is my code

   @FXML
    private void handleRegisterButtonAction() throws SQLException{
        String userName="'"+txt_username.getText()+"'";
        String password="'"+txt_password.getText()+"'";
        String mail="'"+txt_userMail.getText()+"'";
        //for example user id is 22
        int userId=22;

        String insertUser="INSERT INTO USERS(userId,userName,userPassword,userEmail)"
                + " VALUES("+userId+","+userName+","+password+","+mail+");";
        stmt.execute(insertUser);
    }
```

the code runs but table in the database doesn't change

this is because sql doesn't know to apply this query on which database!
But i dont know how to solve this

答:
Write query like this :

```<code>INSERT INTO **Database_Name**.dbo.USERS(userId,userName,userPassword,userEmail)"
                + " VALUES("+userId+","+userName+","+password+","+mail+");";
</code>```

Change Database_Name to your database name, then run your code.

Body:
i want to insert a row of data into my USERS table...
this is my code

   @FXML
    private void handleRegisterButtonAction() throws SQLException{
        String userName="'"+txt_username.getText()+"'";
        String password="'"+txt_password.getText()+"'";
        String mail="'"+txt_userMail.getText()+"'";
        //for example user id is 22
        int userId=22;

        String insertUser="INSERT INTO USERS(userId,userName,userPassword,userEmail)"
                + " VALUES("+userId+","+userName+","+password+","+mail+");";
        stmt.execute(insertUser);
    }

the code runs but table in the database doesn't change

this is because sql doesn't know to apply this query on which database!
But i dont know how to solve this

Body:
Write query like this :

INSERT INTO **Database_Name**.dbo.USERS(userId,userName,userPassword,userEmail)"
                + " VALUES("+userId+","+userName+","+password+","+mail+");";

Change Database_Name to your database name, then run your code.


问:
Page is reloading when using 'LinkToObject' in amChart Map
What i am currently doing, I am using amChart map along with markers and some of the other charts on same page, i've setup the marker and provide URL whenever user click on particular marker whole screen will reload and values/charts will appear accordingly.

Now my problem is when user select that particular country from Map marker URL will update, rest of the charts are working fine even Map starts to zoom accordingly but when zoom is complete, page is reloading itself with same URL. This thing is continuously going on without stopping, if i remove LinkToObject tag from DataProvider of Chart everything works fine, only map will not zoom itself.

I think you got my point, if you need anything else let me know.

答: I've found the solution, basically i set the URL parameter behind every marker of Map and when user try to click on marker complete page will refresh and map starts to zoom to that particular marker. In this case, when map is zoom it is assuming that marker has been clicked so the code is again starts to refresh page. I've increase the check in the code that if URL is set with any particular parameter it means marker is already selected and when page is loading i've remove URL from that marker. By doing this when there is no URL found on click of marker then technically it will not refresh itself.</p>


问:
Stuck in echoing data out of variable CodeIgniter
I try to get some information out of my database to my webpage. Everything seems to be fine but there is one thing that doesn't want to go right. I put all my information out my database into $data. When i do this

```<code>print_r($data);
</code>```

My webpage gives me this:

```<code>(
[0] => stdClass Object
   (
   [reparatie_id] => 19
   [customer_id] => 4
   [medewerker] => 4
   [name] => Joost
   )
)
</code>```

Everything seems to be good but when i try to do this:

```<code>echo $data->voornaam;
</code>```

I keep getting this error

```<code>A PHP Error was encountered

Severity: Notice

Message:  Trying to get property of non-object

Filename: reparaties/cases.php

Line Number: 7

Backtrace:

        File: C:\Ampps\www\beco\application\views\reparaties\cases.php

        Line: 7

        Function: _error_handler

        File: C:\Ampps\www\beco\application\controllers\Reparaties.php

        Line: 57

        Function: view

        File: C:\Ampps\www\beco\public\index.php

        Line: 315

        Function: require_once
</code>```

答:
First of all, your $data array does not have the voornaam element in it. So, assuming you want to echo out the elements that are inside the array, you would use the foreach array, like this:

```<code>foreach($data as $value) {
    echo $value->name;
    echo $value->voorname; //if it exists
}
</code>```

But, if you just want to access that single element from the array then you would do this:

```<code>echo $data[0]->name;
</code>```

Body:
I try to get some information out of my database to my webpage. Everything seems to be fine but there is one thing that doesn't want to go right. I put all my information out my database into $data. When i do this

print_r($data);

My webpage gives me this:

(
[0] => stdClass Object
   (
   [reparatie_id] => 19
   [customer_id] => 4
   [medewerker] => 4
   [name] => Joost
   )
)

Everything seems to be good but when i try to do this:

echo $data->voornaam;

I keep getting this error

A PHP Error was encountered

Severity: Notice

Message:  Trying to get property of non-object

Filename: reparaties/cases.php

Line Number: 7

Backtrace:

        File: C:\Ampps\www\beco\application\views\reparaties\cases.php

        Line: 7

        Function: _error_handler

        File: C:\Ampps\www\beco\application\controllers\Reparaties.php

        Line: 57

        Function: view

        File: C:\Ampps\www\beco\public\index.php

        Line: 315

        Function: require_once

Body:
First of all, your $data array does not have the voornaam element in it. So, assuming you want to echo out the elements that are inside the array, you would use the foreach array, like this:

foreach($data as $value) {
    echo $value->name;
    echo $value->voorname; //if it exists
}

But, if you just want to access that single element from the array then you would do this:

echo $data[0]->name;


问:
Compiler gives warning on performSelectorOnMainThread:@selector(delegateMethod)
I have an NSOperation that wraps some web service functionality. The NSOperation has a delegate that is to be messaged when the operation is over.

As the NSOperation lives on a different thread I have to make the call like this:

```<code>[delegate performSelectorOnMainThread:@selector(getDealersIDSuccess:) withObject:result waitUntilDone:YES];
</code>```

It works just fine, but it gives me a warning:

warning:
  '-performSelectorOnMainThread:withObject:waitUntilDone:'
  not found in protocol(s)

I completely agree with the compiler on this one, it sees a delegate, it checks the protocol, it finds no declaration of a performSelector method.

My question is: can I remove the warning by making this call in a different manner?

My two guesses are that I could (1) write a method called

```<code>- (void) callDelegateMethodOnMainThred {
    [delegate getDealersIDSuccess:result]
}
</code>```

and call that through performSelectorOnMainThread, but I find that solution to be cumbersome and an extra, hard to read, step on top of the delegation.

The second solution could be to cast the delegate to the type of my parent object inside the selector, but that is just plain crazy and goes against the delegate encapsulation pattern.

I would really appreciate a third solution from someone with a better understanding of the language:)

Thank you in advance.

EDIT: Added delegate declaration:

```<code>id <ISDealersIDDelegate> delegate;
</code>```

I declare my delegate as id. The delegate it self extends UIViewController.

I could see that declaring it NSObject would work.

答:
Actually on iOS 4 I prefer using NSNotifications and Observers (with Blocks) to perform updates on the mainthread.

```<code>- (id)addObserverForName:(NSString *)name object:(id)obj queue:(NSOperationQueue *)queue usingBlock:(void (^)(NSNotification *))block
</code>```

I wrote down my design here.

Body:
I have an NSOperation that wraps some web service functionality. The NSOperation has a delegate that is to be messaged when the operation is over.

As the NSOperation lives on a different thread I have to make the call like this:

[delegate performSelectorOnMainThread:@selector(getDealersIDSuccess:) withObject:result waitUntilDone:YES];

It works just fine, but it gives me a warning:

warning:
  '-performSelectorOnMainThread:withObject:waitUntilDone:'
  not found in protocol(s)

I completely agree with the compiler on this one, it sees a delegate, it checks the protocol, it finds no declaration of a performSelector method.

My question is: can I remove the warning by making this call in a different manner?

My two guesses are that I could (1) write a method called

- (void) callDelegateMethodOnMainThred {
    [delegate getDealersIDSuccess:result]
}

and call that through performSelectorOnMainThread, but I find that solution to be cumbersome and an extra, hard to read, step on top of the delegation.

The second solution could be to cast the delegate to the type of my parent object inside the selector, but that is just plain crazy and goes against the delegate encapsulation pattern.

I would really appreciate a third solution from someone with a better understanding of the language:)

Thank you in advance.

EDIT: Added delegate declaration:

id <ISDealersIDDelegate> delegate;

I declare my delegate as id. The delegate it self extends UIViewController.

I could see that declaring it NSObject would work.

Body:
Actually on iOS 4 I prefer using NSNotifications and Observers (with Blocks) to perform updates on the mainthread.

- (id)addObserverForName:(NSString *)name object:(id)obj queue:(NSOperationQueue *)queue usingBlock:(void (^)(NSNotification *))block

I wrote down my design here.


问:
.htaccess file doesn't respect server timezone
.htaccess file set as follows:

```<code>SetEnv TZ Pacific/Auckland
php_value date.timezone ‘Pacific/Auckland’
RewriteEngine on
RewriteRule ^$ http://urlgoeshere.com/news/%{TIME_YEAR}%{TIME_MON}%{TIME_DAY}-%{TIME_HOUR}00-048.mp3 [R=301,L]
</code>```

phpinfo.php shows the timezone is set to Pacific/Auckland, though the script rewrites according to Pacific Timezone. What am I missing? Thanks

答:
You are setting a php value, for php interpreted scripts. Then you are rewriting with Apache. It is never using that php value, because it never executes a php script.

As far as I know, Apache uses the server timezone. See this question on serverfault for more information. In short: Change /etc/sysconfig/clock, then restart the server.

To save yourself from headaches, I would recommend using UTC time for everything you do. It is a nightmare to have to deal with daylight saving and all the edge cases it brings, and it is even worse when you have an international audience and figure out that you have to suddenly translate between two variable timezones. UTC is always precise and constant and makes everything easier.

Body:
.htaccess file set as follows:

SetEnv TZ Pacific/Auckland
php_value date.timezone ‘Pacific/Auckland’
RewriteEngine on
RewriteRule ^$ http://urlgoeshere.com/news/%{TIME_YEAR}%{TIME_MON}%{TIME_DAY}-%{TIME_HOUR}00-048.mp3 [R=301,L]

phpinfo.php shows the timezone is set to Pacific/Auckland, though the script rewrites according to Pacific Timezone. What am I missing? Thanks


问:
Java: Volatile variable not updating (get and set methods not working)
I have a Runnable "NanoClock" class which keeps updating a private volatile double value in its run() method.

This class also has a getTime() method which returns the double value. Another class ("Master") is constructing the NanoClock class and creates a thread, as well as calling the start() method.

After it did this it calls the getTime() method several times (with a delay), but the value is not updating. What am I doing wrong?

NanoClock.java :

```<code>public class NanoClock implements Runnable {
    private volatile boolean running;
    private volatile double time;
    public NanoClock() {
        time = System.currentTimeMillis();
    }
    @Override
    public void run() {
        running = true;
        while(running) {
            try {
                if(System.currentTimeMillis() > time) {
                    time = System.currentTimeMillis();
                }
              //This returns the updated value continuously when commented out
              //System.out.println("Time: " + String.format("%.6f", unix_time));
                Thread.sleep(2000);
            } catch(Exception exc) {
                exc.printStackTrace();
                System.exit(1);
            }
        }
    }
    public double getTime() {
        return time;
    }
    public void end() {
        running = false;
    }
}
</code>```

Master.java:

```<code>public class Master {
    public static void main(String[] args) {
        try {
            NanoClock nClock = new NanoClock();
            Thread clockThread = new Thread(new NanoClock());
            clockThread.setPriority(10);
            clockThread.start();
            //MY_ISSUE: This returns the same value every time
            for(int a = 0; a < 10; a++) {
                System.out.println("Time: " + nClock.getTime());
            }
            //MY_ISSUE: This cannot stop the while loop - I tested it with
            //the println in the NanoClock class.
            nClock.end();
            System.out.println("Done!");
        catch(Exception e) {
            e.printStackTrace();
            System.exit(1);
        }
    }
}
</code>```

答:
System.currentTimeMillis() returns a long, but you store it in a double, which causes a loss of precision. When you change the member time (and also the return type of its getter) to a long you should get the expected result.

As a rule of thumb: When working with time units long is most appropriate datatype most of the time. Floating point numbers are not suitable to store precise results.

Body:
I have a Runnable "NanoClock" class which keeps updating a private volatile double value in its run() method.

This class also has a getTime() method which returns the double value. Another class ("Master") is constructing the NanoClock class and creates a thread, as well as calling the start() method.

After it did this it calls the getTime() method several times (with a delay), but the value is not updating. What am I doing wrong?

NanoClock.java :

public class NanoClock implements Runnable {
    private volatile boolean running;
    private volatile double time;
    public NanoClock() {
        time = System.currentTimeMillis();
    }
    @Override
    public void run() {
        running = true;
        while(running) {
            try {
                if(System.currentTimeMillis() > time) {
                    time = System.currentTimeMillis();
                }
              //This returns the updated value continuously when commented out
              //System.out.println("Time: " + String.format("%.6f", unix_time));
                Thread.sleep(2000);
            } catch(Exception exc) {
                exc.printStackTrace();
                System.exit(1);
            }
        }
    }
    public double getTime() {
        return time;
    }
    public void end() {
        running = false;
    }
}

Master.java:

public class Master {
    public static void main(String[] args) {
        try {
            NanoClock nClock = new NanoClock();
            Thread clockThread = new Thread(new NanoClock());
            clockThread.setPriority(10);
            clockThread.start();
            //MY_ISSUE: This returns the same value every time
            for(int a = 0; a < 10; a++) {
                System.out.println("Time: " + nClock.getTime());
            }
            //MY_ISSUE: This cannot stop the while loop - I tested it with
            //the println in the NanoClock class.
            nClock.end();
            System.out.println("Done!");
        catch(Exception e) {
            e.printStackTrace();
            System.exit(1);
        }
    }
}


问:
Assign string array to comboBox in java
I want to assign dir array to comboBox. Is there any error in my code. I tried to display the dir array it contains the values but cannot assign it comboBox. Here is the code.

```<code>import java.awt.EventQueue;

public class ExpenseManager {

private JFrame frame;
private JTextField txtUserName;
private JLabel lblNewUserName;
private JButton btnDone;
private JButton btnLogin;
private JComboBox<?> comboBox;
private String[] dir = new String[100];
private String[] hello = {"Hii", "Hello"};

/**
 * Launch the application.
 */
public static void main(String[] args) {
    EventQueue.invokeLater(new Runnable() {
        public void run() {
            try {
                ExpenseManager window = new ExpenseManager();
                window.frame.setVisible(true);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    });
}

/**
 * Create the application.
 */
public ExpenseManager() {
    initialize();
}

/**
 * Initialize the contents of the frame.
 */
//@SuppressWarnings("unchecked")
private void initialize() {
    frame = new JFrame();
    frame.setBounds(100, 100, 450, 300);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.getContentPane().setLayout(null);

    JButton btnNewUser = new JButton("New User");
    btnNewUser.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            lblNewUserName.setVisible(true);
            txtUserName.setVisible(true);
            btnDone.setVisible(true);
        }
    });
    btnNewUser.setBounds(23, 34, 89, 23);
    frame.getContentPane().add(btnNewUser);

    txtUserName = new JTextField();
    txtUserName.setBounds(240, 63, 134, 20);
    frame.getContentPane().add(txtUserName);
    txtUserName.setVisible(false);
    txtUserName.setColumns(10);

    lblNewUserName = new JLabel("Enter New UserName");
    lblNewUserName.setBounds(240, 38, 134, 14);
    lblNewUserName.setVisible(false);
    frame.getContentPane().add(lblNewUserName);

    btnDone = new JButton("Done");
    btnDone.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            String newUserName = txtUserName.getText();
            if(!newUserName.isEmpty())
            {
                File f = new File("S:/Expense/" + newUserName);
                if (f.exists() && f.isDirectory()) {
                   JOptionPane.showMessageDialog(null, "User already exists");
                   txtUserName.setText(null);
                }
                else{
                    boolean success = (new File("S:/Expense/" + newUserName)).mkdir();
                    if(!success){
                        JOptionPane.showMessageDialog(null, "Unable to register");
                    }else{
                        JOptionPane.showMessageDialog(null, "User registered Successfully");
                    }
                }
            }
            else
            {
                JOptionPane.showMessageDialog(null, "Kindly enter User Name", "Invalid User Name", JOptionPane.ERROR_MESSAGE);
            }
        }
    });
    btnDone.setBounds(240, 103, 89, 23);
    btnDone.setVisible(false);
    frame.getContentPane().add(btnDone);

    btnLogin = new JButton("Login");
    btnLogin.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent arg0) {
            File[] directories = new File("S:/Expense/").listFiles();

            for(int i = 0; i < directories.length; i++)
            {
                dir[i] = directories[i].getName();
            }

            comboBox.setVisible(true);

        }
    });
    btnLogin.setBounds(23, 68, 89, 23);
    frame.getContentPane().add(btnLogin);

    comboBox = new JComboBox<Object>(dir);
    comboBox.setBounds(24, 138, 72, 20);
    comboBox.setSelectedIndex(1);
    comboBox.setVisible(false);
    frame.getContentPane().add(comboBox);

     }
  }
</code>```

答:
Most of the code posted is not relevant to the question asked, so it should be removed (see MCVE).
Review the following, note the comments:

```<code>public class ExpenseManager {

    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    new ExpenseManager();
                } catch (Exception e) { e.printStackTrace();    }
            }
        });
    }

    public ExpenseManager() {   initialize(); }

    private void initialize() {

        JFrame frame = new JFrame();
        frame.setBounds(100, 100, 450, 300);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.getContentPane().setLayout(null); //better use a layout manger

        JComboBox<String> comboBox = new JComboBox<>();
        comboBox.setBounds(24, 138, 72, 20);
        comboBox.setVisible(false);
        frame.getContentPane().add(comboBox);

        JButton btn = new JButton("Populate combo");
        btn.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent arg0) {

                //populate combo
                String[] dir = new String[5];

                for(int i = 0; i < dir.length; i++) { dir[i] = "String "+ i;}

                comboBox.setModel(new DefaultComboBoxModel<>(dir));
                comboBox.setVisible(true);
                btn.setEnabled(false); //disable button
            }
        });
        btn.setBounds(23, 68, 89, 23);
        frame.getContentPane().add(btn);
        frame.setVisible(true);
    }
}
</code>```

EDIT implementation using a layout manager :

```<code>private void initialize() {

        JFrame frame = new JFrame();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        JComboBox<String> comboBox = new JComboBox<>();
        comboBox.setVisible(false);
        frame.add(comboBox, BorderLayout.SOUTH); //using BorderLayout which is the default

        JButton btn = new JButton("Populate combo");
        btn.setPreferredSize(new Dimension(150,35));
        btn.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent arg0) {

                //populate combo
                String[] dir = new String[5];

                for(int i = 0; i < dir.length; i++) { dir[i] = "String "+ i;}

                comboBox.setModel(new DefaultComboBoxModel<>(dir));
                comboBox.setVisible(true);
                btn.setEnabled(false); //disable button
                frame.pack();  //resize fram to fit the preferred size and layouts
            }
        });
        frame.getContentPane().add(btn, BorderLayout.NORTH);
        frame.pack();
        frame.setVisible(true);
    }
</code>```

Title: Assign string array to comboBox in java

Body:
I want to assign dir array to comboBox. Is there any error in my code. I tried to display the dir array it contains the values but cannot assign it comboBox. Here is the code.

import java.awt.EventQueue;

public class ExpenseManager {

private JFrame frame;
private JTextField txtUserName;
private JLabel lblNewUserName;
private JButton btnDone;
private JButton btnLogin;
private JComboBox<?> comboBox;
private String[] dir = new String[100];
private String[] hello = {"Hii", "Hello"};

/**
 * Launch the application.
 */
public static void main(String[] args) {
    EventQueue.invokeLater(new Runnable() {
        public void run() {
            try {
                ExpenseManager window = new ExpenseManager();
                window.frame.setVisible(true);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    });
}

/**
 * Create the application.
 */
public ExpenseManager() {
    initialize();
}

/**
 * Initialize the contents of the frame.
 */
//@SuppressWarnings("unchecked")
private void initialize() {
    frame = new JFrame();
    frame.setBounds(100, 100, 450, 300);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.getContentPane().setLayout(null);

    JButton btnNewUser = new JButton("New User");
    btnNewUser.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            lblNewUserName.setVisible(true);
            txtUserName.setVisible(true);
            btnDone.setVisible(true);
        }
    });
    btnNewUser.setBounds(23, 34, 89, 23);
    frame.getContentPane().add(btnNewUser);

    txtUserName = new JTextField();
    txtUserName.setBounds(240, 63, 134, 20);
    frame.getContentPane().add(txtUserName);
    txtUserName.setVisible(false);
    txtUserName.setColumns(10);

    lblNewUserName = new JLabel("Enter New UserName");
    lblNewUserName.setBounds(240, 38, 134, 14);
    lblNewUserName.setVisible(false);
    frame.getContentPane().add(lblNewUserName);

    btnDone = new JButton("Done");
    btnDone.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            String newUserName = txtUserName.getText();
            if(!newUserName.isEmpty())
            {
                File f = new File("S:/Expense/" + newUserName);
                if (f.exists() && f.isDirectory()) {
                   JOptionPane.showMessageDialog(null, "User already exists");
                   txtUserName.setText(null);
                }
                else{
                    boolean success = (new File("S:/Expense/" + newUserName)).mkdir();
                    if(!success){
                        JOptionPane.showMessageDialog(null, "Unable to register");
                    }else{
                        JOptionPane.showMessageDialog(null, "User registered Successfully");
                    }
                }
            }
            else
            {
                JOptionPane.showMessageDialog(null, "Kindly enter User Name", "Invalid User Name", JOptionPane.ERROR_MESSAGE);
            }
        }
    });
    btnDone.setBounds(240, 103, 89, 23);
    btnDone.setVisible(false);
    frame.getContentPane().add(btnDone);

    btnLogin = new JButton("Login");
    btnLogin.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent arg0) {
            File[] directories = new File("S:/Expense/").listFiles();

            for(int i = 0; i < directories.length; i++)
            {
                dir[i] = directories[i].getName();
            }

            comboBox.setVisible(true);

        }
    });
    btnLogin.setBounds(23, 68, 89, 23);
    frame.getContentPane().add(btnLogin);

    comboBox = new JComboBox<Object>(dir);
    comboBox.setBounds(24, 138, 72, 20);
    comboBox.setSelectedIndex(1);
    comboBox.setVisible(false);
    frame.getContentPane().add(comboBox);

     }
  }

Body:
Most of the code posted is not relevant to the question asked, so it should be removed (see MCVE).
Review the following, note the comments:

public class ExpenseManager {

    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    new ExpenseManager();
                } catch (Exception e) { e.printStackTrace();    }
            }
        });
    }

    public ExpenseManager() {   initialize(); }

    private void initialize() {

        JFrame frame = new JFrame();
        frame.setBounds(100, 100, 450, 300);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.getContentPane().setLayout(null); //better use a layout manger

        JComboBox<String> comboBox = new JComboBox<>();
        comboBox.setBounds(24, 138, 72, 20);
        comboBox.setVisible(false);
        frame.getContentPane().add(comboBox);

        JButton btn = new JButton("Populate combo");
        btn.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent arg0) {

                //populate combo
                String[] dir = new String[5];

                for(int i = 0; i < dir.length; i++) { dir[i] = "String "+ i;}

                comboBox.setModel(new DefaultComboBoxModel<>(dir));
                comboBox.setVisible(true);
                btn.setEnabled(false); //disable button
            }
        });
        btn.setBounds(23, 68, 89, 23);
        frame.getContentPane().add(btn);
        frame.setVisible(true);
    }
}

EDIT implementation using a layout manager :

private void initialize() {

        JFrame frame = new JFrame();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        JComboBox<String> comboBox = new JComboBox<>();
        comboBox.setVisible(false);
        frame.add(comboBox, BorderLayout.SOUTH); //using BorderLayout which is the default

        JButton btn = new JButton("Populate combo");
        btn.setPreferredSize(new Dimension(150,35));
        btn.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent arg0) {

                //populate combo
                String[] dir = new String[5];

                for(int i = 0; i < dir.length; i++) { dir[i] = "String "+ i;}

                comboBox.setModel(new DefaultComboBoxModel<>(dir));
                comboBox.setVisible(true);
                btn.setEnabled(false); //disable button
                frame.pack();  //resize fram to fit the preferred size and layouts
            }
        });
        frame.getContentPane().add(btn, BorderLayout.NORTH);
        frame.pack();
        frame.setVisible(true);
    }


问:
why do I get a truncated .txt file
I'm trying to generate a file containing a short list of random numbers.  Every time I run this code I get a file where the list is truncated, usually in the middle of a number.  I'm using PyCharm.</p>

```<code>import random

def generate_test(l, r):
    lst = []
    for x in range(1,l):
        lst = lst + [random.randrange(0, r)]
    return lst
test = generate_test(100, 10**12)
test_file = open("test.txt", "wb")
test_file = open("test.txt", "r+")
test_file.write(str(test))
</code>```

答:
Few things I'd like to mention, once you open a file you get that state of the file so if you write, you write in that state, but can't read newly written data. So you do not need to open a file in both(r,w) modes. And last thing I noticed, you didn't close the file.

```<code>import random

def generate_test(l, r):
    lst = []
    for x in range(1,l):
        lst = lst + [random.randrange(0, r)]
    return lst

test = generate_test(100, 10**12)
print(len(test))   # 99

test_file = open('test.txt', 'w')
test_file.write(str(test))
test_file.close()
</code>```

Now read the file to verify the written data

```<code>test_file = open('test.txt','r')
data = test_file.read()
print(len(data.split()))   # 99
test_file.close()
</code>```

Title: why do I get a truncated .txt file

Body:
I'm trying to generate a file containing a short list of random numbers.  Every time I run this code I get a file where the list is truncated, usually in the middle of a number.  I'm using PyCharm.

import random

def generate_test(l, r):
    lst = []
    for x in range(1,l):
        lst = lst + [random.randrange(0, r)]
    return lst
test = generate_test(100, 10**12)
test_file = open("test.txt", "wb")
test_file = open("test.txt", "r+")
test_file.write(str(test))

Body:
Few things I'd like to mention, once you open a file you get that state of the file so if you write, you write in that state, but can't read newly written data. So you do not need to open a file in both(r,w) modes. And last thing I noticed, you didn't close the file.

import random

def generate_test(l, r):
    lst = []
    for x in range(1,l):
        lst = lst + [random.randrange(0, r)]
    return lst

test = generate_test(100, 10**12)
print(len(test))   # 99

test_file = open('test.txt', 'w')
test_file.write(str(test))
test_file.close()

Now read the file to verify the written data

test_file = open('test.txt','r')
data = test_file.read()
print(len(data.split()))   # 99
test_file.close()


问:
One hot encoding categorical features to use as training data with numerical features in sklearn
I am trying to train a model that reads data from a csv as the training data. To do this I am trying to conduct one hot encoding on the categorical features, and then pass the resulting arrays of 1s and 0s in as features, along with just the vanilla numerical features.

I have the following code:

```<code>X = pd.read_csv('Data2Cut.csv')

Y = X.select_dtypes(include=[object])

le = preprocessing.LabelEncoder()

Y_2 = Y.apply(le.fit_transform)

enc = preprocessing.OneHotEncoder()

enc.fit(Y_2)

onehotlabels = enc.transform(Y_2).toarray()
onehotlabels.shape

features = []
labels = []
mycsv = csv.reader(open('Data2Cut.csv'))
indexCount = 0
for row in mycsv:
  if indexCount < 8426:
    features.append([onehotlabels[indexCount], row[1], row[2], row[3], row[6], row[8], row[9], row[10], row[11]])
    labels.append(row[12])
    indexCount = indexCount + 1

training_data = np.array(features, dtype = 'float_')
training_labels = np.array(labels, dtype = 'float_')

log = linear_model.LogisticRegression()
log = log.fit(training_data, training_labels)
joblib.dump(log, "modelLogisticRegression.pkl")
</code>```

It seems to be getting to the line:

```<code>training_data = np.array(features, dtype = 'float_')
</code>```

Before it crashes giving the following error:

```<code>ValueError: setting an array element with a sequence.
</code>```

I figure this is a result of the one hot encoded values being arrays and not floats. How can I change/tweak this code to handle the categorical and numerical features as training data?

Edit: an example of a row i am feeding in, where each column is a feature is:

```<code>mobile, 1498885897, 17491407,   23911,  west coast, 2,  seagull, 18,    41.0666666667,  [0.325, 0.35],  [u'text', u'font', u'writing', u'line'],    102, 5
#...
</code>```

答:
Which version of sklearn are you using?

I see that in sklearn version 0.18.1 , passing 1d arrays as data is deprecated and gives a warning as below and does not give the desired result.

DeprecationWarning: Passing 1d arrays as data is deprecated in 0.17 and will raise ValueError in 0.19. Reshape your data either using X.reshape(-1, 1) if your data has a single feature or X.reshape(1, -1) if it contains a single sample.
  DeprecationWarning)

Try replacing the following line of code

```<code>onehotlabels = enc.transform(Y_2).toarray()
</code>```

to one below

```<code>onehotlabels = enc.transform(Y_2.reshape((-1,1)).toarray()
</code>```

or you may use pd.get_dummies to get the one hot coded feature matrix.

Body:
I am trying to train a model that reads data from a csv as the training data. To do this I am trying to conduct one hot encoding on the categorical features, and then pass the resulting arrays of 1s and 0s in as features, along with just the vanilla numerical features.

I have the following code:

X = pd.read_csv('Data2Cut.csv')

Y = X.select_dtypes(include=[object])

le = preprocessing.LabelEncoder()

Y_2 = Y.apply(le.fit_transform)

enc = preprocessing.OneHotEncoder()

enc.fit(Y_2)

onehotlabels = enc.transform(Y_2).toarray()
onehotlabels.shape

features = []
labels = []
mycsv = csv.reader(open('Data2Cut.csv'))
indexCount = 0
for row in mycsv:
  if indexCount < 8426:
    features.append([onehotlabels[indexCount], row[1], row[2], row[3], row[6], row[8], row[9], row[10], row[11]])
    labels.append(row[12])
    indexCount = indexCount + 1

training_data = np.array(features, dtype = 'float_')
training_labels = np.array(labels, dtype = 'float_')

log = linear_model.LogisticRegression()
log = log.fit(training_data, training_labels)
joblib.dump(log, "modelLogisticRegression.pkl")

It seems to be getting to the line:

training_data = np.array(features, dtype = 'float_')

Before it crashes giving the following error:

ValueError: setting an array element with a sequence.

I figure this is a result of the one hot encoded values being arrays and not floats. How can I change/tweak this code to handle the categorical and numerical features as training data?

Edit: an example of a row i am feeding in, where each column is a feature is:

mobile, 1498885897, 17491407,   23911,  west coast, 2,  seagull, 18,    41.0666666667,  [0.325, 0.35],  [u'text', u'font', u'writing', u'line'],    102, 5
#...

Body:
Which version of sklearn are you using?

I see that in sklearn version 0.18.1 , passing 1d arrays as data is deprecated and gives a warning as below and does not give the desired result.

DeprecationWarning: Passing 1d arrays as data is deprecated in 0.17 and will raise ValueError in 0.19. Reshape your data either using X.reshape(-1, 1) if your data has a single feature or X.reshape(1, -1) if it contains a single sample.
  DeprecationWarning)

Try replacing the following line of code

onehotlabels = enc.transform(Y_2).toarray()

to one below

onehotlabels = enc.transform(Y_2.reshape((-1,1)).toarray()

or you may use pd.get_dummies to get the one hot coded feature matrix.


问:
Google Map not loading with separate files
I can't see the google map on my monitor, but when I put all the code in a single html file and use script tags it works.

Index.html file is:

```<code><!DOCTYPE html>
<html>
  <head>
    <title>Simple Map</title>
    <meta name="viewport" content="initial-scale=1.0">
    <meta charset="utf-8">
    <link rel="stylesheet" href="style.css">
    <script src="script.js"></script>
  </head>
  <body>
    <div id="map"></div>

    <script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyBIpWlWVDAqVEyW20SX6MfThL-iz9IWeQA&callback=initMap"
    ></script>
  </body>
</html>
</code>```

Script.js file is:

```<code>function initMap() {

    var map;
            map = new google.maps.Map(document.getElementById('map'),
            {
              center: {  lat: -34.397,
                         lng: 150.644
                      },
              zoom: 8
            }
            );
          }
</code>```

style.css file is:

```<code>* element that contains the map. */
  #map {
    height: 100%;
  }
  /* Optional: Makes the sample page fill the window. */
  html, body {
    height: 100%;
    margin: 0;
    padding: 0;
  }
</code>```

答:
I consolidated your HTML and it works fine. For some reason, your callback function is not working when in a separate file.</p>

```<code><!DOCTYPE html>
<html>
  <head>
    <title>Simple Map</title>
    <meta name="viewport" content="initial-scale=1.0">
    <meta charset="utf-8">
    <style>
        #map {
        height: 100%;
    }
      html, body {
        height: 100%;
        margin: 0;
        padding: 0;
      }
    </style>
  <script>
  function initMap() {
    var map;
    map = new google.maps.Map(document.getElementById('map'),
    {
      center: {  lat: -34.397,  lng: 150.644},
      zoom: 8
    }
    );
   }
  </script>
  </head>
  <body>
    <div id="map"></div>
    <script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyBIpWlWVDAqVEyW20SX6MfThL-iz9IWeQA&callback=initMap"
    ></script>
  </body>
</html>
</code>```

Body:
I can't see the google map on my monitor, but when I put all the code in a single html file and use script tags it works.

Index.html file is:

<!DOCTYPE html>

    <title>Simple Map</title>
    <meta name="viewport" content="initial-scale=1.0">
    <meta charset="utf-8">
    <link rel="stylesheet" href="style.css">

Script.js file is:

function initMap() {

    var map;
            map = new google.maps.Map(document.getElementById('map'),
            {
              center: {  lat: -34.397,
                         lng: 150.644
                      },
              zoom: 8
            }
            );
          }

style.css file is:

* element that contains the map. */
  #map {
    height: 100%;
  }
  /* Optional: Makes the sample page fill the window. */
  html, body {
    height: 100%;
    margin: 0;
    padding: 0;
  }

Body:
I consolidated your HTML and it works fine. For some reason, your callback function is not working when in a separate file.

<!DOCTYPE html>
<html>
  <head>
    <title>Simple Map</title>
    <meta name="viewport" content="initial-scale=1.0">
    <meta charset="utf-8">
    <style>
        #map {
        height: 100%;
    }
      html, body {
        height: 100%;
        margin: 0;
        padding: 0;
      }
    </style>
  <script>
  function initMap() {
    var map;
    map = new google.maps.Map(document.getElementById('map'),
    {
      center: {  lat: -34.397,  lng: 150.644},
      zoom: 8
    }
    );
   }
  </script>
  </head>
  <body>
    <div id="map"></div>
    <script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyBIpWlWVDAqVEyW20SX6MfThL-iz9IWeQA&callback=initMap"
    ></script>
  </body>
</html>


问:
Very simple RogueLike in F#, making it more "functional"
I have some existing C# code for a very, very simple RogueLike engine. It is deliberately naive in that I was trying to do the minimum amount as simply as possible. All it does is move an @ symbol around a hardcoded map using the arrow keys and System.Console:

```<code>//define the map
var map = new List<string>{
  "                                        ",
  "                                        ",
  "                                        ",
  "                                        ",
  "    ###############################     ",
  "    #                             #     ",
  "    #         ######              #     ",
  "    #         #    #              #     ",
  "    #### #### #    #              #     ",
  "       # #  # #    #              #     ",
  "       # #  # #    #              #     ",
  "    #### #### ######              #     ",
  "    #              =              #     ",
  "    #              =              #     ",
  "    ###############################     ",
  "                                        ",
  "                                        ",
  "                                        ",
  "                                        ",
  "                                        "
};

//set initial player position on the map
var playerX = 8;
var playerY = 6;

//clear the console
Console.Clear();

//send each row of the map to the Console
map.ForEach( Console.WriteLine );

//create an empty ConsoleKeyInfo for storing the last key pressed
var keyInfo = new ConsoleKeyInfo( );

//keep processing key presses until the player wants to quit
while ( keyInfo.Key != ConsoleKey.Q ) {
  //store the player's current location
  var oldX = playerX;
  var oldY = playerY;

  //change the player's location if they pressed an arrow key
  switch ( keyInfo.Key ) {
    case ConsoleKey.UpArrow:
      playerY--;
      break;
    case ConsoleKey.DownArrow:
      playerY++;
      break;
    case ConsoleKey.LeftArrow:
      playerX--;
      break;
    case ConsoleKey.RightArrow:
      playerX++;
      break;
  }

  //check if the square that the player is trying to move to is empty
  if( map[ playerY ][ playerX ] == ' ' ) {
    //ok it was empty, clear the square they were standing on before
    Console.SetCursorPosition( oldX, oldY );
    Console.Write( ' ' );
    //now draw them at the new square
    Console.SetCursorPosition( playerX, playerY );
    Console.Write( '@' );
  } else {
    //they can't move there, change their location back to the old location
    playerX = oldX;
    playerY = oldY;
  }

  //wait for them to press a key and store it in keyInfo
  keyInfo = Console.ReadKey( true );
}
</code>```

I was playing around with doing it in F#, initially I was trying to write it using functional concepts, but turned out I was a bit over my head, so I did pretty much a straight port - it's not really an F# program (though it compiles and runs) it's a procedural program written in F# syntax:

```<code>open System

//define the map
let map = [ "                                        ";
            "                                        ";
            "                                        ";
            "                                        ";
            "    ###############################     ";
            "    #                             #     ";
            "    #         ######              #     ";
            "    #         #    #              #     ";
            "    #### #### #    #              #     ";
            "       # #  # #    #              #     ";
            "       # #  # #    #              #     ";
            "    #### #### ######              #     ";
            "    #              =              #     ";
            "    #              =              #     ";
            "    ###############################     ";
            "                                        ";
            "                                        ";
            "                                        ";
            "                                        ";
            "                                        " ]

//set initial player position on the map
let mutable playerX = 8
let mutable playerY = 6

//clear the console
Console.Clear()

//send each row of the map to the Console
map |> Seq.iter (printfn "%s")

//create an empty ConsoleKeyInfo for storing the last key pressed
let mutable keyInfo = ConsoleKeyInfo()

//keep processing key presses until the player wants to quit
while not ( keyInfo.Key = ConsoleKey.Q ) do
    //store the player's current location
    let mutable oldX = playerX
    let mutable oldY = playerY

    //change the player's location if they pressed an arrow key
    if keyInfo.Key = ConsoleKey.UpArrow then
        playerY <- playerY - 1
    else if keyInfo.Key = ConsoleKey.DownArrow then
        playerY <- playerY + 1
    else if keyInfo.Key = ConsoleKey.LeftArrow then
        playerX <- playerX - 1
    else if keyInfo.Key = ConsoleKey.RightArrow then
        playerX <- playerX + 1

    //check if the square that the player is trying to move to is empty
    if map.Item( playerY ).Chars( playerX ) = ' ' then
        //ok it was empty, clear the square they were standing on
        Console.SetCursorPosition( oldX, oldY )
        Console.Write( ' ' )
        //now draw them at the new square
        Console.SetCursorPosition( playerX, playerY )
        Console.Write( '@' )
    else
        //they can't move there, change their location back to the old location
        playerX <- oldX
        playerY <- oldY

    //wait for them to press a key and store it in keyInfo
    keyInfo <- Console.ReadKey( true )
</code>```

So my question is, what do I need to learn in order to rewrite this more functionally, can you give me some hints, a vague overview, that kind of thing.

I'd prefer a shove in the right direction rather than just seeing some code, but if that's the easiest way for you to explain it to me then fine, but in that case can you please also explain the "why" rather the "how" of it?

答:
That's a nice little game :-). In functional programming, you'd want to avoid using mutable state (as others pointed out) and you'd also want to write the core of your game as a function that doesn't have any side-effects (e.g. reading from console and writing).

The key part of the game is the function that controls the position. You could refactor your code to  have a function with the type signature:

```<code>val getNextPosition : (int * int) -> ConsoleKey -> option<int * int>
</code>```

The function returns None if the game should quit. Otherwise it returns Some(posX, posY) where posX and posY are your new locations for the @ symbol. By doing the change, you get a nice functional core and the function getNextPosition is also easy to test (because it always returns the same result for the same inputs).

To use the function, the best option is to write the looping using recursion. The structure of the main function would look like this:

```<code>let rec playing pos =
  match getNextPosition pos (Console.ReadKey()) with
  | None -> () // Quit the game
  | Some(newPos) ->
     // This function redraws the screen (this is a side-effect,
     // but it is localized to a single function)
     redrawScreen pos newPos
     playing newPos
</code>```

Body:
I have some existing C# code for a very, very simple RogueLike engine. It is deliberately naive in that I was trying to do the minimum amount as simply as possible. All it does is move an @ symbol around a hardcoded map using the arrow keys and System.Console:

//define the map
var map = new List<string>{
  "                                        ",
  "                                        ",
  "                                        ",
  "                                        ",
  "    ###############################     ",
  "    #                             #     ",
  "    #         ######              #     ",
  "    #         #    #              #     ",
  "    #### #### #    #              #     ",
  "       # #  # #    #              #     ",
  "       # #  # #    #              #     ",
  "    #### #### ######              #     ",
  "    #              =              #     ",
  "    #              =              #     ",
  "    ###############################     ",
  "                                        ",
  "                                        ",
  "                                        ",
  "                                        ",
  "                                        "
};

//set initial player position on the map
var playerX = 8;
var playerY = 6;

//clear the console
Console.Clear();

//send each row of the map to the Console
map.ForEach( Console.WriteLine );

//create an empty ConsoleKeyInfo for storing the last key pressed
var keyInfo = new ConsoleKeyInfo( );

//keep processing key presses until the player wants to quit
while ( keyInfo.Key != ConsoleKey.Q ) {
  //store the player's current location
  var oldX = playerX;
  var oldY = playerY;

  //change the player's location if they pressed an arrow key
  switch ( keyInfo.Key ) {
    case ConsoleKey.UpArrow:
      playerY--;
      break;
    case ConsoleKey.DownArrow:
      playerY++;
      break;
    case ConsoleKey.LeftArrow:
      playerX--;
      break;
    case ConsoleKey.RightArrow:
      playerX++;
      break;
  }

  //check if the square that the player is trying to move to is empty
  if( map[ playerY ][ playerX ] == ' ' ) {
    //ok it was empty, clear the square they were standing on before
    Console.SetCursorPosition( oldX, oldY );
    Console.Write( ' ' );
    //now draw them at the new square
    Console.SetCursorPosition( playerX, playerY );
    Console.Write( '@' );
  } else {
    //they can't move there, change their location back to the old location
    playerX = oldX;
    playerY = oldY;
  }

  //wait for them to press a key and store it in keyInfo
  keyInfo = Console.ReadKey( true );
}

I was playing around with doing it in F#, initially I was trying to write it using functional concepts, but turned out I was a bit over my head, so I did pretty much a straight port - it's not really an F# program (though it compiles and runs) it's a procedural program written in F# syntax:

open System

//define the map
let map = [ "                                        ";
            "                                        ";
            "                                        ";
            "                                        ";
            "    ###############################     ";
            "    #                             #     ";
            "    #         ######              #     ";
            "    #         #    #              #     ";
            "    #### #### #    #              #     ";
            "       # #  # #    #              #     ";
            "       # #  # #    #              #     ";
            "    #### #### ######              #     ";
            "    #              =              #     ";
            "    #              =              #     ";
            "    ###############################     ";
            "                                        ";
            "                                        ";
            "                                        ";
            "                                        ";
            "                                        " ]

//set initial player position on the map
let mutable playerX = 8
let mutable playerY = 6

//clear the console
Console.Clear()

//send each row of the map to the Console
map |> Seq.iter (printfn "%s")

//create an empty ConsoleKeyInfo for storing the last key pressed
let mutable keyInfo = ConsoleKeyInfo()

//keep processing key presses until the player wants to quit
while not ( keyInfo.Key = ConsoleKey.Q ) do
    //store the player's current location
    let mutable oldX = playerX
    let mutable oldY = playerY

    //change the player's location if they pressed an arrow key
    if keyInfo.Key = ConsoleKey.UpArrow then
        playerY <- playerY - 1
    else if keyInfo.Key = ConsoleKey.DownArrow then
        playerY <- playerY + 1
    else if keyInfo.Key = ConsoleKey.LeftArrow then
        playerX <- playerX - 1
    else if keyInfo.Key = ConsoleKey.RightArrow then
        playerX <- playerX + 1

    //check if the square that the player is trying to move to is empty
    if map.Item( playerY ).Chars( playerX ) = ' ' then
        //ok it was empty, clear the square they were standing on
        Console.SetCursorPosition( oldX, oldY )
        Console.Write( ' ' )
        //now draw them at the new square
        Console.SetCursorPosition( playerX, playerY )
        Console.Write( '@' )
    else
        //they can't move there, change their location back to the old location
        playerX <- oldX
        playerY <- oldY

    //wait for them to press a key and store it in keyInfo
    keyInfo <- Console.ReadKey( true )

So my question is, what do I need to learn in order to rewrite this more functionally, can you give me some hints, a vague overview, that kind of thing.

I'd prefer a shove in the right direction rather than just seeing some code, but if that's the easiest way for you to explain it to me then fine, but in that case can you please also explain the "why" rather the "how" of it?

Body:
That's a nice little game :-). In functional programming, you'd want to avoid using mutable state (as others pointed out) and you'd also want to write the core of your game as a function that doesn't have any side-effects (e.g. reading from console and writing).

The key part of the game is the function that controls the position. You could refactor your code to  have a function with the type signature:

val getNextPosition : (int * int) -> ConsoleKey -> option<int * int>

The function returns None if the game should quit. Otherwise it returns Some(posX, posY) where posX and posY are your new locations for the @ symbol. By doing the change, you get a nice functional core and the function getNextPosition is also easy to test (because it always returns the same result for the same inputs).

To use the function, the best option is to write the looping using recursion. The structure of the main function would look like this:

let rec playing pos =
  match getNextPosition pos (Console.ReadKey()) with
  | None -> () // Quit the game
  | Some(newPos) ->
     // This function redraws the screen (this is a side-effect,
     // but it is localized to a single function)
     redrawScreen pos newPos
     playing newPos


问:
Concatenating specific words together in an array list
I have a problem, suppose I have a text file like so:

Name Surname, number, number ..... number\n
Name Middle  Surname, number, number......number\n
Name, number, number ..... number\n

I wanted to keep the "names + surname" or "names +middle +surname" in each line into one array list index.
For Example, I want "Name Surname" of the first line in one index of an array list.

I did try using a string variable and adding the two elements together in a loop. But as you see the names aren't really of any specific type.
How would I do it? I would really appreciate the help!

答:
I suggest to split the line :

```<code>String[] parts = line.split(",");
</code>```

This gives you an array with all parts.  parts[0] holds the name, and all the numbers following in subsequant indexes.

Body:
I suggest to split the line :

String[] parts = line.split(",");

This gives you an array with all parts.  parts[0] holds the name, and all the numbers following in subsequant indexes.


问:
Pick a number from two columns and calculate
A given file contains pairs of <two-digit number, amount>.  Then take a toss-up two-digit number (called X), and compute the win/loss amount.  The win/loss rule is if the input number matches X, then it’s a win and the winning total is (amount * 70); otherwise, it’s a loss of (-amount).

For example: [ticket.txt]
  09 10
  13 15
  25 21

If the toss-up number is 09, the win/loss amount of the ticket is (10 * 70 - 15 - 21)

If the toss-up number is 42, the win/loss amount of the ticket is (-10 - 15 - 21).

This is my beginner project. I stuck at calculating the win amount and lost amount.
This is my problem

```<code>#include <iostream>
#include <fstream>

using namespace std;
int line1[100]; // array that can hold 100 numbers for 1st column
int line2[100]; // array that can hold 100 numbers for 2nd column
int main()
{
    int winNum, winAmount, lostAmount;
    int num = 0; // num start at 0
    ifstream inFile;
    inFile.open("Ticket.txt"); //open File
    if (inFile.fail())
    {
        cout << "Fail to open the file" << endl;
        return 1;
    }
    cout << "Numbers from File: " << endl;
    while (!inFile.eof()) // read File to end of file
        {
            inFile >> line1[num]; // read first column, the first column is the number that user choosing
            inFile >> line2[num]; // read second column, the second column is the amount of money that user paying
            cout << "\n" << line1[num] << "\t" << line2[num];
            ++num;
        }
    inFile.close();
    cout << endl;
    cout << "Enter the toss-up number: "; // enter the win number
    cin >> winNum;
    if (line1[num] == winNum)
    {
        winAmount = line2[num] * 70; //  number user choose = win number, winAmount = winAmount * 70 - lostAmount
        cout << winAmount;
        }
        else
        {
            lostAmount =- line2[num]; //number user choose != win number, the amount will be -lost amounts
cout << lostAmount;
        }
        cout << endl << endl;
        system("pause");
        return 0;
    }
</code>```

答:
When you test line1[num] == winNum (and all the operations carried out after that) you're using the value of num that you modified with ++num;, this means you're working with empty or not meaningful values for both line1 and line2. For example, if the 3 rows of values showed in your "ticket.txt" are used, they are stored in postions 0, 1 and 2 of the arrays, while the num has a value of 4 at the end.

If I understood what you are trying to achieve, you should put the if-else statement in a for loop that goes from 0 to num, and then every operation on line1 and line2 should be done with the looping variable as an index.
Also, move the cout just after the loop if you want only total amounts to be displayed.

Body:
A given file contains pairs of <two-digit number, amount>.  Then take a toss-up two-digit number (called X), and compute the win/loss amount.  The win/loss rule is if the input number matches X, then it’s a win and the winning total is (amount * 70); otherwise, it’s a loss of (-amount).

For example: [ticket.txt]
  09 10
  13 15
  25 21

If the toss-up number is 09, the win/loss amount of the ticket is (10 * 70 - 15 - 21)

If the toss-up number is 42, the win/loss amount of the ticket is (-10 - 15 - 21).

This is my beginner project. I stuck at calculating the win amount and lost amount.
This is my problem

#include <iostream>
#include <fstream>

using namespace std;
int line1[100]; // array that can hold 100 numbers for 1st column
int line2[100]; // array that can hold 100 numbers for 2nd column
int main()
{
    int winNum, winAmount, lostAmount;
    int num = 0; // num start at 0
    ifstream inFile;
    inFile.open("Ticket.txt"); //open File
    if (inFile.fail())
    {
        cout << "Fail to open the file" << endl;
        return 1;
    }
    cout << "Numbers from File: " << endl;
    while (!inFile.eof()) // read File to end of file
        {
            inFile >> line1[num]; // read first column, the first column is the number that user choosing
            inFile >> line2[num]; // read second column, the second column is the amount of money that user paying
            cout << "\n" << line1[num] << "\t" << line2[num];
            ++num;
        }
    inFile.close();
    cout << endl;
    cout << "Enter the toss-up number: "; // enter the win number
    cin >> winNum;
    if (line1[num] == winNum)
    {
        winAmount = line2[num] * 70; //  number user choose = win number, winAmount = winAmount * 70 - lostAmount
        cout << winAmount;
        }
        else
        {
            lostAmount =- line2[num]; //number user choose != win number, the amount will be -lost amounts
cout << lostAmount;
        }
        cout << endl << endl;
        system("pause");
        return 0;
    }


问:
Better way to Check for values
Is there a more elegant way to do this?

```<code>if(response && response.body && response.body.data) {
  const users = response.body.data
  dispatch(UserActions.usersReceived(users))
}
</code>```

Meaning the response && response.body && response.body.data ?

答:
If you won't check an object existence before calling its property, you can get exception and the execution stop. Therefore, someone would suggest a try catch.

However, from my experience, it is better to check this way, explicit, easy to read and maintenance code is always good.

Title: Better way to Check for values

Body:
Is there a more elegant way to do this?

if(response && response.body && response.body.data) {
  const users = response.body.data
  dispatch(UserActions.usersReceived(users))
}

Meaning the response && response.body && response.body.data ?


问:
C# How to get multiple elements in textfile with in basics for
Here is file data that I want to use and I´m more familiar with python and I can´t find solution what I need here. Thanks for helping.

prices:

Some sold "something 1", price is 20 £

Some sold "something 2", price is 40 £

Some sold "something 3", price is 60 £

Some sold "something 4", price is 80 £

Some sold "something 5", price is 100 £

```<code>using System;
using System.IO;

namespace CalcPrices
{
    internal class Program
    {
        private static void Main()
        {
            string[] lines = File.ReadAllLines(
                @"C:\Users\Eggii\Desktop\code\c# katse\GoodsPrices\GoodsPrices\bin\Debug\PriceOfSoldGoods.txt");

            for (int i = 0; i < lines.Length; i++)
            {
                string[] line = lines[i].Split();

                for (int j = 0; j < line.Length; j++)
                {
                    Console.WriteLine(line[6]);

                    // Output should be something like:
                    // 20
                    // 40
                    // 60
                    // 80
                    // 100
                    // because I want every 7th element in line
                }
            }
        }
    }
}
</code>```

答:
This is what you need to do:</p>

```<code>string[] lines = File.ReadAllLines(@"C:\Users\Eggii\Desktop\code\c# katse\GoodsPrices\GoodsPrices\bin\Debug\PriceOfSoldGoods.txt");
foreach(string line in lines)
{
    Console.WriteLine(line.Split(new[] { "price is " }, StringSplitOptions.None)[1].Replace(" £", ""));
}
</code>```

Body:
Here is file data that I want to use and I´m more familiar with python and I can´t find solution what I need here. Thanks for helping.

prices:

Some sold "something 1", price is 20 £

Some sold "something 2", price is 40 £

Some sold "something 3", price is 60 £

Some sold "something 4", price is 80 £

Some sold "something 5", price is 100 £

using System;
using System.IO;

namespace CalcPrices
{
    internal class Program
    {
        private static void Main()
        {
            string[] lines = File.ReadAllLines(
                @"C:\Users\Eggii\Desktop\code\c# katse\GoodsPrices\GoodsPrices\bin\Debug\PriceOfSoldGoods.txt");

            for (int i = 0; i < lines.Length; i++)
            {
                string[] line = lines[i].Split();

                for (int j = 0; j < line.Length; j++)
                {
                    Console.WriteLine(line[6]);

                    // Output should be something like:
                    // 20
                    // 40
                    // 60
                    // 80
                    // 100
                    // because I want every 7th element in line
                }
            }
        }
    }
}

Body:
This is what you need to do:

string[] lines = File.ReadAllLines(@"C:\Users\Eggii\Desktop\code\c# katse\GoodsPrices\GoodsPrices\bin\Debug\PriceOfSoldGoods.txt");
foreach(string line in lines)
{
    Console.WriteLine(line.Split(new[] { "price is " }, StringSplitOptions.None)[1].Replace(" £", ""));
}


问:
I have a working Angular 4 app. Is there an easy way to extend it to be compatible with Ionic 3 framework?
I have recently finished creating a Angular 4 app which is fully deployed and working fine as a single page web application running on top of browsers.

I want to develop mobile apps for this (Android/iOS), but I really want to avoid starting from the scratch. Since I am not familiar with mobile developments, I want to minimize my effort on maintaining them by using Ionic framework.

Since Ionic 3 is built on top of Angular 4, I do see a lot of similarities in components/modules.

However, 'html' files and views seem to be little bit different, which I am okay with developing similar ones if I must need to do.

Is there a way which I can easily re-use existing components in my Angular 4 components in Ionic app? Can I assume that if components that I wrote for Angular 4 works in Angular 4, should those components be also compatible with Ionic?

If I can re-use the components, would it be possible to maintain Angular 4 app and Ionic 3 app in the same code base? (e.g. I don't want to copy components to a separate Ionic project and have to maintain of 2 copies the same component in different 2 different locations.)

I would love to see example codebase that is compatible with Angular 4 & Ionic 3, but have not found one yet. I am not sure if that is doable... but angular.io website has the following words in the front page.

One framework. Mobile & desktop

答:
I managed to switch one of my apps from Angular 2 to Ionic 2 before, and it was really simple.

You can't do any magic trick to make the switch, but it's possible.

All you have to do is copy pasting + few modifications for each component/module.

Some things you might consider when switching:

You should use the Ionic UI components in order to benefit from the cross-platofrm UI. e.g <button ion-button>, <ion-select>, etc..

You should rewrite your app routes to work with Ionic Nav. It's really quick since you don't have to declare all your routes, and you can simply navigate by navCtrl.push('MyPageName'). No import needed!

In Ionic 3 each page/component is a module, so you will have to wrap your modules/components with @IonicPage

Once you are familiar with Ionic 3, create a new app, create your components using the Ionic CLI then start copy pasting and modifying each component logic and template to fit Ionic 3 as described above.

Not sure if I missed something but that's all what you have to do in general. I managed to convert my 50 components app to Ionic within one day.

If you are not sure you need Ionic, consider just using cordova or phonegap to wrap your app for mobile.


问:
Get topics terms only with LDA
I applied LDA from gensim package on the corpus and I get the probability with each term. My problem is how I get only the terms without their probability.
Here is my code:

```<code>K = ldamodel.num_topics
t = 0
topicWordProbMat = ldamodel.print_topics(K)
for  topic_dist in topicWordProbMat:
    print('Topic #',t,topic_dist)
    t = t + 1
</code>```

The output as example is like this:

```<code>Topic # 0 '0.181*things + 0.181*amazon + 0.181*good
Topic # 1 '0.031*nokia + 0.031*microsoft + 0.031*apple
</code>```

and I want it as this:

```<code>Topic # 0 things amazon good
Topic # 1 nokia microsoft apple
</code>```

any idea how? Thanks in advance

答:
Gensim has a show_topic method built in which will display n most probable words for each topic. The following will return the top 10 words in each topic as a dict with  key value pairs.

```<code>topn_words = {'Topic_' + str(i): [word for word, prob in lda.show_topic(i, topn=10)] for i in range(0, lda.num_topics)}
</code>```

Similar question here: How to generate word clouds from LDA models in Python?

Title: Get topics terms only with LDA

Body:
I applied LDA from gensim package on the corpus and I get the probability with each term. My problem is how I get only the terms without their probability.
Here is my code:

K = ldamodel.num_topics
t = 0
topicWordProbMat = ldamodel.print_topics(K)
for  topic_dist in topicWordProbMat:
    print('Topic #',t,topic_dist)
    t = t + 1

The output as example is like this:

Topic # 0 '0.181*things + 0.181*amazon + 0.181*good
Topic # 1 '0.031*nokia + 0.031*microsoft + 0.031*apple

and I want it as this:

Topic # 0 things amazon good
Topic # 1 nokia microsoft apple

any idea how? Thanks in advance

Body:
Gensim has a show_topic method built in which will display n most probable words for each topic. The following will return the top 10 words in each topic as a dict with  key value pairs.

topn_words = {'Topic_' + str(i): [word for word, prob in lda.show_topic(i, topn=10)] for i in range(0, lda.num_topics)}

Similar question here: How to generate word clouds from LDA models in Python?


问:
cordova build android give error "The system cannot find the path specified."
I am new to cordova. I have successfully created my first project using

cordova create FirstProject com.phonegappro.hello HelloWorld

cordova platform add android

cordova build android I am getting following error.

```<code>D:\wamp\www\FirstProject>cordova build android
ANDROID_HOME=C:\Users\Santosh\AppData\Local\Android\sdk
JAVA_HOME=C:\Program Files\Java\jdk1.8.0_131
The system cannot find the path specified.
Error: cmd: Command failed with exit code 1
</code>```

what I am doing wrong ?
I have android studio installed. phonegab and cordova are latest with Node js higher v6.10.2

答:
The problem was with the Gradle. Previously I had uninstalled android studio. And now again when I install it there was two folder for Android studio. Android Studio and Android Studio 1 by default it was trying to access the Gradle inside the Android Studio which was empty. I deleted it and renamed the Android Studio 1 to Android Studio.

path : C:\Program Files\Android\Android Studio

It worked for me.

Body:
I am new to cordova. I have successfully created my first project using

cordova create FirstProject com.phonegappro.hello HelloWorld

cordova platform add android

cordova build android I am getting following error.

D:\wamp\www\FirstProject>cordova build android
ANDROID_HOME=C:\Users\Santosh\AppData\Local\Android\sdk
JAVA_HOME=C:\Program Files\Java\jdk1.8.0_131
The system cannot find the path specified.
Error: cmd: Command failed with exit code 1

what I am doing wrong ?
I have android studio installed. phonegab and cordova are latest with Node js higher v6.10.2


答:
If the code below will take 2 seconds, then the time will change.

```<code>//MY_ISSUE: This returns the same value every time
for(int a = 0; a < 10; a++) {
    System.out.println("Time: " + nClock.getTime());
}
</code>```

However a for loop with 10 iterations and a system.out will not even take a millisecond so it will not change.

Why 2 seconds? because you have a Thread.sleep in your runnable code.

```<code>Thread.sleep(2000);
</code>```

Which means, the next update will be in 2 seconds.

And use System.nanoTime() instead of System.currentTimeMillis() since you really wanted nano time not millis.

Updated:

In my machine

```<code>public static void main(String args[]) {
    long start = System.currentTimeMillis();
    for(int a = 0; a < 10; a++) {
        System.out.println("Iterating " + a);
    }
    long end = System.currentTimeMillis();
    System.out.println("Start = " + start);
    System.out.println("End   = " + end);
}
</code>```

Result, there is no difference in the start time and end time

```<code>Iterating 0
Iterating 1
Iterating 2
Iterating 3
Iterating 4
Iterating 5
Iterating 6
Iterating 7
Iterating 8
Iterating 9
Start = 1499592836298
End   = 1499592836298
</code>```

That code block executed so fast that it did not take even a single millisecond. Depending on the timing, it may take 1 millisecond.

Changing it to System.nanoTime()

```<code>public static void main(String args[]) {
    long start = System.nanoTime();
    for(int a = 0; a < 10; a++) {
        System.out.println("Iterating " + a);
    }
    long end = System.nanoTime();
    System.out.println("Start = " + start);
    System.out.println("End   = " + end);
}
</code>```

Result, there is a difference in the start time and end time.

```<code>Iterating 0
Iterating 1
Iterating 2
Iterating 3
Iterating 4
Iterating 5
Iterating 6
Iterating 7
Iterating 8
Iterating 9
Start = 1012518090518837
End   = 1012518091012960
</code>```

Title: Java: Volatile variable not updating (get and set methods not working)

Body:
I have a Runnable "NanoClock" class which keeps updating a private volatile double value in its run() method.

This class also has a getTime() method which returns the double value. Another class ("Master") is constructing the NanoClock class and creates a thread, as well as calling the start() method.

After it did this it calls the getTime() method several times (with a delay), but the value is not updating. What am I doing wrong?

NanoClock.java :

public class NanoClock implements Runnable {
    private volatile boolean running;
    private volatile double time;
    public NanoClock() {
        time = System.currentTimeMillis();
    }
    @Override
    public void run() {
        running = true;
        while(running) {
            try {
                if(System.currentTimeMillis() > time) {
                    time = System.currentTimeMillis();
                }
              //This returns the updated value continuously when commented out
              //System.out.println("Time: " + String.format("%.6f", unix_time));
                Thread.sleep(2000);
            } catch(Exception exc) {
                exc.printStackTrace();
                System.exit(1);
            }
        }
    }
    public double getTime() {
        return time;
    }
    public void end() {
        running = false;
    }
}

Master.java:

public class Master {
    public static void main(String[] args) {
        try {
            NanoClock nClock = new NanoClock();
            Thread clockThread = new Thread(new NanoClock());
            clockThread.setPriority(10);
            clockThread.start();
            //MY_ISSUE: This returns the same value every time
            for(int a = 0; a < 10; a++) {
                System.out.println("Time: " + nClock.getTime());
            }
            //MY_ISSUE: This cannot stop the while loop - I tested it with
            //the println in the NanoClock class.
            nClock.end();
            System.out.println("Done!");
        catch(Exception e) {
            e.printStackTrace();
            System.exit(1);
        }
    }
}

Body:
If the code below will take 2 seconds, then the time will change.

//MY_ISSUE: This returns the same value every time
for(int a = 0; a < 10; a++) {
    System.out.println("Time: " + nClock.getTime());
}

However a for loop with 10 iterations and a system.out will not even take a millisecond so it will not change.

Why 2 seconds? because you have a Thread.sleep in your runnable code.

Thread.sleep(2000);

Which means, the next update will be in 2 seconds.

And use System.nanoTime() instead of System.currentTimeMillis() since you really wanted nano time not millis.

Updated:

In my machine

public static void main(String args[]) {
    long start = System.currentTimeMillis();
    for(int a = 0; a < 10; a++) {
        System.out.println("Iterating " + a);
    }
    long end = System.currentTimeMillis();
    System.out.println("Start = " + start);
    System.out.println("End   = " + end);
}

Result, there is no difference in the start time and end time

Iterating 0
Iterating 1
Iterating 2
Iterating 3
Iterating 4
Iterating 5
Iterating 6
Iterating 7
Iterating 8
Iterating 9
Start = 1499592836298
End   = 1499592836298

That code block executed so fast that it did not take even a single millisecond. Depending on the timing, it may take 1 millisecond.

Changing it to System.nanoTime()

public static void main(String args[]) {
    long start = System.nanoTime();
    for(int a = 0; a < 10; a++) {
        System.out.println("Iterating " + a);
    }
    long end = System.nanoTime();
    System.out.println("Start = " + start);
    System.out.println("End   = " + end);
}

Result, there is a difference in the start time and end time.

Iterating 0
Iterating 1
Iterating 2
Iterating 3
Iterating 4
Iterating 5
Iterating 6
Iterating 7
Iterating 8
Iterating 9
Start = 1012518090518837
End   = 1012518091012960


问:
Laravel 5.2 Sessions Not Working Properly
I am working on laravel 5.2 project and have a problem with sessions. When I create a session, I can only access it from the blade template. If I want to access it from any of other classes, it is not possible. I'am using Laravel 5.2 and all of my routes are inside of the 'web' middleware. I searched the entire web but none of them has provided a solution to my problem.

Session creation code:

```<code><?php namespace App\Lib\Services;

$this->request->session()->put('errors', $this->errors);`
redirect()->back()->send();
</code>```

When I test the session in the view like below, it works (gives the intended data):

```<code>@extends('themes.backend.metronic.main')

@section('pageContent')
{{ dd(session ('errors')) }}
@endsection
</code>```

However, If I want to use it another class like below, it returns null:

```<code>namespace App\Lib\Themes\Errors;

function __construct($specs)
    {
        parent::__construct($specs);
        $this->setData();
        dd(session('errors')); // this returns null value
        $this->setErrorMsg();
    }
</code>```

Can anybody help me to solve this problem please?

答: Since you are accessing your session variable within a constructor of the class, it could be that your class is being created before you can set your session variables. Try setting your session variables first, and then create a new object of that class.</p>

Body:
I am working on laravel 5.2 project and have a problem with sessions. When I create a session, I can only access it from the blade template. If I want to access it from any of other classes, it is not possible. I'am using Laravel 5.2 and all of my routes are inside of the 'web' middleware. I searched the entire web but none of them has provided a solution to my problem.

Session creation code:

<?php namespace App\Lib\Services;

$this->request->session()->put('errors', $this->errors);`
redirect()->back()->send();

When I test the session in the view like below, it works (gives the intended data):

@extends('themes.backend.metronic.main')

@section('pageContent')
{{ dd(session ('errors')) }}
@endsection

However, If I want to use it another class like below, it returns null:

namespace App\Lib\Themes\Errors;

function __construct($specs)
    {
        parent::__construct($specs);
        $this->setData();
        dd(session('errors')); // this returns null value
        $this->setErrorMsg();
    }

Can anybody help me to solve this problem please?