问:
Show message when Tform2 is created?
I want to when Tform2 is created then show a message to user.
I use this code, but not work well.</p>

```<code>procedure TForm1.Button1Click(Sender: TObject);
var
   a:TForm2;
begin

if a=nil then
 begin
    a := TForm2.Create(Self);
    a.Show;
 end
 else
 begin
    showmessage('TForm2 is created');
 end;

end;
</code>```

答:
That's because you declare a as a local variable. Each time you enter TForm1.Button1Click this variable will be brand new and uninitialized even though there might still be a Form2. That means that the check for nil won't even work.

You should either:

Make a a global (like the Form2 global you get when you first create a form)

Make a part of the declaration of Form1 (you main form?) or a datamodule of other class  that lives throughout your entire program.

Don't use a variable at all, but check Screen.Forms to see if you got a Form2 in there.

[edit]

Like this:

```<code>var
  i: Integer;
begin
  // Check
  for i := 0 to Screen.FormCount - 1 do
  begin
    // Could use the 'is' operator too, but this checks the exact class instead
    // of descendants as well. And opposed to ClassNameIs, it will force you
    // to change the name here too if you decide to rename TForm2 to a more
    // useful name.
    if Screen.Forms[i].ClassType = TForm2 then
    begin
      ShowMessage('Form2 already exists');
      Exit;
    end;
  end;

  // Create and show.
  TForm2.Create(Self).Show;
end;
</code>```

Title: Show message when Tform2 is created?

Body:
I want to when Tform2 is created then show a message to user.
I use this code, but not work well.

procedure TForm1.Button1Click(Sender: TObject);
var
   a:TForm2;
begin

if a=nil then
 begin
    a := TForm2.Create(Self);
    a.Show;
 end
 else
 begin
    showmessage('TForm2 is created');
 end;

end;

Body:
That's because you declare a as a local variable. Each time you enter TForm1.Button1Click this variable will be brand new and uninitialized even though there might still be a Form2. That means that the check for nil won't even work.

You should either:

Make a a global (like the Form2 global you get when you first create a form)

Make a part of the declaration of Form1 (you main form?) or a datamodule of other class  that lives throughout your entire program.

Don't use a variable at all, but check Screen.Forms to see if you got a Form2 in there.

[edit]

Like this:

var
  i: Integer;
begin
  // Check
  for i := 0 to Screen.FormCount - 1 do
  begin
    // Could use the 'is' operator too, but this checks the exact class instead
    // of descendants as well. And opposed to ClassNameIs, it will force you
    // to change the name here too if you decide to rename TForm2 to a more
    // useful name.
    if Screen.Forms[i].ClassType = TForm2 then
    begin
      ShowMessage('Form2 already exists');
      Exit;
    end;
  end;

  // Create and show.
  TForm2.Create(Self).Show;
end;


来源: stackexchange

问:
DIV stops refreshing when new database entry is made
(UPDATE)
So the problem isn't the database entries or the auto-refresh (sort of).
I've narrowed down the problem to a function in my index.php, that determines the color of the entry to be displayed. This function seems to be undefined when the auto-refresh reloads the included PHP pages.

So this is a very annoying issue that breaks the whole purpose of my web-based application. I have tried to troubleshoot it and can't figure out why it's refusing to work. My only guess is that the PHP/MySQL calls are not also being re-run when the refresh occurs, but that can't be true, because when I trigger event #3 listed below, it disappears just fine. It just doesn't update when an entry exists.

Div ID "unitsAvail" works fine, even when a new entry is created/deleted.

1) Refreshes perfectly fine when no entries exist.
2) Stops refreshing when a new database entry is created.
2b) Refreshing the page does not fix the auto-refresh.
3) Starts refreshing again when that entry is deleted, whether or not the page was reloaded.

Note: The refreshing php pages consist of an HTML table, and PHP code to call MySQL queries. They don't consist of any divs, or any other conflicting things.

Note-2: I added time stamp echos to each div, and Active/pending are indeed stopping their auto-refresh when new DB entries are made. Units Available continues to refresh perfectly fine, and the time stamp updates.

(I'm thinking it might be better to just put those PHP pages inside this page, and refresh the div content instead. How would I change my auto refresh to do that, if that's a better method? What do I change .load() to?)

```<code>    <script src="java/jquery.js"></script>
    <script type="text/javascript">

    $(document).ready(function() {
        refreshActive();
    });

    function refreshActive() {
        $('#incActive').load('active.php', function() {
            setTimeout(refreshActive, 5000);
        });
        $('#incPending').load('pending.php', function() {
            setTimeout(refreshPending, 5000);
        });
        $('#unitsAvail').load('units.php', function() {
            setTimeout(refreshUnits, 5000);
        });
    }

    </script>
<body>
        <div id="fixed">

            <? include ("topmenu.php"); ?>

            <div id="backpanel">

                <div id="incActive">
                    <?
                    include "active.php";
                    ?>
                </div>

                <div id="incPending">
                    <?
                    include "pending.php";
                    ?>
                </div>

                <div id="unitsAvail">
                    <?
                    include "units.php";
                    ?>
                </div>

            </div>

        </div>

</body>
</code>```

答:
This could be caused by the load method throwing an exception. You should add some error handling to assist with debugging the issue.

Try using this to catch for any errors:

```<code>$('#incActive').load('active.php', function( response, status, xhr ) {
    if ( status == "error" ) {
        var msg = "Sorry but there was an error: ";
        $( "#error" ).html( msg + xhr.status + " " + xhr.statusText );
    }
    else{
        setTimeout(refreshActive, 5000);
    }
);
</code>```

ContentLicense: CC BY-SA 3.0

Body:
(UPDATE)
So the problem isn't the database entries or the auto-refresh (sort of).
I've narrowed down the problem to a function in my index.php, that determines the color of the entry to be displayed. This function seems to be undefined when the auto-refresh reloads the included PHP pages.

So this is a very annoying issue that breaks the whole purpose of my web-based application. I have tried to troubleshoot it and can't figure out why it's refusing to work. My only guess is that the PHP/MySQL calls are not also being re-run when the refresh occurs, but that can't be true, because when I trigger event #3 listed below, it disappears just fine. It just doesn't update when an entry exists.

Div ID "unitsAvail" works fine, even when a new entry is created/deleted.

1) Refreshes perfectly fine when no entries exist.
2) Stops refreshing when a new database entry is created.
2b) Refreshing the page does not fix the auto-refresh.
3) Starts refreshing again when that entry is deleted, whether or not the page was reloaded.

Note: The refreshing php pages consist of an HTML table, and PHP code to call MySQL queries. They don't consist of any divs, or any other conflicting things.

Note-2: I added time stamp echos to each div, and Active/pending are indeed stopping their auto-refresh when new DB entries are made. Units Available continues to refresh perfectly fine, and the time stamp updates.

(I'm thinking it might be better to just put those PHP pages inside this page, and refresh the div content instead. How would I change my auto refresh to do that, if that's a better method? What do I change .load() to?)

            <? include ("topmenu.php"); ?>

                    <?
                    include "active.php";
                    ?>

                    <?
                    include "pending.php";
                    ?>

                    <?
                    include "units.php";
                    ?>

Body:
This could be caused by the load method throwing an exception. You should add some error handling to assist with debugging the issue.

Try using this to catch for any errors:

$('#incActive').load('active.php', function( response, status, xhr ) {
    if ( status == "error" ) {
        var msg = "Sorry but there was an error: ";
        $( "#error" ).html( msg + xhr.status + " " + xhr.statusText );
    }
    else{
        setTimeout(refreshActive, 5000);
    }
);


问:
Jmeter switch off the SSL certificate
How to disable SSL certificate validation in Apache Jmeter 3.2
analogous to the switch in the postman "SSL-certificate verification on / off"?</p>

答:
JMeter does not validate certificate by default.
If you’re facing issues with ssl , it’s another cause.

As per your comment root cause was a missing header.
After adding those headers it worked:

Accept-Enconding=application/json

Content-Type=application / json

Title: Jmeter switch off the SSL certificate


问:
how to pull data from influxdb via API call?
i have pushed the data using the below api call in the database "dbvishnutest"

```<code>curl -XPOST http://<localhost>:8086/write?db=dbvishnutest --data-binary "weather,location=us-midwest temperature=82 1465839830100400200"
</code>```

Now i am trying to pull back the data using the below api call .

```<code>curl -i -XPOST -G http://<localhost>:8086/query?pretty=true --data-urlencode "dbvishnutest" --data-urlencode "q=select * from weather where location=us-midwest"
</code>```

i am getting the below error :

```<code>HTTP/1.1 200 OK
Content-Type: application/json
Request-Id: 1966e27f-dc05-11e7-8087-000000000000
X-Influxdb-Build: OSS
X-Influxdb-Version: 1.4.2
X-Request-Id: 1966e27f-dc05-11e7-8087-000000000000
Date: Fri, 08 Dec 2017 10:46:51 GMT
Transfer-Encoding: chunked

{
    "results": [
        {
            "statement_id": 0,
            "error": "database name required"
        }
    ]
}
</code>```

i am new to influx db , i tried fix i was not able to fix this.

Can someone correct my mistake please ? thanks in advance :)

答:
look careful influx doc

should specify "db="

```<code>--data-urlencode "db=dbvishnutest"
</code>```

Body:
i have pushed the data using the below api call in the database "dbvishnutest"

curl -XPOST http://<localhost>:8086/write?db=dbvishnutest --data-binary "weather,location=us-midwest temperature=82 1465839830100400200"

Now i am trying to pull back the data using the below api call .

curl -i -XPOST -G http://<localhost>:8086/query?pretty=true --data-urlencode "dbvishnutest" --data-urlencode "q=select * from weather where location=us-midwest"

i am getting the below error :

HTTP/1.1 200 OK
Content-Type: application/json
Request-Id: 1966e27f-dc05-11e7-8087-000000000000
X-Influxdb-Build: OSS
X-Influxdb-Version: 1.4.2
X-Request-Id: 1966e27f-dc05-11e7-8087-000000000000
Date: Fri, 08 Dec 2017 10:46:51 GMT
Transfer-Encoding: chunked

{
    "results": [
        {
            "statement_id": 0,
            "error": "database name required"
        }
    ]
}

i am new to influx db , i tried fix i was not able to fix this.

Can someone correct my mistake please ? thanks in advance :)

Body:
look careful influx doc

should specify "db="

--data-urlencode "db=dbvishnutest"

ContentLicense: CC BY-SA 4.0


问:
How are Python in-place operator functions different than the standard operator functions?
From the docs:

Many operations have an “in-place”
version. The following functions
provide a more primitive access to
in-place operators than the usual
syntax does; for example, the
statement x += y is equivalent to x =
operator.iadd(x, y). Another way to
put it is to say that z =
operator.iadd(x, y) is equivalent to
the compound statement z = x; z += y.

Questions:

Why isn't operator.iadd(x, y) equivalent to z = x; z += y?

How does operator.iadd(x, y) differ from operator.add(x, y)?

Related question, but I'm not interested in Python class methods; just regular operators on built-in Python types.

答:
First, you need to understand the difference between __add__ and __iadd__.

An object's __add__ method is regular addition: it takes two parameters, returns their sum, and doesn't modify either parameter.

An object's __iadd__ method also takes two parameters, but makes the change in-place, modifying the contents of the first parameter. Because this requires object mutation, immutable types (like the standard number types) shouldn't have an __iadd__ method.

a + b uses __add__.  a += b uses __iadd__ if it exists; if it doesn't, it emulates it via __add__, as in tmp = a + b; a = tmp.  operator.add and operator.iadd differ in the same way.

To the other question: operator.iadd(x, y) isn't equivalent to z = x; z += y, because if no __iadd__ exists __add__ will be used instead.  You need to assign the value to ensure that the result is stored in both cases: x = operator.iadd(x, y).

You can see this yourself easily enough:

```<code>import operator
a = 1
operator.iadd(a, 2)
# a is still 1, because ints don't have __iadd__; iadd returned 3

b = ['a']
operator.iadd(b, ['b'])
# lists do have __iadd__, so b is now ['a', 'b']
</code>```

Body:
First, you need to understand the difference between __add__ and __iadd__.

An object's __add__ method is regular addition: it takes two parameters, returns their sum, and doesn't modify either parameter.

An object's __iadd__ method also takes two parameters, but makes the change in-place, modifying the contents of the first parameter. Because this requires object mutation, immutable types (like the standard number types) shouldn't have an __iadd__ method.

a + b uses __add__.  a += b uses __iadd__ if it exists; if it doesn't, it emulates it via __add__, as in tmp = a + b; a = tmp.  operator.add and operator.iadd differ in the same way.

To the other question: operator.iadd(x, y) isn't equivalent to z = x; z += y, because if no __iadd__ exists __add__ will be used instead.  You need to assign the value to ensure that the result is stored in both cases: x = operator.iadd(x, y).

You can see this yourself easily enough:

import operator
a = 1
operator.iadd(a, 2)
# a is still 1, because ints don't have __iadd__; iadd returned 3

b = ['a']
operator.iadd(b, ['b'])
# lists do have __iadd__, so b is now ['a', 'b']


问:
How to inject objects which are not annotated Spring classes
Lets say I've got a JavaFx class and an ViewState class which needs to have referance of stage created in start method. How am I able to autowire such dependency? I know that Stage.class is not annotated as @Component so Spring is unable to detect duch @Bean.

```<code>@SpringBootApplication
@ComponentScan({"controller","service","dao","javafx.stage.Stage"})
@EntityScan( basePackages = {"Model"})
@Import({ SpringConfig.class})
public class JavaFXandSpringBootTestApplication extends Application{

    private ApplicationContext ctx;

    public static void main(String[] args) {
        launch();
    }

    @Override
    public void start(Stage stage) throws Exception {
    ViewState viewState = ctx.getBean(ViewState.class);
}
</code>```

ViewState class:

```<code>@Componenet
public class ViewState {

@Autowired
private ApplicationContext ctx;
private Stage stage;

@Autowired
public ViewState(Stage stage)
{
    this.stage = stage;
}
}
</code>```

Compiler massage:

```<code>Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'javafx.stage.Stage' available: expected at least 1
</code>```

答:
You probably don't want to do this at all: your ViewState class would seem to be a model class of some kind, so it should not have references to UI elements (such as Stages).

For completeness, though, here is an example that works, using ConfigurableApplicationContext.getBeanFactory().registerResolvableDependency(...). Note that, since you won't be able to create the View object until the stage is registered, you need to make the View bean @Lazy:

```<code>package example;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Component;

import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.StackPane;
import javafx.stage.Stage;

@Component
@Lazy
public class View {

    @Autowired
    public View(Stage stage) {
        Button close = new Button("Close");
        close.setOnAction(e -> stage.hide());
        StackPane root = new StackPane(close);
        Scene scene = new Scene(root, 400, 400);
        stage.setScene(scene);
        stage.show();
    }
}
</code>```

```<code>package example;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ConfigurableApplicationContext;

import javafx.application.Application;
import javafx.stage.Stage;

@SpringBootApplication
public class Main extends Application {

    private ConfigurableApplicationContext ctx ;

    @Override
    public void start(Stage primaryStage) {
        ctx = SpringApplication.run(Main.class);
        ctx.getBeanFactory().registerResolvableDependency(Stage.class, primaryStage);
        ctx.getBean(View.class);
    }

    @Override
    public void stop() {
        ctx.close();
    }

    public static void main(String[] args) {
        launch(args);
    }
}
</code>```

Body:
Lets say I've got a JavaFx class and an ViewState class which needs to have referance of stage created in start method. How am I able to autowire such dependency? I know that Stage.class is not annotated as @Component so Spring is unable to detect duch @Bean.

@SpringBootApplication
@ComponentScan({"controller","service","dao","javafx.stage.Stage"})
@EntityScan( basePackages = {"Model"})
@Import({ SpringConfig.class})
public class JavaFXandSpringBootTestApplication extends Application{

    private ApplicationContext ctx;

    public static void main(String[] args) {
        launch();
    }

    @Override
    public void start(Stage stage) throws Exception {
    ViewState viewState = ctx.getBean(ViewState.class);
}

ViewState class:

@Componenet
public class ViewState {

@Autowired
private ApplicationContext ctx;
private Stage stage;

@Autowired
public ViewState(Stage stage)
{
    this.stage = stage;
}
}

Compiler massage:

Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'javafx.stage.Stage' available: expected at least 1

Body:
You probably don't want to do this at all: your ViewState class would seem to be a model class of some kind, so it should not have references to UI elements (such as Stages).

For completeness, though, here is an example that works, using ConfigurableApplicationContext.getBeanFactory().registerResolvableDependency(...). Note that, since you won't be able to create the View object until the stage is registered, you need to make the View bean @Lazy:

package example;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Component;

import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.StackPane;
import javafx.stage.Stage;

@Component
@Lazy
public class View {

    @Autowired
    public View(Stage stage) {
        Button close = new Button("Close");
        close.setOnAction(e -> stage.hide());
        StackPane root = new StackPane(close);
        Scene scene = new Scene(root, 400, 400);
        stage.setScene(scene);
        stage.show();
    }
}

package example;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ConfigurableApplicationContext;

import javafx.application.Application;
import javafx.stage.Stage;

@SpringBootApplication
public class Main extends Application {

    private ConfigurableApplicationContext ctx ;

    @Override
    public void start(Stage primaryStage) {
        ctx = SpringApplication.run(Main.class);
        ctx.getBeanFactory().registerResolvableDependency(Stage.class, primaryStage);
        ctx.getBean(View.class);
    }

    @Override
    public void stop() {
        ctx.close();
    }

    public static void main(String[] args) {
        launch(args);
    }
}


问:
Create a matrix of scatterplots (pairs() equivalent) in ggplot2
Is it possible to plot a matrix of scatter plots with ggplot2, using ggplot's nice features like mapping additional factors to color, shape etc. and adding smoother?

I am thinking about something similar to the base function pairs.

答:
If one wants to obtain a ggplot object (not ggmatrix as in case of ggpairs()), the solution is to melt the data twice, then ggplot with facetting. facet_wrap would be better than facet_grid in limiting the plotted area, given the scales = 'free' parameter is supplied.

```<code>require(ggplot2)
require(dplyr)
require(tidyr)

gatherpairs <- function(data, ...,
                        xkey = '.xkey', xvalue = '.xvalue',
                        ykey = '.ykey', yvalue = '.yvalue',
                        na.rm = FALSE, convert = FALSE, factor_key = FALSE) {
  vars <- quos(...)
  xkey <- enquo(xkey)
  xvalue <- enquo(xvalue)
  ykey <- enquo(ykey)
  yvalue <- enquo(yvalue)

  data %>% {
    cbind(gather(., key = !!xkey, value = !!xvalue, !!!vars,
                 na.rm = na.rm, convert = convert, factor_key = factor_key),
          select(., !!!vars))
  } %>% gather(., key = !!ykey, value = !!yvalue, !!!vars,
               na.rm = na.rm, convert = convert, factor_key = factor_key)
}

iris %>%
  gatherpairs(Sepal.Length, Sepal.Width, Petal.Length, Petal.Width) %>% {
  ggplot(., aes(x = .xvalue, y = .yvalue, color = Species)) +
      geom_point() +
      geom_smooth(method = 'lm') +
      facet_wrap(.xkey ~ .ykey, ncol = length(unique(.$.ykey)), scales = 'free', labeller = label_both) +
      scale_color_brewer(type = 'qual')
}
</code>```

Body:
If one wants to obtain a ggplot object (not ggmatrix as in case of ggpairs()), the solution is to melt the data twice, then ggplot with facetting. facet_wrap would be better than facet_grid in limiting the plotted area, given the scales = 'free' parameter is supplied.

require(ggplot2)
require(dplyr)
require(tidyr)

gatherpairs <- function(data, ...,
                        xkey = '.xkey', xvalue = '.xvalue',
                        ykey = '.ykey', yvalue = '.yvalue',
                        na.rm = FALSE, convert = FALSE, factor_key = FALSE) {
  vars <- quos(...)
  xkey <- enquo(xkey)
  xvalue <- enquo(xvalue)
  ykey <- enquo(ykey)
  yvalue <- enquo(yvalue)

  data %>% {
    cbind(gather(., key = !!xkey, value = !!xvalue, !!!vars,
                 na.rm = na.rm, convert = convert, factor_key = factor_key),
          select(., !!!vars))
  } %>% gather(., key = !!ykey, value = !!yvalue, !!!vars,
               na.rm = na.rm, convert = convert, factor_key = factor_key)
}

iris %>%
  gatherpairs(Sepal.Length, Sepal.Width, Petal.Length, Petal.Width) %>% {
  ggplot(., aes(x = .xvalue, y = .yvalue, color = Species)) +
      geom_point() +
      geom_smooth(method = 'lm') +
      facet_wrap(.xkey ~ .ykey, ncol = length(unique(.$.ykey)), scales = 'free', labeller = label_both) +
      scale_color_brewer(type = 'qual')
}


问:
Is there a way to write node.js code synchronously?
I am trying to create a program that analyses some data. The data I am collection form the internet with node.js. I'm having a very hard time with the fact that the code is asynchronous, and I'm getting a lot of bugs because of it.

I know that it is not efficient at all, but is there a way to write the whole code shynchronously?

*I've used a lot of promises and patched a lot of bugs, but I still keep getting bugs because the code is asynchronous, and I'm tired of thinking of creative ideas to make my code work.

答:
This highly depends on the functions you use. Of course you can write an entire Node.js program purely synchronous - you just have to avoid using any function that is asynchronous.

But as Node.js is asynchronous by heart, I doubt that this will work for more complex things. Since you mentioned loading data from over the network: Just this is already an example of a task that can't be accomplished synchronously in Node.js, as any I/O in Node.js is always asynchronous (except for the file system methods that exist twice, but they are the exception to the rule).

I think the way better approach to solve your problems is to either use a different platform than Node.js, or to appropriately learn to deal with asynchronous code.

I guess that this is not the answer you wanted to hear, but unfortunately that's just the way it is IMHO.


问:
Storing a list within another list in a database without previous information in that list getting lost
I want to store a list within another list in a database (SQL) without previous data being lost.This is one example of values i have in my database (1, 'Haned', 15, 11, 'Han15', 'password', "['easymaths', 6]"). What i want to do is store another piece of information/data within the list [] without it getting rid of  "['easymaths', 6]" so it would look something like  "['easymaths', 6,'mediummaths', 6]" and so on.Thank you

答: Though not intended you could join the list by a specific seperator. In turn when you query the selected field you have to convert it into a list again.</p>


问:
Can't generate signed APK in AndroidStudio, 'java.io.IOException'
I have a problem with generating signed APK in Android Studio.

Error:Execution failed for task ':app:transformClassesWithMultidexlistForDebug'.
  java.io.IOException: Can't write [C:\Users\Ahmed\StudioProjects\android1\app\build\intermediates\multi-dex\debug\componentClasses.jar] (Can't read [C:\Users\Ahmed.gradle\caches\transforms-1\files-1.1\support-compat-25.2.0.aar\8a6c38a056e2992b7f752213fb56ad15\jars\classes.jar(;;;;;;.class)] (Duplicate zip entry [classes.jar:android/support/v4/view/ViewCompat.class]))

```<code>apply plugin: 'com.android.application'

android {
    compileSdkVersion 25
    buildToolsVersion '26.0.2'

defaultConfig {
    applicationId "com.ahmedkarray.switchsides.colorsdash"
    minSdkVersion 16
    targetSdkVersion 25
    multiDexEnabled true

    ndk {
        moduleName "player_shared"
    }
}

buildTypes {
    release {
        minifyEnabled false
        shrinkResources false
        proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.txt'
    }

}
sourceSets.main {
    jni.srcDirs = []// <-- disable automatic ndk-build call
}
}
android{

configurations {
    all*.exclude group: 'com.android.support', module: 'support-v4'
    all*.exclude group: 'com.android.support', module: 'support-annotations'
}
}

dependencies {
compile 'com.android.support:multidex:1.0.1'
compile ('com.google.android.gms:play-services:+'){exclude module: 'support-v4'}
compile files('libs/dagger-1.2.2.jar')
compile files('libs/javax.inject-1.jar')
compile files('libs/nineoldandroids-2.4.0.jar')
compile files('libs/support-v4-19.0.1.jar')
compile ('com.android.support:multidex:1.0.1')
compile 'com.android.support:support-annotations:27.0.2'
}
</code>```

答:
Change your dependencies this way

```<code>dependencies {
    compile 'com.android.support:multidex:1.0.1'
    compile ('com.google.android.gms:play-services:+'){
       exclude module: 'support-v4'
    }
    compile files('libs/dagger-1.2.2.jar')
    compile files('libs/javax.inject-1.jar')
    compile files('libs/nineoldandroids-2.4.0.jar')
    compile 'com.android.support:support-v4:27.0.2'
    compile 'com.android.support:mediarouter-v7:27.0.2'
    compile 'com.android.support:support-compat:27.0.2'
    compile 'com.android.support:support-core-ui:27.0.2'
    compile 'com.android.support:appcompat-v7:27.0.2'
    compile 'com.android.support:support-annotations:27.0.2'
}
</code>```

Change also compileSdkVersion

```<code>android {
   compileSdkVersion 27
</code>```

And remove support-v4-19.0.1.jar from your libs folder

Body:
I have a problem with generating signed APK in Android Studio.

Error:Execution failed for task ':app:transformClassesWithMultidexlistForDebug'.
  java.io.IOException: Can't write [C:\Users\Ahmed\StudioProjects\android1\app\build\intermediates\multi-dex\debug\componentClasses.jar] (Can't read [C:\Users\Ahmed.gradle\caches\transforms-1\files-1.1\support-compat-25.2.0.aar\8a6c38a056e2992b7f752213fb56ad15\jars\classes.jar(;;;;;;.class)] (Duplicate zip entry [classes.jar:android/support/v4/view/ViewCompat.class]))

apply plugin: 'com.android.application'

android {
    compileSdkVersion 25
    buildToolsVersion '26.0.2'

defaultConfig {
    applicationId "com.ahmedkarray.switchsides.colorsdash"
    minSdkVersion 16
    targetSdkVersion 25
    multiDexEnabled true

    ndk {
        moduleName "player_shared"
    }
}

buildTypes {
    release {
        minifyEnabled false
        shrinkResources false
        proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.txt'
    }

}
sourceSets.main {
    jni.srcDirs = []// <-- disable automatic ndk-build call
}
}
android{

configurations {
    all*.exclude group: 'com.android.support', module: 'support-v4'
    all*.exclude group: 'com.android.support', module: 'support-annotations'
}
}

dependencies {
compile 'com.android.support:multidex:1.0.1'
compile ('com.google.android.gms:play-services:+'){exclude module: 'support-v4'}
compile files('libs/dagger-1.2.2.jar')
compile files('libs/javax.inject-1.jar')
compile files('libs/nineoldandroids-2.4.0.jar')
compile files('libs/support-v4-19.0.1.jar')
compile ('com.android.support:multidex:1.0.1')
compile 'com.android.support:support-annotations:27.0.2'
}

Body:
Change your dependencies this way

dependencies {
    compile 'com.android.support:multidex:1.0.1'
    compile ('com.google.android.gms:play-services:+'){
       exclude module: 'support-v4'
    }
    compile files('libs/dagger-1.2.2.jar')
    compile files('libs/javax.inject-1.jar')
    compile files('libs/nineoldandroids-2.4.0.jar')
    compile 'com.android.support:support-v4:27.0.2'
    compile 'com.android.support:mediarouter-v7:27.0.2'
    compile 'com.android.support:support-compat:27.0.2'
    compile 'com.android.support:support-core-ui:27.0.2'
    compile 'com.android.support:appcompat-v7:27.0.2'
    compile 'com.android.support:support-annotations:27.0.2'
}

Change also compileSdkVersion

android {
   compileSdkVersion 27

And remove support-v4-19.0.1.jar from your libs folder


问:
How to track my software available as link on other websites
I need to track my software available as link on other websites.
I want information of those websites who make my software as downloadable link available on their website without my permission.

Please help me out in finding out some good related articles or solutions

答:
Enable the web server logs, and track the Referer HTTP header for all requests to your software package.

Of course, that would only help track sites that directly link to your site. There is no easy way to track websites that mirror your package and allow users to download it from the mirror.

ContentLicense: CC BY-SA 2.5


问:
How do I upload images in php after I have already saved data from the form1 and images are uploaded in form2
I have a html page, with a form and image upload,
I want to update the database with the images once uploaded, the two form work well individually, but I need to link the form-data to the uploaded images in the database.

kindly help with logic, I am considering using sessions

答:
You could save your images in the session if you don't want to save them in the database (which, by the way, might not be a good idea), this avoids putting stuff in the database that is not yet finally processed (as I understand: this happens when the other form is submitted?)

You could put them in a table for "temporary images" which are not yet processed finally and just keep track of the IDs through the session


问:
How to use tf.nn.crelu in tensorflow?
I am trying different activation functions in my simple neural network.

It does not matter using tf.nn.relu, tf.nn.sigmoid,... the network does what it should do.

But if I am using tf.nn.crelu, I have a dimension error.

It returns something like [max, min] and the width dimension is twice bigger.
What do I have to do? Fitting the following weights and biases to the output of crelu?

答:
You're right, if you're building the network manually, you need to adjust the dimensions of the following layer to match tf.nn.crelu output. In this sense, tf.nn.crelu is not interchangeable with tf.nn.relu, tf.nn.elu, etc.

The situation is simpler if you use a high-level API, e.g. tensorflow slim. In this case, the layer functions are taking care of matching dimensions, so you can replace tf.nn.relu easily with tf.nn.crelu in code. However, keep in mind that the network is silently becoming twice as big.

Here's an example:

with slim.arg_scope([slim.conv2d, slim.fully_connected],
                    activation_fn=tf.nn.crelu,
                    normalizer_fn=slim.batch_norm,
                    normalizer_params={'is_training': is_training, 'decay': 0.95}):
    conv1 = slim.conv2d(x_image, 16, [5, 5], scope='conv1')
    pool1 = slim.max_pool2d(conv1, [2, 2], scope='pool1')
    conv2 = slim.conv2d(pool1, 32, [5, 5], scope='conv2')
    pool2 = slim.max_pool2d(conv2, [2, 2], scope='pool2')
    flatten = slim.flatten(pool2)
    fc = slim.fully_connected(flatten, 1024, scope='fc1')
    drop = slim.dropout(fc, keep_prob=keep_prob)
    logits = slim.fully_connected(drop, 10, activation_fn=None, scope='logits')
```

slim.arg_scope simply applies all provided arguments to the underlying layers, in particular activation_fn. Also note activation_fn=None in the last layer to fix the output dimension. Complete code can be found here.

Title: How to use tf.nn.crelu in tensorflow?

Body:
You're right, if you're building the network manually, you need to adjust the dimensions of the following layer to match tf.nn.crelu output. In this sense, tf.nn.crelu is not interchangeable with tf.nn.relu, tf.nn.elu, etc.

The situation is simpler if you use a high-level API, e.g. tensorflow slim. In this case, the layer functions are taking care of matching dimensions, so you can replace tf.nn.relu easily with tf.nn.crelu in code. However, keep in mind that the network is silently becoming twice as big.

Here's an example:

with slim.arg_scope([slim.conv2d, slim.fully_connected],
                    activation_fn=tf.nn.crelu,
                    normalizer_fn=slim.batch_norm,
                    normalizer_params={'is_training': is_training, 'decay': 0.95}):
    conv1 = slim.conv2d(x_image, 16, [5, 5], scope='conv1')
    pool1 = slim.max_pool2d(conv1, [2, 2], scope='pool1')
    conv2 = slim.conv2d(pool1, 32, [5, 5], scope='conv2')
    pool2 = slim.max_pool2d(conv2, [2, 2], scope='pool2')
    flatten = slim.flatten(pool2)
    fc = slim.fully_connected(flatten, 1024, scope='fc1')
    drop = slim.dropout(fc, keep_prob=keep_prob)
    logits = slim.fully_connected(drop, 10, activation_fn=None, scope='logits')

slim.arg_scope simply applies all provided arguments to the underlying layers, in particular activation_fn. Also note activation_fn=None in the last layer to fix the output dimension. Complete code can be found here.


问:
MDA-8086 8*8 Dot matrix display code segment explaination
I have a code that display 'A' in the dot matrix display of MDA-8086. Here is it:

```<code>ORG 1000H
MOV AL, 10000000B       ;Activate Signal
OUT 1EH, AL             ;Writing Activate signal to  Control Register
MOV AL, 11111111B       ;Off Signal
OUT 18H, AL             ;Writing off signal to Port A
L1: MOV SI, OFFSET FONT ;Assigning source address to Memory address/                            ;offset of FONT Variable
    MOV AH, 00000001B
L2: MOV AL, BYTE PTR CS:[SI]
    OUT 1AH, AL
    MOV AL, AH
    OUT 1CH, AL
    CALL TIMER
    INC SI
    CLC
    ROL AH, 1
    JNC L2
    JMP L1
    INT 3
TIMER: MOV CX, 300
TIMER1: NOP
        NOP
        NOP
        NOP
        LOOP TIMER1
        RET
FONT: DB 11111111B
      DB 11001001B
      DB 10110100B
      DB 10110110B
      DB 10110110B
      DB 10110110B
      DB 10000000B
      DB 11111111B
</code>```

Now I don't get these lines; MOV SI, OFFSET FONT and MOV AL, BYTE PTR CS:[SI]. can anyone tell me what these lines do?

Edit:

I also want to know how DB is working in FONT and how each DB is evaluated.

答:
Now I don't get these lines

16- and 32-bit code of x86 CPUs always use two numbers to specify the address of something stored in memory:

The segment and the offset.

The segment describes some region in memory.

The "real" address of some item in memory can be calculated by:

```<code>(address of the first byte of the segment) + offset
</code>```

The CS register is normally read-only. It contains the segment which contains the instruction which is currently executed.

The MOV SI, OFFSET FONT instruction will now write the offset of the data following the FONT: label to the SI register.

The MOV AL, BYTE PTR CS:[SI] instruction will read one byte from the memory into the register AL. The byte is read from the following address:

```<code>(address of the first byte of the CS segment) + (value of register SI)
</code>```

Because the FONT: label is in the same segment as the instruction itself (CS) and SI contains the offset of FONT: the address calculated this way is the address of the first byte of FONT:.

In other words: The instruction loads the first byte of FONT: into the register AL.

(When the instruction is called the second time the second byte of FONT: will be loaded because SI has been incremented.)

I also want to know how DB is working ...

DB is not an instruction.

DB tells the assembler to write a byte with a certain value into the memory instead of an instruction.

So the following (non-sense) code:

```<code>mov ax, 1
db 10
mov ax, 2
</code>```

... means that there shall be the byte with the value 10 between the two mov instructions.

how DB is working in FONT

The 8 bytes (here not specified as decimal but as binary numbers) are stored at the memory location named FONT:.

Body:
I have a code that display 'A' in the dot matrix display of MDA-8086. Here is it:

ORG 1000H
MOV AL, 10000000B       ;Activate Signal
OUT 1EH, AL             ;Writing Activate signal to  Control Register
MOV AL, 11111111B       ;Off Signal
OUT 18H, AL             ;Writing off signal to Port A
L1: MOV SI, OFFSET FONT ;Assigning source address to Memory address/                            ;offset of FONT Variable
    MOV AH, 00000001B
L2: MOV AL, BYTE PTR CS:[SI]
    OUT 1AH, AL
    MOV AL, AH
    OUT 1CH, AL
    CALL TIMER
    INC SI
    CLC
    ROL AH, 1
    JNC L2
    JMP L1
    INT 3
TIMER: MOV CX, 300
TIMER1: NOP
        NOP
        NOP
        NOP
        LOOP TIMER1
        RET
FONT: DB 11111111B
      DB 11001001B
      DB 10110100B
      DB 10110110B
      DB 10110110B
      DB 10110110B
      DB 10000000B
      DB 11111111B

Now I don't get these lines; MOV SI, OFFSET FONT and MOV AL, BYTE PTR CS:[SI]. can anyone tell me what these lines do?

Edit:

I also want to know how DB is working in FONT and how each DB is evaluated.

Body:
Now I don't get these lines

16- and 32-bit code of x86 CPUs always use two numbers to specify the address of something stored in memory:

The segment and the offset.

The segment describes some region in memory.

The "real" address of some item in memory can be calculated by:

(address of the first byte of the segment) + offset

The CS register is normally read-only. It contains the segment which contains the instruction which is currently executed.

The MOV SI, OFFSET FONT instruction will now write the offset of the data following the FONT: label to the SI register.

The MOV AL, BYTE PTR CS:[SI] instruction will read one byte from the memory into the register AL. The byte is read from the following address:

(address of the first byte of the CS segment) + (value of register SI)

Because the FONT: label is in the same segment as the instruction itself (CS) and SI contains the offset of FONT: the address calculated this way is the address of the first byte of FONT:.

In other words: The instruction loads the first byte of FONT: into the register AL.

(When the instruction is called the second time the second byte of FONT: will be loaded because SI has been incremented.)

I also want to know how DB is working ...

DB is not an instruction.

DB tells the assembler to write a byte with a certain value into the memory instead of an instruction.

So the following (non-sense) code:

mov ax, 1
db 10
mov ax, 2

... means that there shall be the byte with the value 10 between the two mov instructions.

how DB is working in FONT

The 8 bytes (here not specified as decimal but as binary numbers) are stored at the memory location named FONT:.


问:
Don't understand why my multiplication isn't working?
I'm trying to make a temperature conversion function for a class assignment, and my function receives all of the arguments correctly but for some reason after it hits the equation to convert the number it just makes the number 0.

Here is the code so you know what I'm talking about:

```<code>void convertToCelsius(int farenheitTemperature, int temperatureType){

if (temperatureType == 1)
{

farenheitTemperature = ((5/9) * (farenheitTemperature - 32));
printf("Your temperature in Celsius is %i\n", farenheitTemperature);

}

else
{
    printf("Your temperature is already in celsius!\n");
}
}
</code>```

the main function puts the arguments in correctly, so I don't think that's the problem.

Thank you very much for any help you can give!

答:
Don't know why are you writing it that way(it's better to use a different variable name on the left-hand side for temperature in Celsius. "Code readability matters")  but you are doing wrong when you write,

```<code>farenheitTemperature = ((5/9) * (farenheitTemperature - 32));
</code>```

In C,(5/9) evaluates to 0, which makes the whole expression 0. You should use double/float for fahrenheitTemperature and change (5/9) to (5/9.0) or (5.0/9).

Body:
I'm trying to make a temperature conversion function for a class assignment, and my function receives all of the arguments correctly but for some reason after it hits the equation to convert the number it just makes the number 0.

Here is the code so you know what I'm talking about:

void convertToCelsius(int farenheitTemperature, int temperatureType){

if (temperatureType == 1)
{

farenheitTemperature = ((5/9) * (farenheitTemperature - 32));
printf("Your temperature in Celsius is %i\n", farenheitTemperature);

}

else
{
    printf("Your temperature is already in celsius!\n");
}
}

the main function puts the arguments in correctly, so I don't think that's the problem.

Thank you very much for any help you can give!

Body:
Don't know why are you writing it that way(it's better to use a different variable name on the left-hand side for temperature in Celsius. "Code readability matters")  but you are doing wrong when you write,

farenheitTemperature = ((5/9) * (farenheitTemperature - 32));

In C,(5/9) evaluates to 0, which makes the whole expression 0. You should use double/float for fahrenheitTemperature and change (5/9) to (5/9.0) or (5.0/9).


问:
implicit inheritance - how to remove boilerplate and code duplication
In the code example below there is quite a lot of code duplication. Is there any way to remove this ? I have been thinking about this for a while but still have no idea.

```<code>abstract class RouteBase[E <: Entity](
  )(
    implicit
    i:  ClassTag[E],
    en: Encoder[E],
    de: Decoder[E],
    sa: InterfaceToStateAccessor,
    ec: ExecutionContext)
{
   common concrete methods ...
   abstract methods ...
}

abstract class GetRouteBase [E <: Entity] (
    implicit
    i:  ClassTag[E],
    en: Encoder[E],
    de: Decoder[E],
    sa: InterfaceToStateAccessor,
    ec: ExecutionContext) extends RouteBase[E]
{
  implemented methods used by Get operations ...
}

class GetRoute[E <: Entity](
  )(
    implicit
    i:  ClassTag[E],
    en: Encoder[E],
    de: Decoder[E],
    sa: InterfaceToStateAccessor,
    ec: ExecutionContext) extends GetRouteBase[E]
   {
     actual method implementations of all abstract methods ...
   }
}
</code>```

EDIT:

Interestingly this code compiles just fine:

```<code>class A {
  implicit val s:String = "bla"
}
class B  extends  A
{
  def printImplicit(implicit s:String)={
    println(s)
  }
  printImplicit
}
</code>```

答:
This is the best I could come up with. I am not sure if code duplication can be reduced even more in this example.</p>

```<code>trait T {
  implicit val s:String
  implicit val i:Int
}

trait A { T =>
    def printA(implicit s:String) = {println("A"+s)}
}

trait B extends  A
{ T=>
  def printB(implicit i:Int) = {println("B"+i)}
}

trait C extends  B
{ T=>
  def printImplicit(implicit s:String,i:Int)={
    println(s)
    printA
    printB
  }
}

class D(implicit s2:String,i:Int) extends C {

    printImplicit
}
</code>```

Body:
In the code example below there is quite a lot of code duplication. Is there any way to remove this ? I have been thinking about this for a while but still have no idea.

abstract class RouteBase[E <: Entity](
  )(
    implicit
    i:  ClassTag[E],
    en: Encoder[E],
    de: Decoder[E],
    sa: InterfaceToStateAccessor,
    ec: ExecutionContext)
{
   common concrete methods ...
   abstract methods ...
}

abstract class GetRouteBase [E <: Entity] (
    implicit
    i:  ClassTag[E],
    en: Encoder[E],
    de: Decoder[E],
    sa: InterfaceToStateAccessor,
    ec: ExecutionContext) extends RouteBase[E]
{
  implemented methods used by Get operations ...
}

class GetRoute[E <: Entity](
  )(
    implicit
    i:  ClassTag[E],
    en: Encoder[E],
    de: Decoder[E],
    sa: InterfaceToStateAccessor,
    ec: ExecutionContext) extends GetRouteBase[E]
   {
     actual method implementations of all abstract methods ...
   }
}

EDIT:

Interestingly this code compiles just fine:

class A {
  implicit val s:String = "bla"
}
class B  extends  A
{
  def printImplicit(implicit s:String)={
    println(s)
  }
  printImplicit
}

Body:
This is the best I could come up with. I am not sure if code duplication can be reduced even more in this example.

trait T {
  implicit val s:String
  implicit val i:Int
}

trait A { T =>
    def printA(implicit s:String) = {println("A"+s)}
}

trait B extends  A
{ T=>
  def printB(implicit i:Int) = {println("B"+i)}
}

trait C extends  B
{ T=>
  def printImplicit(implicit s:String,i:Int)={
    println(s)
    printA
    printB
  }
}

class D(implicit s2:String,i:Int) extends C {

    printImplicit
}


问:
Stuck in a loop when trying to log in
I am trying to implement a SAML2 SSO setup with Azure AD as the IDP and SP using the hslavich/OneloginSamlBundle on Symfony3.

When I access the login path on my app, the browser is stuck in a circular loop between Azure AD and my APP which I've not been able to decipher.

Here are my configurations:

config.yml

```<code>hslavich_onelogin_saml:
# Basic settings
idp:
    entityId: 'https://login.microsoftonline.com/azure_app_id/saml2'
    singleSignOnService:
        url: 'https://login.microsoftonline.com/azure_app_id/saml2'
        binding: 'urn:oasis:names:tc:SAML:2.0:bindings:HTTP-Redirect'
    singleLogoutService:
        url: 'https://login.microsoftonline.com/azure_app_id/saml2'
        binding: 'urn:oasis:names:tc:SAML:2.0:bindings:HTTP-Redirect'
    x509cert: '%kernel.project_dir%/src/AppBundle/Resources/config/AzureCert.cer'
sp:
    entityId: 'https://myapp.com/saml/meta'
    assertionConsumerService:
        url: 'https://myapp.com/saml/acs'
        binding: 'urn:oasis:names:tc:SAML:2.0:bindings:HTTP-POST'
    singleLogoutService:
        url: 'https://myapp.com/saml/logout'
        binding: 'urn:oasis:names:tc:SAML:2.0:bindings:HTTP-Redirect'
</code>```

Azure AD configuration

```<code>Identifier(EntityId): https://myapp.com/saml/meta
Reply URL (ACS): https://myapp.com/saml/acs
</code>```

Would anyone be able to see where I am going wrong?

答: You can use this sign out URL and try - https://login.microsoftonline.com/common/wsfederation?wa=wsignout1.0 </p>

Title: Stuck in a loop when trying to log in

Body:
I am trying to implement a SAML2 SSO setup with Azure AD as the IDP and SP using the hslavich/OneloginSamlBundle on Symfony3.

When I access the login path on my app, the browser is stuck in a circular loop between Azure AD and my APP which I've not been able to decipher.

Here are my configurations:

config.yml

hslavich_onelogin_saml:
# Basic settings
idp:
    entityId: 'https://login.microsoftonline.com/azure_app_id/saml2'
    singleSignOnService:
        url: 'https://login.microsoftonline.com/azure_app_id/saml2'
        binding: 'urn:oasis:names:tc:SAML:2.0:bindings:HTTP-Redirect'
    singleLogoutService:
        url: 'https://login.microsoftonline.com/azure_app_id/saml2'
        binding: 'urn:oasis:names:tc:SAML:2.0:bindings:HTTP-Redirect'
    x509cert: '%kernel.project_dir%/src/AppBundle/Resources/config/AzureCert.cer'
sp:
    entityId: 'https://myapp.com/saml/meta'
    assertionConsumerService:
        url: 'https://myapp.com/saml/acs'
        binding: 'urn:oasis:names:tc:SAML:2.0:bindings:HTTP-POST'
    singleLogoutService:
        url: 'https://myapp.com/saml/logout'
        binding: 'urn:oasis:names:tc:SAML:2.0:bindings:HTTP-Redirect'

Azure AD configuration

Identifier(EntityId): https://myapp.com/saml/meta
Reply URL (ACS): https://myapp.com/saml/acs

Would anyone be able to see where I am going wrong?


问:
add combobox to mainwindow
I created a Main window with 2 button by pyqt5 and now i want to add a combo box to it. But if i keep App(QMainWindow), the combo box wont show. Only if i write App(QWidgets) it will show. Are there any way to add a combo box to main window ? here is my code:</p>

```<code>class App(QMainWindow):

    def __init__(self):
        super().__init__()
        self.title = 'Phan mem quan ly tai lieu- Tuan tien mom'
        self.left = 200
        self.top = 200
        self.width = 320
        self.height = 200
        self.initUI()

    def initUI(self):
        self.setWindowTitle(self.title)
        self.setGeometry(self.left, self.top, self.width, self.height)

        button = QPushButton('chaychuongtrinh', self)
        button.setToolTip('bam vao nut nay de chay chuong trinh')
        button.move(100, 70)
        button.clicked.connect(self.on_click)

        button1 = QPushButton('kiemtra', self)
        button1.setToolTip('kiem tra thong tin')
        button1.move(200, 70)
        button1.clicked.connect(self.on_click)

        layout = QHBoxLayout()
        self.cb = QComboBox()
        self.cb.addItem("C")
        self.cb.addItem("C++")
        self.cb.addItems(["Java", "C#", "Python"])
        self.cb.currentIndexChanged.connect(self.selectionchange)
        layout.addWidget(self.cb)
        self.setLayout(layout)
        self.setWindowTitle("combo box demo")
        self.show()
    def selectionchange(self,i):
        print ("Items in the list are :")
        print(self.cb.currentText())
</code>```

答:
QMainWindow is a special widget, it already has a layout, so we should not add another layout as shown in the image:

In this case you must create a new widget and place it in the central widget, in this new widget we must place the widget like the QPushButton or the QComboBox.

In your case the QPushButton are visible because if a widget passed a parent, it will be located in the position (0, 0) of the parent, and then you have moved it to a specific position with move(). In contrast, the combobox has no parent so it is not visible.

Also if you are going to use a layout, you should not use the move () function since the layout will expand throughout the widget. In the following example without using the layout:

```<code>def initUI(self):
    self.setWindowTitle(self.title)
    self.setGeometry(self.left, self.top, self.width, self.height)
    self.widget = QWidget(self)
    self.setCentralWidget(self.widget)
    button = QPushButton('chaychuongtrinh', self.widget)
    button.move(100, 70)
    button.setToolTip('bam vao nut nay de chay chuong trinh')
    button.clicked.connect(self.on_click)
    button1 = QPushButton('kiemtra', self.widget)
    button1.setToolTip('kiem tra thong tin')
    button1.clicked.connect(self.on_click)
    button1.move(200, 70)
    self.cb = QComboBox(self.widget)
    self.cb.addItem("C")
    self.cb.addItem("C++")
    self.cb.addItems(["Java", "C#", "Python"])
    self.cb.currentIndexChanged.connect(self.selectionchange)
    self.cb.move(300, 70)
    self.setWindowTitle("combo box demo")
</code>```

with layouts:

```<code>def initUI(self):
    self.setWindowTitle(self.title)
    self.setGeometry(self.left, self.top, self.width, self.height)
    self.widget = QWidget(self)
    self.setCentralWidget(self.widget)
    layout = QHBoxLayout(self.widget)
    layout.addItem(QSpacerItem(139, 20, QSizePolicy.Expanding, QSizePolicy.Minimum))
    vlay = QVBoxLayout()
    vlay.addItem(QSpacerItem(20, 40, QSizePolicy.Minimum, QSizePolicy.Expanding))
    layout.addLayout(vlay)
    layout.addItem(QSpacerItem(139, 20, QSizePolicy.Expanding, QSizePolicy.Minimum))
    button = QPushButton('chaychuongtrinh', self)
    button.setToolTip('bam vao nut nay de chay chuong trinh')
    button.clicked.connect(self.on_click)
    button1 = QPushButton('kiemtra', self)
    button1.setToolTip('kiem tra thong tin')
    button1.clicked.connect(self.on_click)
    self.cb = QComboBox(self)
    self.cb.addItem("C")
    self.cb.addItem("C++")
    self.cb.addItems(["Java", "C#", "Python"])
    self.cb.currentIndexChanged.connect(self.selectionchange)
    vlay.addWidget(button)
    vlay.addWidget(button1)
    vlay.addWidget(self.cb)
    vlay.addItem(QSpacerItem(20, 40, QSizePolicy.Minimum, QSizePolicy.Expanding))
    self.setWindowTitle("combo box demo")
    self.show()
</code>```

Title: add combobox to mainwindow

Body:
I created a Main window with 2 button by pyqt5 and now i want to add a combo box to it. But if i keep App(QMainWindow), the combo box wont show. Only if i write App(QWidgets) it will show. Are there any way to add a combo box to main window ? here is my code:

class App(QMainWindow):

    def __init__(self):
        super().__init__()
        self.title = 'Phan mem quan ly tai lieu- Tuan tien mom'
        self.left = 200
        self.top = 200
        self.width = 320
        self.height = 200
        self.initUI()

    def initUI(self):
        self.setWindowTitle(self.title)
        self.setGeometry(self.left, self.top, self.width, self.height)

        button = QPushButton('chaychuongtrinh', self)
        button.setToolTip('bam vao nut nay de chay chuong trinh')
        button.move(100, 70)
        button.clicked.connect(self.on_click)

        button1 = QPushButton('kiemtra', self)
        button1.setToolTip('kiem tra thong tin')
        button1.move(200, 70)
        button1.clicked.connect(self.on_click)

        layout = QHBoxLayout()
        self.cb = QComboBox()
        self.cb.addItem("C")
        self.cb.addItem("C++")
        self.cb.addItems(["Java", "C#", "Python"])
        self.cb.currentIndexChanged.connect(self.selectionchange)
        layout.addWidget(self.cb)
        self.setLayout(layout)
        self.setWindowTitle("combo box demo")
        self.show()
    def selectionchange(self,i):
        print ("Items in the list are :")
        print(self.cb.currentText())

Body:
QMainWindow is a special widget, it already has a layout, so we should not add another layout as shown in the image:

In this case you must create a new widget and place it in the central widget, in this new widget we must place the widget like the QPushButton or the QComboBox.

In your case the QPushButton are visible because if a widget passed a parent, it will be located in the position (0, 0) of the parent, and then you have moved it to a specific position with move(). In contrast, the combobox has no parent so it is not visible.

Also if you are going to use a layout, you should not use the move () function since the layout will expand throughout the widget. In the following example without using the layout:

def initUI(self):
    self.setWindowTitle(self.title)
    self.setGeometry(self.left, self.top, self.width, self.height)
    self.widget = QWidget(self)
    self.setCentralWidget(self.widget)
    button = QPushButton('chaychuongtrinh', self.widget)
    button.move(100, 70)
    button.setToolTip('bam vao nut nay de chay chuong trinh')
    button.clicked.connect(self.on_click)
    button1 = QPushButton('kiemtra', self.widget)
    button1.setToolTip('kiem tra thong tin')
    button1.clicked.connect(self.on_click)
    button1.move(200, 70)
    self.cb = QComboBox(self.widget)
    self.cb.addItem("C")
    self.cb.addItem("C++")
    self.cb.addItems(["Java", "C#", "Python"])
    self.cb.currentIndexChanged.connect(self.selectionchange)
    self.cb.move(300, 70)
    self.setWindowTitle("combo box demo")

with layouts:

def initUI(self):
    self.setWindowTitle(self.title)
    self.setGeometry(self.left, self.top, self.width, self.height)
    self.widget = QWidget(self)
    self.setCentralWidget(self.widget)
    layout = QHBoxLayout(self.widget)
    layout.addItem(QSpacerItem(139, 20, QSizePolicy.Expanding, QSizePolicy.Minimum))
    vlay = QVBoxLayout()
    vlay.addItem(QSpacerItem(20, 40, QSizePolicy.Minimum, QSizePolicy.Expanding))
    layout.addLayout(vlay)
    layout.addItem(QSpacerItem(139, 20, QSizePolicy.Expanding, QSizePolicy.Minimum))
    button = QPushButton('chaychuongtrinh', self)
    button.setToolTip('bam vao nut nay de chay chuong trinh')
    button.clicked.connect(self.on_click)
    button1 = QPushButton('kiemtra', self)
    button1.setToolTip('kiem tra thong tin')
    button1.clicked.connect(self.on_click)
    self.cb = QComboBox(self)
    self.cb.addItem("C")
    self.cb.addItem("C++")
    self.cb.addItems(["Java", "C#", "Python"])
    self.cb.currentIndexChanged.connect(self.selectionchange)
    vlay.addWidget(button)
    vlay.addWidget(button1)
    vlay.addWidget(self.cb)
    vlay.addItem(QSpacerItem(20, 40, QSizePolicy.Minimum, QSizePolicy.Expanding))
    self.setWindowTitle("combo box demo")
    self.show()


问:
How to load custom plugins in CakePHP?
I'm writing a poll plugin for a website based on CakePHP. The plugin works good if I access it from its own URL (eg. myapp.com/plugin/controller) but I need to call it from different pages. I would like to include it as a widget in every page.

I'm looking for a method like $myplugin->renderPoll($pollId); but I really didn't find any information about how to instantiate the Polls class. I tried with App::import and ClassRegistry::init with no luck.

Any suggestion ?
Thank you

答:
Looks like you are trying to create some sort of Helper to create poll cross views? I would suggest creating a Helper for that particular class. Simply create a helper in plugins/plugin_name/views/helpers/foo.php, and in each controller (or in app_controller.php) that you need it, include the helpers as $helpers = array("PluginName.Foo"); and inside your view, you should be able to use the methods defined in foo.php by calling $foo->renderPoll($pollId).

```<code>//app/plugins/plugin_name/views/helpers/foo.php
class FooHelper extends AppHelper {
    var $name = "Foo";

    function renderPoll($id=0) {
        //...
    }
}
</code>```

Title: How to load custom plugins in CakePHP?

Body:
Looks like you are trying to create some sort of Helper to create poll cross views? I would suggest creating a Helper for that particular class. Simply create a helper in plugins/plugin_name/views/helpers/foo.php, and in each controller (or in app_controller.php) that you need it, include the helpers as $helpers = array("PluginName.Foo"); and inside your view, you should be able to use the methods defined in foo.php by calling $foo->renderPoll($pollId).

//app/plugins/plugin_name/views/helpers/foo.php
class FooHelper extends AppHelper {
    var $name = "Foo";

    function renderPoll($id=0) {
        //...
    }
}


问:
Change image src when accordion is opened ,Angular
In my html I have this:

```<code> <div class="col-md-3 col-sm-2 col-2 collapsedData" >
          <a class="collapsed" data-toggle="collapse" data-parent="#accordion" href="#collapseTwo" aria-expanded="false"
            aria-controls="collapseTwo">
            <img src="downArrow.svg">
          </a>
        </div>
      </div>
      <div id="collapseTwo" class="collapse" role="tabpanel" aria-labelledby="headingTwo">
      <p> Some text that displays</p>
      </div>
</code>```

When the downIcon is clicked, the class collapsed gets removed, and aria-expanded becomes true.

Is there a way to use these two changed values, so that on the Img tag I have something like ;

```<code> *ngIf aria-expanded=true, then display this image.
 else display another image.
</code>```

I need to shift between arrow up and arrow down.
Can I bind these attributes to an ngIf ?

答:
You can create a property in your component class that will be true when the component is collapsed and false when it is open.

```<code>export class MyComponent {
  collapsed: boolean = false;
  // ...etc
}
</code>```

Then, bind to the click event in your template, so you change collapsed from false to true and vice versa. And use a ternary operator to change the image path inside the src property of img

```<code> <a class="collapsed"
   data-toggle="collapse"
   data-parent="#accordion"
   href="#collapseTwo"
   aria-expanded="false"
   aria-controls="collapseTwo"
   (click)="collapsed = !collapsed">
   <img [src]="collapsed ? 'downArrow.svg' : 'upArrow.svg'">
 </a>
</code>```

Body:
In my html I have this:

 Some text that displays

When the downIcon is clicked, the class collapsed gets removed, and aria-expanded becomes true.

Is there a way to use these two changed values, so that on the Img tag I have something like ;

 *ngIf aria-expanded=true, then display this image.
 else display another image.

I need to shift between arrow up and arrow down.
Can I bind these attributes to an ngIf ?

Body:
You can create a property in your component class that will be true when the component is collapsed and false when it is open.

export class MyComponent {
  collapsed: boolean = false;
  // ...etc
}

Then, bind to the click event in your template, so you change collapsed from false to true and vice versa. And use a ternary operator to change the image path inside the src property of img

 <a class="collapsed"
   data-toggle="collapse"
   data-parent="#accordion"
   href="#collapseTwo"
   aria-expanded="false"
   aria-controls="collapseTwo"
   (click)="collapsed = !collapsed">
   <img [src]="collapsed ? 'downArrow.svg' : 'upArrow.svg'">
 </a>


问:
Align text to top in multiline form fields for dynamically generated PDF
I have a PDF form with text aligned in the middle for multiline fields, I am looking for a script that will execute when the file is opened to align those text to the top instead.

It has been created using this converter (https://www.idrsolutions.com/online-pdf-to-html5-converter) to generate an HTML version of a PDF form. Then there is a function to convert it back to PDF.

For example with this: https://files.idrsolutions.com/Examples/FDFForms/CVData/form.html

You can enter some text and then click the save icon to generate the PDF.

Here is the generated file too: https://devcn.000webhostapp.com/temp/sampleAlign.pdf

In the PDF generated the text that appears in the multiline form fields is aligned to the middle. If you edit the text with changes it then aligns it to the top. Also if you select the field properties and change the multiline checkbox deselecting and selecting it again the text then too aligns to the top. Would like to automate this somehow so that when the user opens the PDF the texts are aligned to the top.

答:
First, multiline text fields in Acrobat always align to the top unless the field is set to allow rich text and the user defines the field to vertically align the text to the middle; there is no way to define vertically align center in a typical PDF field programmatically and have it stick through a user edit.

What you are seeing when you first open the file is the field appearance which was generated by the converter. You can add a script at the document level that toggles the "delay" property which will cause the appearance to be regenerated by the viewer. You'd add this to a document level script so it runs when the file is first opened. See code and warning below.

```<code>nFields = this.numFields;
for (var i = 0; i < nFields; i++) {
    var f = this.getField(this.getNthFieldName(i));
    f.delay = true;
    f.delay = false
}
</code>```

However, this will only run in a JavaScript capable viewer the can edit PDF like Acrobat and Reader and a few others. When I selected your link, it opened in Chrome first, which doesn't execute JavaScript. Unfortunately, non-javascript capable viewers are built into most browsers now so the likelihood of the file first being opened by the user and having your script run is low. You need to fix the appearance in the conversion process, not in the viewer.

To do that, either preprocess the HTML so that the appearance generated by the converter matches the properties of the PDF field that will be generated or convince IDR to update their software to create appearances that reflect the properties of the field generated rather than the properties of the HTML field source.

Body:
First, multiline text fields in Acrobat always align to the top unless the field is set to allow rich text and the user defines the field to vertically align the text to the middle; there is no way to define vertically align center in a typical PDF field programmatically and have it stick through a user edit.

What you are seeing when you first open the file is the field appearance which was generated by the converter. You can add a script at the document level that toggles the "delay" property which will cause the appearance to be regenerated by the viewer. You'd add this to a document level script so it runs when the file is first opened. See code and warning below.

nFields = this.numFields;
for (var i = 0; i < nFields; i++) {
    var f = this.getField(this.getNthFieldName(i));
    f.delay = true;
    f.delay = false
}

However, this will only run in a JavaScript capable viewer the can edit PDF like Acrobat and Reader and a few others. When I selected your link, it opened in Chrome first, which doesn't execute JavaScript. Unfortunately, non-javascript capable viewers are built into most browsers now so the likelihood of the file first being opened by the user and having your script run is low. You need to fix the appearance in the conversion process, not in the viewer.

To do that, either preprocess the HTML so that the appearance generated by the converter matches the properties of the PDF field that will be generated or convince IDR to update their software to create appearances that reflect the properties of the field generated rather than the properties of the HTML field source.


问:
UWP App with release configuration and .net native crashes only when build on VSTS hosted agent
We implemented a build pipeline for our UWP app on VSTS. We can build the application on any of our developer workstations in release mode with .NET native enabled and the app works as expected.

When we build the same application on a Hosted VS2017 Agent in VSTS, the application also builds successful and the resulting appxbundle file can be installed on a device. However, the application crashes right after showing the splash screen.

I can't see any difference in the way we build the application in VS2017 compared to the way it is build on the Hosted VS2017 Agent in VSTS.

The event log shows the following right after the crash:

Faulting application name: Foo.exe, version: 0.19.1.0, time stamp: 0x5a1d8e4a
Faulting module name: Windows.UI.Xaml.dll, version: 10.0.16299.15, time stamp: 0xf6706fe0
Exception code: 0xc000027b
Fault offset: 0x00000000006e7269
Faulting process ID: 0x3044
Faulting application start time: 0x01d368691c216952
Faulting application path: C:\Program Files\WindowsApps\Foo_0.19.1.0_x64__fdr8vq4bd9b2a\Foo.exe
Faulting module path: C:\Windows\System32\Windows.UI.Xaml.dll
Report ID: 2655f631-947c-42e5-b3d4-2d2679a93332
Faulting package full name: Foo_0.19.1.0_x64__fdr8vq4bd9b2a
Faulting package-relative application ID: App

The build step in VSTS is configured as following:

```<code>/p:AppxBundlePlatforms="$(BuildPlatform)" /p:AppxPackageDir="$(Build.ArtifactStagingDirectory)\AppxPackages\\" /p:AppxBundle=Always /p:UapAppxPackageBuildMode=StoreUpload
</code>```

If I use the same command line and run it on any developer workstation it works and the resulting appxbundle can be installed and started without any crash.

Any idea what the difference could be or how I can debug the app best?

答:
The issue is caused by a upload task to App Center (aka Mobile Center) within the build pipeline of VSTS. This tasks seems to "corrupt" the file in a really strange way.

I replaced the task with one using the App Center CLI and the upload works and the app no longer crashes.

I posted another question for the root cause here: Distribute UWP App to App Center (aka Mobile Center) using VSTS Task

Body:
We implemented a build pipeline for our UWP app on VSTS. We can build the application on any of our developer workstations in release mode with .NET native enabled and the app works as expected.

When we build the same application on a Hosted VS2017 Agent in VSTS, the application also builds successful and the resulting appxbundle file can be installed on a device. However, the application crashes right after showing the splash screen.

I can't see any difference in the way we build the application in VS2017 compared to the way it is build on the Hosted VS2017 Agent in VSTS.

The event log shows the following right after the crash:

Faulting application name: Foo.exe, version: 0.19.1.0, time stamp: 0x5a1d8e4a
Faulting module name: Windows.UI.Xaml.dll, version: 10.0.16299.15, time stamp: 0xf6706fe0
Exception code: 0xc000027b
Fault offset: 0x00000000006e7269
Faulting process ID: 0x3044
Faulting application start time: 0x01d368691c216952
Faulting application path: C:\Program Files\WindowsApps\Foo_0.19.1.0_x64__fdr8vq4bd9b2a\Foo.exe
Faulting module path: C:\Windows\System32\Windows.UI.Xaml.dll
Report ID: 2655f631-947c-42e5-b3d4-2d2679a93332
Faulting package full name: Foo_0.19.1.0_x64__fdr8vq4bd9b2a
Faulting package-relative application ID: App

The build step in VSTS is configured as following:

/p:AppxBundlePlatforms="$(BuildPlatform)" /p:AppxPackageDir="$(Build.ArtifactStagingDirectory)\AppxPackages\\" /p:AppxBundle=Always /p:UapAppxPackageBuildMode=StoreUpload

If I use the same command line and run it on any developer workstation it works and the resulting appxbundle can be installed and started without any crash.

Any idea what the difference could be or how I can debug the app best?


问:
How to disable and put limits on checkboxes with radio button (Javascript)
I have a radio-type button and a few checkboxes. I basically want to disable the checkboxes when I choose Non-Exclusive then limit the checkboxes to 2 if I choose Package 1.

Here's my html code:

```<code><label>
    <input type="radio" value="non-exclusive" id="non-exclusive" name="packages"> Non-Exclusive
    </label>
    <label>
    <input type="radio" value="package1" id="package1" name="packages"> Package 1
    </label>
    <label>
    <input type="radio" value="package2" id="package2" name="packages"> Package 2
    </label>
<br />
    <label><h2>Rice </h2></label>
    <br />
    <a style="color: darkred;">2 Choices</a>
    <br />
    <div class="checkboxfood">
      <label>
      <input type="checkbox" class="food" value=""> Plain Rice (Mandatory)
      </label>
    <label>
      <input type="checkbox" class="food" value=""> Buttered Rice
      </label>
      <label>
      <input type="checkbox" class="food" value=""> Garlic Rice
      </label>
    <label>
      <input type="checkbox" class="food" value=""> Kimchi Rice
      </label>
    <label>
      <input type="checkbox" class="food" value=""> Adobo Rice
      </label>
    <label>
      <input type="checkbox" class="food" value=""> Yang Chow Rice
      </label>
    <br />
    <label>
      <input type="checkbox" class="food" value=""> Shanghai Rice
      </label>
    <label>
      <input type="checkbox" class="food" value=""> Bagoong Rice
      </label>
    </div>
</code>```

I've tried this javascript:

```<code>$('#package1').on('change', function() {
$('.checkBoxes :checkbox').prop('disabled', true);
$(':checkbox:eq(0), :checkbox:eq(1), :checkbox:eq(2), :checkbox:eq(3), :checkbox:eq(4), :checkbox:eq(5)\n\
, :checkbox:eq(6), :checkbox:eq(7), :checkbox:eq(8), :checkbox:eq(9), :checkbox:eq(10), :checkbox:eq(11), :checkbox:eq(12)\n\
, :checkbox:eq(13), :checkbox:eq(14), :checkbox:eq(15)').prop('disabled', false);

});

$('#package2').on('change', function() {
$('.checkBoxes :checkbox').prop('disabled', true);
$(':checkbox:eq(0), :checkbox:eq(1)').prop('disabled', false);
});

$('#non-exclusive').on('change', function() {
$('.checkBoxes :checkbox').prop('disabled', true);
});
</code>```

It enables checkboxes but it won't limit it. Also if I press back to Non-Exlusive the checkboxes doesn't go back to being "disabled".

I've also tried this code:

```<code>var limit = 3;
$('input.single-checkbox').on('change', function(evt) {
if($(this).siblings(':checked').length >= limit) {
   this.checked = false;
}
});
</code>```

Which limits my checkboxes but isn't responsive to my radio buttons.

答:
Following will do all you ask as well as uncheck any checkboxes greater than 2 if user changes to package 1 after selecting more than 2 in package 2

var $checkboxes = $('.checkboxfood :checkbox'),
  $radios = $('.radios input:radio')

$radios.on('change', function(e) {
  if (this.value === 'non-exclusive') {
    $checkboxes.prop('checked', false).prop('disabled', true)
  } else {
    $checkboxes.prop('disabled', false);
  }
  if (this.value == 'package1') {
    // leave only 2 checked
    $checkboxes.filter(':checked:gt(1)').prop('checked', false)
  }
});

// only need to know if package 1 is checked when checkboxes are selected
$checkboxes.on('change', function(e){
  if($('#package1').is(':checked') && $checkboxes.filter(':checked').length >2){
    this.checked = false;
    console.log("Only 2 allowed for package 1")
  }
})```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="radios">
  <label>
    <input type="radio" value="non-exclusive" id="non-exclusive" name="packages"> Non-Exclusive
  </label>
  <label>
    <input type="radio" value="package1" id="package1" name="packages"> Package 1
  </label>
  <label>
    <input type="radio" value="package2" id="package2" name="packages"> Package 2
  </label>
</div>

<br />
<label>
  <h2>Rice </h2></label>
<br />
2 Choices
<br />
<div class="checkboxfood">
  <label>
    <input type="checkbox" class="food" value=""> Plain Rice (Mandatory)
  </label>
  <label>
    <input type="checkbox" class="food" value=""> Buttered Rice
  </label>
  <label>
    <input type="checkbox" class="food" value=""> Garlic Rice
  </label>
  <label>
    <input type="checkbox" class="food" value=""> Kimchi Rice
  </label>
  <label>
    <input type="checkbox" class="food" value=""> Adobo Rice
  </label>
  <label>
    <input type="checkbox" class="food" value=""> Yang Chow Rice
  </label>
  <br />
  <label>
    <input type="checkbox" class="food" value=""> Shanghai Rice
  </label>
  <label>
    <input type="checkbox" class="food" value=""> Bagoong Rice
  </label>
</div></code>```

Body:
I have a radio-type button and a few checkboxes. I basically want to disable the checkboxes when I choose Non-Exclusive then limit the checkboxes to 2 if I choose Package 1.

Here's my html code:

    <input type="radio" value="non-exclusive" id="non-exclusive" name="packages"> Non-Exclusive

    <input type="radio" value="package1" id="package1" name="packages"> Package 1

    <input type="radio" value="package2" id="package2" name="packages"> Package 2

Rice

    2 Choices

      <input type="checkbox" class="food" value=""> Plain Rice (Mandatory)

      <input type="checkbox" class="food" value=""> Buttered Rice

      <input type="checkbox" class="food" value=""> Garlic Rice

      <input type="checkbox" class="food" value=""> Kimchi Rice

      <input type="checkbox" class="food" value=""> Adobo Rice

      <input type="checkbox" class="food" value=""> Yang Chow Rice

      <input type="checkbox" class="food" value=""> Shanghai Rice

      <input type="checkbox" class="food" value=""> Bagoong Rice

I've tried this javascript:

$('#package1').on('change', function() {
$('.checkBoxes :checkbox').prop('disabled', true);
$(':checkbox:eq(0), :checkbox:eq(1), :checkbox:eq(2), :checkbox:eq(3), :checkbox:eq(4), :checkbox:eq(5)\n\
, :checkbox:eq(6), :checkbox:eq(7), :checkbox:eq(8), :checkbox:eq(9), :checkbox:eq(10), :checkbox:eq(11), :checkbox:eq(12)\n\
, :checkbox:eq(13), :checkbox:eq(14), :checkbox:eq(15)').prop('disabled', false);

});

$('#package2').on('change', function() {
$('.checkBoxes :checkbox').prop('disabled', true);
$(':checkbox:eq(0), :checkbox:eq(1)').prop('disabled', false);
});

$('#non-exclusive').on('change', function() {
$('.checkBoxes :checkbox').prop('disabled', true);
});

It enables checkboxes but it won't limit it. Also if I press back to Non-Exlusive the checkboxes doesn't go back to being "disabled".

I've also tried this code:

var limit = 3;
$('input.single-checkbox').on('change', function(evt) {
if($(this).siblings(':checked').length >= limit) {
   this.checked = false;
}
});

Which limits my checkboxes but isn't responsive to my radio buttons.

Body:
Following will do all you ask as well as uncheck any checkboxes greater than 2 if user changes to package 1 after selecting more than 2 in package 2

var $checkboxes = $('.checkboxfood :checkbox'),
  $radios = $('.radios input:radio')

$radios.on('change', function(e) {
  if (this.value === 'non-exclusive') {
    $checkboxes.prop('checked', false).prop('disabled', true)
  } else {
    $checkboxes.prop('disabled', false);
  }
  if (this.value == 'package1') {
    // leave only 2 checked
    $checkboxes.filter(':checked:gt(1)').prop('checked', false)
  }
});

// only need to know if package 1 is checked when checkboxes are selected
$checkboxes.on('change', function(e){
  if($('#package1').is(':checked') && $checkboxes.filter(':checked').length >2){
    this.checked = false;
    console.log("Only 2 allowed for package 1")
  }
})

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="radios">
  <label>
    <input type="radio" value="non-exclusive" id="non-exclusive" name="packages"> Non-Exclusive
  </label>
  <label>
    <input type="radio" value="package1" id="package1" name="packages"> Package 1
  </label>
  <label>
    <input type="radio" value="package2" id="package2" name="packages"> Package 2
  </label>
</div>

<br />
<label>
  <h2>Rice </h2></label>
<br />
<a style="color: darkred;">2 Choices</a>
<br />
<div class="checkboxfood">
  <label>
    <input type="checkbox" class="food" value=""> Plain Rice (Mandatory)
  </label>
  <label>
    <input type="checkbox" class="food" value=""> Buttered Rice
  </label>
  <label>
    <input type="checkbox" class="food" value=""> Garlic Rice
  </label>
  <label>
    <input type="checkbox" class="food" value=""> Kimchi Rice
  </label>
  <label>
    <input type="checkbox" class="food" value=""> Adobo Rice
  </label>
  <label>
    <input type="checkbox" class="food" value=""> Yang Chow Rice
  </label>
  <br />
  <label>
    <input type="checkbox" class="food" value=""> Shanghai Rice
  </label>
  <label>
    <input type="checkbox" class="food" value=""> Bagoong Rice
  </label>
</div>


问:
Finding factors to an integer using functions in c++
I am trying to print factors for a given integer. As output, I should be printing the input number and factors of that number. Instead, i get output of 2.

Where have i made a mistake?

I am new to c++ and any help would be appreciated.

Code:

```<code>#include<iostream>

int fact(int x);

using namespace std;

int main()
{
    int x;
    cout<<"plz,enter no."<<endl;
    cout<<fact(x)<<endl;
}
int fact(int num)
{
    for ( int i = 2; i <= num; ++i )
    {
        while ( num % i == 0 )
        {
            num /= i;
            std::cout << i << std::endl;
        }
    }
}
</code>```

答:
I have made your code work. But you can improve this code by running only sqrt(num) iterations.

```<code>#include<iostream>

int fact(int x);

using namespace std;

int main()
{
    int x;
    cout<<"plz,enter no."<<endl;
    cin >> x;
    cout << "Factors: ";
    fact(x);
}
int fact(int num)
{
    for ( int i = 1; i <= num; ++i )
    {
        if ( num % i == 0 )
        {
            std::cout << i << " ";
        }
    }
    cout << endl;
}
</code>```

Body:
I am trying to print factors for a given integer. As output, I should be printing the input number and factors of that number. Instead, i get output of 2.

Where have i made a mistake?

I am new to c++ and any help would be appreciated.

Code:

#include<iostream>

int fact(int x);

using namespace std;

int main()
{
    int x;
    cout<<"plz,enter no."<<endl;
    cout<<fact(x)<<endl;
}
int fact(int num)
{
    for ( int i = 2; i <= num; ++i )
    {
        while ( num % i == 0 )
        {
            num /= i;
            std::cout << i << std::endl;
        }
    }
}

Body:
I have made your code work. But you can improve this code by running only sqrt(num) iterations.

#include<iostream>

int fact(int x);

using namespace std;

int main()
{
    int x;
    cout<<"plz,enter no."<<endl;
    cin >> x;
    cout << "Factors: ";
    fact(x);
}
int fact(int num)
{
    for ( int i = 1; i <= num; ++i )
    {
        if ( num % i == 0 )
        {
            std::cout << i << " ";
        }
    }
    cout << endl;
}


问:
React: Material-ui tableRow can not choose, if using setState in onRowSelection
I have a material-ui table

 And I want to Pass selected rows to function in DELETE button.

```<code>  constructor(props) {
      super(props);
      this.state = {
            selectedRows: 'none',
      };
      }

  onRowSelection(val){
    console.log(this);
    this.setState({
      selectedRows: val,
    });
  }

render() {
<Table
              fixedHeader={true}
              selectable={true}
              multiSelectable={true}
              onRowSelection={this.onRowSelection.bind(this)}
            >
    ...
               <TableFooter adjustForCheckbox={true}>
                 <TableRow>
                   <TableRowColumn colSpan="5" style={{textAlign: 'right'}}>
                  <RaisedButton
                    primary={true}
                    label="DELETE"
                    labelPosition="after"
                    icon={<ActionDelete/>}
                    onClick={this.props.onDelete.bind(this.state.selectedRows)}
                  />
                   </TableRowColumn>
                 </TableRow>
               </TableFooter>
</Table>
}
</code>```

I want to pass this.state.selectedRows to this.props.onDelete function, but as
reffered in this issue, material-ui has problems with setState in onRowSelection.

How may I fix it, is there another way to access selected rows & pass them to some function and why such errors exist (why onRowSelection minds if I use setState on parent component?)

答:
I think the issue here is the way you are using bind function. bind function's first parameter should be thisArg and second parameter is what you want to pass to the resultant function. So you should pass function to onClick like this

```<code>onClick={this.props.onDelete.bind(this, this.state.selectedRows)}
</code>```

Body:
I have a material-ui table

 And I want to Pass selected rows to function in DELETE button.

  constructor(props) {
      super(props);
      this.state = {
            selectedRows: 'none',
      };
      }

  onRowSelection(val){
    console.log(this);
    this.setState({
      selectedRows: val,
    });
  }

render() {

    ...
               <TableFooter adjustForCheckbox={true}>
                 <TableRow>
                   <TableRowColumn colSpan="5" style={{textAlign: 'right'}}>
                  <RaisedButton
                    primary={true}
                    label="DELETE"
                    labelPosition="after"
                    icon={<ActionDelete/>}
                    onClick={this.props.onDelete.bind(this.state.selectedRows)}
                  />
                   </TableRowColumn>
                 </TableRow>
               </TableFooter>

}

I want to pass this.state.selectedRows to this.props.onDelete function, but as
reffered in this issue, material-ui has problems with setState in onRowSelection.

How may I fix it, is there another way to access selected rows & pass them to some function and why such errors exist (why onRowSelection minds if I use setState on parent component?)

Body:
I think the issue here is the way you are using bind function. bind function's first parameter should be thisArg and second parameter is what you want to pass to the resultant function. So you should pass function to onClick like this

onClick={this.props.onDelete.bind(this, this.state.selectedRows)}


问:
Let JSON object accept bytes or let urlopen output strings
With Python 3 I am requesting a json document from a URL.

```<code>response = urllib.request.urlopen(request)
</code>```

The response object is a file-like object with read and readline methods. Normally a JSON object can be created with a file opened in text mode.

```<code>obj = json.load(fp)
</code>```

What I would like to do is:

```<code>obj = json.load(response)
</code>```

This however does not work as urlopen returns a file object in binary mode.

A work around is of course:

```<code>str_response = response.read().decode('utf-8')
obj = json.loads(str_response)
</code>```

but this feels bad...

Is there a better way that I can transform a bytes file object to a string file object? Or am I missing any parameters for either urlopen or json.load to give an encoding?

答:
Your workaround actually just saved me. I was having a lot of problems processing the request using the Falcon framework. This worked for me. req being the request form curl pr httpie</p>

```<code>json.loads(req.stream.read().decode('utf-8'))
</code>```

Body:
With Python 3 I am requesting a json document from a URL.

response = urllib.request.urlopen(request)

The response object is a file-like object with read and readline methods. Normally a JSON object can be created with a file opened in text mode.

obj = json.load(fp)

What I would like to do is:

obj = json.load(response)

This however does not work as urlopen returns a file object in binary mode.

A work around is of course:

str_response = response.read().decode('utf-8')
obj = json.loads(str_response)

but this feels bad...

Is there a better way that I can transform a bytes file object to a string file object? Or am I missing any parameters for either urlopen or json.load to give an encoding?

Body:
Your workaround actually just saved me. I was having a lot of problems processing the request using the Falcon framework. This worked for me. req being the request form curl pr httpie

json.loads(req.stream.read().decode('utf-8'))


问:
Making a POST call to Google Translate with Jersey returns HTTP 404
I'm trying to write a POST call to Google Translate with Jersey 1.5. This is my code:

```<code>package main;

import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.WebResource;
import com.sun.jersey.core.util.MultivaluedMapImpl;

import javax.ws.rs.core.MultivaluedMap;

public class Main {

    private static String GOOGLE_TRANSLATE_URL = "https://www.googleapis.com/language/translate/v2";

    private static String translateString(String sourceString, String sourceLanguage, String targetLanguage) {
        String response;
        Client c = Client.create();

        WebResource wr = c.resource(GOOGLE_TRANSLATE_URL);
        MultivaluedMap<String, String> params = new MultivaluedMapImpl();
        params.add("q", sourceString);
        params.add("source", sourceLanguage);
        params.add("target", targetLanguage);
        params.add("key", "xxxx");
        wr.header("X-HTTP-Method-Override", "GET");
        response = wr.post(String.class, params);

        return response;
    }

    public static void main(String[] args) {
        System.out.println(translateString("Hello", "en", "sv"));
    }
}
</code>```

When I run this, all I get back is this: com.sun.jersey.api.client.UniformInterfaceException: POST https://www.googleapis.com/language/translate/v2 returned a response status of 404.

I've managed to accomplish this with a simple cURL command like so:

curl --header "X-HTTP-Method-Override: GET" -d key=xxxx -d q=Hello -d source=en -d target=sv https://www.googleapis.com/language/translate/v2

Thanks in advance!

答:
I suspect that POST with zero Content-Length is not something a normal HTTP server will accept. The RFC does not define this case, but the main assumption of POST is that you're sending a message body.

Looking at the Google API, they mention the following

You can also use POST to invoke the API if you want to send more data in a single request. The q parameter in the POST body must be less than 5K characters. To use POST, you must use the X-HTTP-Method-Override header to tell the Translate API to treat the request as a GET (use X-HTTP-Method-Override: GET).

This means that instead of adding q, source and target parameters in the URL, you need to do so in the POST body. I'm not familiar with the Jersey API, from a brief look you just need to add params as an explicit second parameter to the .post call, remove the queryParams() call, and set the Content-Length properly.

Body:
I'm trying to write a POST call to Google Translate with Jersey 1.5. This is my code:

package main;

import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.WebResource;
import com.sun.jersey.core.util.MultivaluedMapImpl;

import javax.ws.rs.core.MultivaluedMap;

public class Main {

    private static String GOOGLE_TRANSLATE_URL = "https://www.googleapis.com/language/translate/v2";

    private static String translateString(String sourceString, String sourceLanguage, String targetLanguage) {
        String response;
        Client c = Client.create();

        WebResource wr = c.resource(GOOGLE_TRANSLATE_URL);
        MultivaluedMap<String, String> params = new MultivaluedMapImpl();
        params.add("q", sourceString);
        params.add("source", sourceLanguage);
        params.add("target", targetLanguage);
        params.add("key", "xxxx");
        wr.header("X-HTTP-Method-Override", "GET");
        response = wr.post(String.class, params);

        return response;
    }

    public static void main(String[] args) {
        System.out.println(translateString("Hello", "en", "sv"));
    }
}

When I run this, all I get back is this: com.sun.jersey.api.client.UniformInterfaceException: POST https://www.googleapis.com/language/translate/v2 returned a response status of 404.

I've managed to accomplish this with a simple cURL command like so:

curl --header "X-HTTP-Method-Override: GET" -d key=xxxx -d q=Hello -d source=en -d target=sv https://www.googleapis.com/language/translate/v2

Thanks in advance!


问:
How to edit lists using input function
I am trying to edit and fill the lists in A, B and C using the input function.

```<code>A = ['']
B = ['']
C = ['']
key = input()
key[0] = 'X'
</code>```

But i get this error.

```<code>TypeError: 'str' object does not support item assignment
</code>```

How can i use the input function to edit my list. Or you might have better way to do this?

Thank You!

答:
The strings per se in Python are immutable (you can't modify its content) however what you can do is to store them in a char list and a list in python is a mutable object, hence you can modify the char list as you see fit.

```<code>key = input() # "hello"
new_key = list(key) # ['h','e','l','l','o']
new_key[0] = 'X' # ['X','e','l','l','o']
</code>```

Title: How to edit lists using input function

Body:
I am trying to edit and fill the lists in A, B and C using the input function.

A = ['']
B = ['']
C = ['']
key = input()
key[0] = 'X'

But i get this error.

TypeError: 'str' object does not support item assignment

How can i use the input function to edit my list. Or you might have better way to do this?

Thank You!

Body:
The strings per se in Python are immutable (you can't modify its content) however what you can do is to store them in a char list and a list in python is a mutable object, hence you can modify the char list as you see fit.

key = input() # "hello"
new_key = list(key) # ['h','e','l','l','o']
new_key[0] = 'X' # ['X','e','l','l','o']


问:
Firebase .childAdded does not work, because observed child might not exist yet
I want to use some data out of the Database for later purpose. However the data I want to load might not exist yet, because the observed data is a dictionary of friend requests which do not exist at the very first time the app is used. Although the .childAdded observer should do it, it just stops there and the code is not executed further

```<code>func getFriendRequest(_ uid: String, completion: @escaping ([String]) -> Void) {
    var friendRequests = [String]()
    let currentUserRef = DatabaseReference.users(uid: self.currentUser.uid).reference()
    currentUserRef.child("sendFriendRequest").observe(.childAdded, with: { (snap) in
        let request = FriendRequest(dictionary: snap.value as! [String : Any])
        let requestedUid = request.uid
        print(requestedUid)
        friendRequests = [requestedUid]
        completion(friendRequests)
    }, withCancel: nil)
}
</code>```

It does not get into the observe method ...
Has anyone an idea why that is?

答: The .childAdded completion handler will only be called when there is a child. If there are no child nodes it will not be invoked until you add a child under sendFriendRequest.

Body:
I want to use some data out of the Database for later purpose. However the data I want to load might not exist yet, because the observed data is a dictionary of friend requests which do not exist at the very first time the app is used. Although the .childAdded observer should do it, it just stops there and the code is not executed further

func getFriendRequest(_ uid: String, completion: @escaping ([String]) -> Void) {
    var friendRequests = [String]()
    let currentUserRef = DatabaseReference.users(uid: self.currentUser.uid).reference()
    currentUserRef.child("sendFriendRequest").observe(.childAdded, with: { (snap) in
        let request = FriendRequest(dictionary: snap.value as! [String : Any])
        let requestedUid = request.uid
        print(requestedUid)
        friendRequests = [requestedUid]
        completion(friendRequests)
    }, withCancel: nil)
}

It does not get into the observe method ...
Has anyone an idea why that is?


问:
How do I upload images in php after I have already saved data from the form1 and images are uploaded in form2
I have a html page, with a form and image upload,
I want to update the database with the images once uploaded, the two form work well individually, but I need to link the form-data to the uploaded images in the database.

kindly help with logic, I am considering using sessions

答:
You can use session as you mentioned or you can updated the relevant record with the next form details.

Say for example, once first form is filled and submited by the user, add those details in database and get the ID of that record.
When the second form is submited by the user, update the same record which you have already added for form 1.

So in database you will have only one record for both the forms with all relavent detials.


问:
Is there a way to write node.js code synchronously?
I am trying to create a program that analyses some data. The data I am collection form the internet with node.js. I'm having a very hard time with the fact that the code is asynchronous, and I'm getting a lot of bugs because of it.

I know that it is not efficient at all, but is there a way to write the whole code shynchronously?

*I've used a lot of promises and patched a lot of bugs, but I still keep getting bugs because the code is asynchronous, and I'm tired of thinking of creative ideas to make my code work.

答:
If you're using networking (which it sounds like you are to retrieve data from other sources), then NO you can't write synchronous networking code in node.js.  Does not exist.  All networking API in node.js are asynchronous.

To use node.js networking, you must learn asynchronous programming.

It is possible to use only synchronous file I/O which should never be done in server request processing (because it wrecks scalability), but is sometimes useful in server startup and in non-server type scripts.