问:
Crafter 3 Gradle bundle error
I am using Crafter 3.0.2 and trying to create deployable bundles through the gradle tooling provided by the craftercms project.

When executing gradlew build deploy bundle -Pcrafter.profile=true, I received the error message:

```<code>FAILURE: Build failed with an exception.

* Where:
Build file 'build.gradle' line: 774

* What went wrong:
Execution failed for task ':zipauthoring'.
> archive's size exceeds the limit of 4GByte.
</code>```

The gradle suggestion following the error above is to enable zip64. So I added zip64 true to the build.gradle pack method's tasks.create("zip${envName}", Zip.class) {, and the bundle task completed successfully.

However, this approach seemed a little invasive. What is the proper procedure for producing a Crafter 3 bundle with profile enabled? If zip64 is to be used for the authoring bundle, is there a command line option that can be provided instead of editing build.gradle? Alternatively, is there a mechanism for creating only the tar.gz archive (which does not appear to have the 4gb file limitation) instead of the zip archive?

答:
There is a ticket now to allow the users to select the bundle they want: https://github.com/craftercms/craftercms/issues/1669

I've never seen a bundle exceed 600MB, you're pushing up against 4GB which is very unusual. While adding 64bit will help it push on, there might be another issue at play here.

Title: Crafter 3 Gradle bundle error

Body:
I am using Crafter 3.0.2 and trying to create deployable bundles through the gradle tooling provided by the craftercms project.

When executing gradlew build deploy bundle -Pcrafter.profile=true, I received the error message:

FAILURE: Build failed with an exception.

* Where:
Build file 'build.gradle' line: 774

* What went wrong:
Execution failed for task ':zipauthoring'.
> archive's size exceeds the limit of 4GByte.

The gradle suggestion following the error above is to enable zip64. So I added zip64 true to the build.gradle pack method's tasks.create("zip${envName}", Zip.class) {, and the bundle task completed successfully.

However, this approach seemed a little invasive. What is the proper procedure for producing a Crafter 3 bundle with profile enabled? If zip64 is to be used for the authoring bundle, is there a command line option that can be provided instead of editing build.gradle? Alternatively, is there a mechanism for creating only the tar.gz archive (which does not appear to have the 4gb file limitation) instead of the zip archive?


来源: stackexchange

问:
How to add a image at the center of navigationBar in Objective-C?
I am developing in IOS , I use the following code to set a background to the navigationBar.

```<code>[self.navigationController.navigationBar setBackgroundImage:[UIImage imageNamed:@"bar-back"] forBarMetrics:UIBarMetricsDefault];
</code>```

And I want to add a image on navigationBar and center of navigationBar like the following picture.

How to add a image at the center of navigationBar in Objective-C ?

Thanks in advance.

答:
I was facing the same issue, since iOS 11 and Xcode 9 started managing the Navigation Bars with auto layout instead of frames you should be aware of your Navigation Bar layout.

In the WWDC Session 204, Updating your app for iOS 11, was stated that UIToolBar and UINavigationBar was upgraded to use auto layout, and in order to avoid Zero-Sized Custom Views you should know a few things about it.

UINavigation and UIToolBar provide position, do not care about it.

You must provide the size of the Custom view with one of the following:

Constraints for width and height.

Implement intrinsicContentSize

Connect your subviews via constraints.

Answering your question, I set the titleView with a ImageView,providing the size in two different ways:

Giving Height and width explicitly.

```<code>-(void)updateNavTitleView{
    UIImageView *imageView = [[UIImageView alloc] initWithImage:[ UIImage imageNamed:@"TitleViewImage"]];
    [imageView.widthAnchor constraintEqualToConstant:160].active = YES;
    [imageView.heightAnchor constraintEqualToConstant:44].active = YES;
    self.navigationItem.titleView = imageView;
}
</code>```

Or setting the aspect mode as aspectFit

```<code>-(void) updateNavTitleView{
    UIImageView *imageView = [[UIImageView alloc] initWithImage:[ UIImage imageNamed:@"TitleViewImage"]];
    [imageView setContentMode:UIViewContentModeScaleAspectFit];
    self.navigationItem.titleView = imageView;
}
</code>```

In case you want to watch the Session, Session 204

ContentLicense: CC BY-SA 3.0

Body:
I am developing in IOS , I use the following code to set a background to the navigationBar.

[self.navigationController.navigationBar setBackgroundImage:[UIImage imageNamed:@"bar-back"] forBarMetrics:UIBarMetricsDefault];

And I want to add a image on navigationBar and center of navigationBar like the following picture.

How to add a image at the center of navigationBar in Objective-C ?

Thanks in advance.

Body:
I was facing the same issue, since iOS 11 and Xcode 9 started managing the Navigation Bars with auto layout instead of frames you should be aware of your Navigation Bar layout.

In the WWDC Session 204, Updating your app for iOS 11, was stated that UIToolBar and UINavigationBar was upgraded to use auto layout, and in order to avoid Zero-Sized Custom Views you should know a few things about it.

UINavigation and UIToolBar provide position, do not care about it.

You must provide the size of the Custom view with one of the following:

Constraints for width and height.

Implement intrinsicContentSize

Connect your subviews via constraints.

Answering your question, I set the titleView with a ImageView,providing the size in two different ways:

Giving Height and width explicitly.

-(void)updateNavTitleView{
    UIImageView *imageView = [[UIImageView alloc] initWithImage:[ UIImage imageNamed:@"TitleViewImage"]];
    [imageView.widthAnchor constraintEqualToConstant:160].active = YES;
    [imageView.heightAnchor constraintEqualToConstant:44].active = YES;
    self.navigationItem.titleView = imageView;
}

Or setting the aspect mode as aspectFit

-(void) updateNavTitleView{
    UIImageView *imageView = [[UIImageView alloc] initWithImage:[ UIImage imageNamed:@"TitleViewImage"]];
    [imageView setContentMode:UIViewContentModeScaleAspectFit];
    self.navigationItem.titleView = imageView;
}

In case you want to watch the Session, Session 204


问:
Excel - Create a countdown that ignores blanks; Take the minimum date of 3 columns - TODAY(),
I am trying to create a column that displays the number of days between now and the next time a person is required to participate in a study.

If there were no blanks in the columns that list the dates, the following formula works (N,P & R contain dates):

```<code>=MIN(N5,P5,R5)-TODAY()
</code>```

Unfortunately, my data contains blanks in the columns, which returns a "N/A" value.

Does anyone know how to avoid counting blanks in this situation?
Please let me know. Thanks.

答:
SMALL function will ignore any blanks, so you can use this formula

=SMALL((N5,P5,R5),1)-TODAY()

If all three cells are blank you'll get a #NUM! error so you might want to add an IFERROR function to handle that, e.g.

=IFERROR(SMALL((N5,P5,R5),1)-TODAY(),"")

Body:
I am trying to create a column that displays the number of days between now and the next time a person is required to participate in a study.

If there were no blanks in the columns that list the dates, the following formula works (N,P & R contain dates):

=MIN(N5,P5,R5)-TODAY()

Unfortunately, my data contains blanks in the columns, which returns a "N/A" value.

Does anyone know how to avoid counting blanks in this situation?
Please let me know. Thanks.


问:
Weird bug - the application is stuck, but the UI still responds
So.. I have a really strange bug in my application.

At some point, for some reason, application stops handling some events, for example: adapters wont update after notifydatasetchanged call, mapview is not responding at all, activities wont start, any kind of fragments transaction does nothing - list goes on.

But at the same time, if I'll press some button - it displays ripple effect and fires onClick (and even network request started by this click finishes successfully), this means that main thread still works correctly.

I am able to hide and show views programmatically, receive firebase realtime db events and do all kind of business logic.

My wild guess is that either some thread responsible for this kind of stuff stuck (deadlock?), or maybe this is how application works after OutOfMemoryException? Because this usually happens after working with map a lot (Yandex Map).

I really don't understand whats going on.

答:
I figured it out. This weird behaviour was due to a lot work with UI elements from one background thread. I don't know why and how project was still working, but thats the case. Something breaks after N calls to UI from non-UI threads.

Also, on Android 8 it breaks right away, but on lower api levels application can work for hours before breaking.


问:
Spring Cloud microservice configuration in cloud deployment
I created a sample Spring Cloud microservice by using Eureka server and Zuul Spring Cloud tools in my local system. It runs properly. I registered my microservice as client at eureka server project. And also registered my Zuul as client at Eureka server.

The below is my Eureka server project application.properties,

```<code>server.port=8071
eureka:
numberRegistrySyncRetries: 1
instance:
hostname: localhost
client:
registerWithEureka: false
fetchRegistry: false
serviceUrl:
  defaultZone: http://localhost:8071/eureka/
server:
enable-self-preservation: true
</code>```

And the below code is my microservice application.property file content,

```<code>eureka.client.serviceUrl.defaultZone=http://localhost:8071/eureka/
eureka.client.register-with-eureka=true
eureka.client.fetch-registry=true
</code>```

And My zuul application.properties code is,

```<code>eureka.client.serviceUrl.defaultZone=http://localhost:8071/eureka/
eureka.client.register-with-eureka=true
eureka.client.fetch-registry=true
spring.application.name=eurekaZuulClient
ribbon.eureka.enabled=true
zuul:
 routes:
  espace-service:
   path: /espace/**
   stripPrefix: true
   serviceId: espace-service
   server.port=8090
</code>```

Here my doubt is that when we deploying this application into cloud, What change we need to make in application.properties?, since we don't know about server.port and "eureka.client.serviceUrl.defaultZone" at cloud.Here I only running with localhost.

So how we need to follow cloud deployment procedure in configuration? I am beginner with Spring Cloud, and I have lot of confusions in these configuration.

答:
Its good to have known port for Eureka, so that we can easily check the status of various APIs. There are multiple ways to handle this for cloud deployment.

You can hard code the IP of the instance where eureka is deployed and separate it with profile names.

```<code>eureka:
  client:
    serviceUrl:
      defaultZone: http://localhost:8761/eureka/
---
eureka:
  client:
    serviceUrl:
      defaultZone: http://172.0.0.1:8761/eureka/
</code>```

The bit of configuration under the --- delimiter is for when the application is run under the cloud Spring profile. It’s easy to set a profile using the SPRING_PROFILES_ACTIVE environment variable. You can configure Cloud Foundry environment variables in your manifest.yml or, on Cloud Foundry Lattice, your Docker file.

If hostname can’t be determined by Java, then IP address is sent to Eureka. The only explict way of setting hostname is by using eureka.instance.hostname. You can set your hostname at the runtime using environment variable, for example eureka.instance.hostname=${HOST_NAME}

```<code>eureka:
  instance:
    serviceUrl:
      defaultZone: http://${eureka.instance.hostname}:${server.port}/eureka/
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I created a sample Spring Cloud microservice by using Eureka server and Zuul Spring Cloud tools in my local system. It runs properly. I registered my microservice as client at eureka server project. And also registered my Zuul as client at Eureka server.

The below is my Eureka server project application.properties,

server.port=8071
eureka:
numberRegistrySyncRetries: 1
instance:
hostname: localhost
client:
registerWithEureka: false
fetchRegistry: false
serviceUrl:
  defaultZone: http://localhost:8071/eureka/
server:
enable-self-preservation: true

And the below code is my microservice application.property file content,

eureka.client.serviceUrl.defaultZone=http://localhost:8071/eureka/
eureka.client.register-with-eureka=true
eureka.client.fetch-registry=true

And My zuul application.properties code is,

eureka.client.serviceUrl.defaultZone=http://localhost:8071/eureka/
eureka.client.register-with-eureka=true
eureka.client.fetch-registry=true
spring.application.name=eurekaZuulClient
ribbon.eureka.enabled=true
zuul:
 routes:
  espace-service:
   path: /espace/**
   stripPrefix: true
   serviceId: espace-service
   server.port=8090

Here my doubt is that when we deploying this application into cloud, What change we need to make in application.properties?, since we don't know about server.port and "eureka.client.serviceUrl.defaultZone" at cloud.Here I only running with localhost.

So how we need to follow cloud deployment procedure in configuration? I am beginner with Spring Cloud, and I have lot of confusions in these configuration.

Body:
Its good to have known port for Eureka, so that we can easily check the status of various APIs. There are multiple ways to handle this for cloud deployment.

You can hard code the IP of the instance where eureka is deployed and separate it with profile names.

eureka:
  client:
    serviceUrl:
      defaultZone: http://localhost:8761/eureka/
---
eureka:
  client:
    serviceUrl:
      defaultZone: http://172.0.0.1:8761/eureka/

The bit of configuration under the --- delimiter is for when the application is run under the cloud Spring profile. It’s easy to set a profile using the SPRING_PROFILES_ACTIVE environment variable. You can configure Cloud Foundry environment variables in your manifest.yml or, on Cloud Foundry Lattice, your Docker file.

If hostname can’t be determined by Java, then IP address is sent to Eureka. The only explict way of setting hostname is by using eureka.instance.hostname. You can set your hostname at the runtime using environment variable, for example eureka.instance.hostname=${HOST_NAME}

eureka:
  instance:
    serviceUrl:
      defaultZone: http://${eureka.instance.hostname}:${server.port}/eureka/


问:
VSTS Data Charges
Do you get charged per GB for egress traffic out of VSTS?

Say you have a 5gb repository, and 10 developers and they all downloaded the repo; are there limits we will hit and be charged for?

I cannot find any documentation on the VSTS site for traffic or storage quotients.

Many thanks.

答:
There are no extra azure costs when cloning a git repo from VSTS. It is included in the per-user price. </p>

<p>See the additional items builds load tests cost more next to the user costs. </p>

Title: VSTS Data Charges

Body:
There are no extra azure costs when cloning a git repo from VSTS. It is included in the per-user price.

See the additional items builds load tests cost more next to the user costs.


问:
Multiplying parenthesis to get a polynomial in python
I was asked to do the newton polynomial interpolation and I was able to write the main code.
https://en.wikipedia.org/wiki/Newton_polynomial
But there is still one small thing that I am not able to get around since a couple of days, after reading I found a way to do it using Sympy, but I am not allowed to use anything other than basic numpy.
Now my problem is that I trying to multiply something like this

p(x)=j(x-q)(x-w)(x-e)+k(x-w)(x-e)+l(x-e)+d

to get this p(x)=ax³+bx²+cx+d , so I amlooking for the polynomial coefficients a,b,c,d

for example:

p(x)=5-7(x+1)+9(x+1)(x)-7(x+1)(x)(x-1)=-7x³+9x²+9x-2

of course I am looking for the general case, not only for ploynomials from third degree.
Any tip would be much appreciated, I am really stuck at this since a couple of days.
and Sorry for the sloppy writing of notation, but it seems stackoverflow doesn't accept latex and I am not able to post a picture because I don't have rhe required reputation. (if there is other solutuions to post it properly please tell me and I'll just post it again)

Thanks in advance :)

答:
First, I'll rewrite the equation as

c3(x-r3)(x-r2)(x-r1)+c2(x-r2)(x-r1)+c1(x-r1)+c0

Next, note that this is equivalent to:

((c3(x-r3)+c2)(x-r2)+c1)(x-r1)+c0

You can multiply it out if you want to check.

So in general, you can do:

```<code>poly = np.poly1d([c[n]])
for i in range(n,0,-1):
    poly = poly*np.poly1d([1,-r[n]])+np.poly1d([n-1])
</code>```

You can probably replace np.poly1d([c[n]]) with just c[n] and np.poly1d([c[n-1]]) with just c[n-1], if you're willing to trust the coercion to work properly

Body:
First, I'll rewrite the equation as

c3(x-r3)(x-r2)(x-r1)+c2(x-r2)(x-r1)+c1(x-r1)+c0

Next, note that this is equivalent to:

((c3(x-r3)+c2)(x-r2)+c1)(x-r1)+c0

You can multiply it out if you want to check.

So in general, you can do:

poly = np.poly1d([c[n]])
for i in range(n,0,-1):
    poly = poly*np.poly1d([1,-r[n]])+np.poly1d([n-1])

You can probably replace np.poly1d([c[n]]) with just c[n] and np.poly1d([c[n-1]]) with just c[n-1], if you're willing to trust the coercion to work properly


问:
JPA Date is output to wrong date/time when running on Weblogic server, but displays correctly when running locally embedded Tomcat
I have a spring boot application using spring data to retrieve data from an Oracle database.  When I run the code locally in embedded Tomcat, the date appears correctly.  However, the same code when deployed to Weblogic server gives a completely different date/time result.  I have confirmed that the timezone on the Weblogic server is the same as my local timezone (US/Eastern).

What is odd is that the minutes are being stripped out and always set to 00, and also the time difference between the correct date and the date displayed is unpredictable (one example is 16 hours behind, and with a different example, it's 19 hours)

jpa mapping:

```<code>import java.util.Date;
...
@Temporal(TemporalType.TIMESTAMP)
@Column(name = "INITIAL_CREATE_DATE")
private Date initialCreateDate;
</code>```

controller log statement:

```<code>SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy hh:mm z");
...
log.info("~~create date: " + medley.getInitialCreateDate() + " sdf " + sdf.format(medley.getInitialCreateDate()));
</code>```

output from Weblogic (WRONG):

```<code>~~create date: Thu Oct 26 20:00:00 EDT 2017 sdf 10/26/2017 08:00 EDT
</code>```

output from local Tomcat and spring data unit tests (CORRECT):

```<code>~~create date: 2017-10-27 11:57:53.0 sdf 10/27/2017 11:57 EDT
</code>```

Two things that stand out to me (besides the date/time being totally wrong)
1. The time is missing the minutes
2. The format is different on the .toString() output for the date

Any help or ideas how I can further troubleshoot this problem are very much appreciated!

答:
I figured my problem out - posting my answer, maybe it will help someone else.

My "medley" object was not retrieved directly from the database here.  It was retrieved by a job that then posted this medley object as JSON to this method here that outputs the date.  While I still don't understand the odd date/time behavior, at least now I know the fix.

My previous version of the code was using @Temporal(TemporalType.DATE)
and serializing json as this...

```<code>"initialCreateDate": "2017-10-27",
</code>```

which I don't understand why this was being converted to Thu Oct 26 20:00:00 - but at least I know that applying the @Temporal(TemporalType.TIMESTAMP) in my job fixed the problem. (i.e. updating the version of the repository code in pom.xml to the same version used by the service)

This is the correct serialization of the date/time:

```<code>"initialCreateDate":1509119873000
</code>```

Body:
I have a spring boot application using spring data to retrieve data from an Oracle database.  When I run the code locally in embedded Tomcat, the date appears correctly.  However, the same code when deployed to Weblogic server gives a completely different date/time result.  I have confirmed that the timezone on the Weblogic server is the same as my local timezone (US/Eastern).

What is odd is that the minutes are being stripped out and always set to 00, and also the time difference between the correct date and the date displayed is unpredictable (one example is 16 hours behind, and with a different example, it's 19 hours)

jpa mapping:

import java.util.Date;
...
@Temporal(TemporalType.TIMESTAMP)
@Column(name = "INITIAL_CREATE_DATE")
private Date initialCreateDate;

controller log statement:

SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy hh:mm z");
...
log.info("~~create date: " + medley.getInitialCreateDate() + " sdf " + sdf.format(medley.getInitialCreateDate()));

output from Weblogic (WRONG):

~~create date: Thu Oct 26 20:00:00 EDT 2017 sdf 10/26/2017 08:00 EDT

output from local Tomcat and spring data unit tests (CORRECT):

~~create date: 2017-10-27 11:57:53.0 sdf 10/27/2017 11:57 EDT

Two things that stand out to me (besides the date/time being totally wrong)
1. The time is missing the minutes
2. The format is different on the .toString() output for the date

Any help or ideas how I can further troubleshoot this problem are very much appreciated!

Body:
I figured my problem out - posting my answer, maybe it will help someone else.

My "medley" object was not retrieved directly from the database here.  It was retrieved by a job that then posted this medley object as JSON to this method here that outputs the date.  While I still don't understand the odd date/time behavior, at least now I know the fix.

My previous version of the code was using @Temporal(TemporalType.DATE)
and serializing json as this...

"initialCreateDate": "2017-10-27",

which I don't understand why this was being converted to Thu Oct 26 20:00:00 - but at least I know that applying the @Temporal(TemporalType.TIMESTAMP) in my job fixed the problem. (i.e. updating the version of the repository code in pom.xml to the same version used by the service)

This is the correct serialization of the date/time:

"initialCreateDate":1509119873000


问:
Open windows powershell when react is running
I have started learning react. I have installed and created a new todo-app. I am using windows 10.

In windows powershell how can I get the prompt back when the react is already running.

This is what I get in powershell -

```<code>Compiled successfully!

You can now view todoapp in the browser.

  Local:            http://localhost:3000/
  On Your Network:  http://192.168.0.34:3000/

Note that the development build is not optimized.
To create a production build, use npm run build.
</code>```

Do I need to open a separate cmd or is there any way to get back the command prompt in powershell while react is running.

Any help is highly appreciated.

答: After typing PowerShell in windows search hold shift while pressing enter to open a new instance of PowerShell

Body:
I have started learning react. I have installed and created a new todo-app. I am using windows 10.

In windows powershell how can I get the prompt back when the react is already running.

This is what I get in powershell -

Compiled successfully!

You can now view todoapp in the browser.

  Local:            http://localhost:3000/
  On Your Network:  http://192.168.0.34:3000/

Note that the development build is not optimized.
To create a production build, use npm run build.

Do I need to open a separate cmd or is there any way to get back the command prompt in powershell while react is running.

Any help is highly appreciated.


问:
Algorithm for accurate detection of overlap between a square and a circle?
I am implementing (in C++) a method to detect when an overlap is occurring between two static, axis-aligned shapes on a 2d plane. The shapes are either squares or circles, and therefore there are three cases I need to consider for overlap: square-square, circle-circle, and circle-square.

Square-square and circle-circle were simple enough, but I am struggling to find any solid information online about what the correct algorithm is for calculating square-circle overlap.

I am aware that I could embed the square inside a circle (or vice versa) as a rough method, but I'm interested in what would be considered the cleanest way to do this more precisely?

Researching it online suggests there is a 'correct' answer to this question, but it isn't made clear what exactly that answer is.

答:
Here's a simple and fast algorithm:

```<code>bool doesSquareCircleOverlap(float squareCenterX, float squareCenterY, float squareHalfSize, float circleCenterX, float circleCenterY, float circleRadius) {
    float x = fabs(circleCenterX - squareCenterX) - squareHalfSize;
    float y = fabs(circleCenterY - squareCenterY) - squareHalfSize;

    if (x>0) {
        if (y>0) {
            return x*x + y*y<circleRadius*circleRadius;
        } else {
            return x<circleRadius;
        }
    } else {
        return y<circleRadius;
    }
}
</code>```

Note that the square is represented by the center and half-size.

Basically, what it does is:

it removes symmetrical cases with fabs()

puts the corner into the origin

checks which area the center of circle is, to determine the closest point on the square from the circle. If this closes point is nearer than circleRadius, then there is an overlap.

Body:
Here's a simple and fast algorithm:

bool doesSquareCircleOverlap(float squareCenterX, float squareCenterY, float squareHalfSize, float circleCenterX, float circleCenterY, float circleRadius) {
    float x = fabs(circleCenterX - squareCenterX) - squareHalfSize;
    float y = fabs(circleCenterY - squareCenterY) - squareHalfSize;

    if (x>0) {
        if (y>0) {
            return x*x + y*y<circleRadius*circleRadius;
        } else {
            return x<circleRadius;
        }
    } else {
        return y<circleRadius;
    }
}

Note that the square is represented by the center and half-size.

Basically, what it does is:

it removes symmetrical cases with fabs()

puts the corner into the origin

checks which area the center of circle is, to determine the closest point on the square from the circle. If this closes point is nearer than circleRadius, then there is an overlap.


问:
Trying to get the value of dynamically created inputs, how would I get "this" value?
I'm trying to get the value out of each specific dynamically created divs input, but I'm having a hard time getting them. I want to get the input value for "this" specific input on my button click, but it's just giving me the first divs input value no matter what button I click. Any help would be greatly appreciated!</p>

```<code>    getGames().done(function(results){
        $.each(results, function (i, gameData){
            $.each(gameData, function(key, game){

                var gamesHome = game.home_team_conference;
                var gamesAway = game.away_team_conference;

                if(gamesHome == "Big 12" || gamesAway == "Big 12"){
                    // console.log(this);
                    var gameId = game.id;
                    var homeTeam = game.home_team;
                    var awayTeam = game.away_team;
                    var pointTotal = game.total_points_bet;
                    var gameTime = game.game_time_hour;
                    var gameDate = game.game_time_date;
                    var gameId = game.id;
                    var network = game.broadcast_network;
                    var hue = 'rgb(' + (Math.floor(Math.random() * 256)) + ',' + (Math.floor(Math.random() * 256)) + ',' + (Math.floor(Math.random() * 256)) + ')';
                    var hueTwo = 'rgb(' + (Math.floor(Math.random() * 256)) + ',' + (Math.floor(Math.random() * 256)) + ',' + (Math.floor(Math.random() * 256)) + ')';
                    var self = $(this);

                $('.wrapper').append('\
                    <div class="main-wrapper '+ gameId +' col-lg-6 col-md-6 col-sm-12">\
                    <div class="game-cards">\
                    <div class="chart-container">\
                    <canvas id="'+ homeTeam +'" width="500" height="500"></canvas>\
                    </div>\
                    <div class="right-info">\
                    <h4>' + awayTeam + '<br>' + " @ " + '<br>' + homeTeam +'</h4>\
                    <h5 id="time-channel">'+ gameDate +' @ ' + gameTime  + '<br>' + ' On ' + network +'</h5>\
                    <div class="total-points-live">\
                    <h5>Total Points Bet</h5>\
                    <h5 id="point-total">'+ pointTotal +'</h5>\
                    <p>'+ awayTeam +'</p>\
                    <input class="bet-input-away" data-team-type="'+ awayTeam +'" type="number" pattern="[0-9]*" name="betAmountAway" placeholder="Wager Amount">\
                    <p>'+ homeTeam +'</p>\
                    <input class="bet-input-home" data-team-type="'+ homeTeam +'" type="number" pattern="[0-9]*" name="betAmountHome" placeholder="Wager Amount">\
                    <p class="bet-button" gameid="'+ gameId +'">Click To Place Bet</p>\
                    </div>\
                    </div>\
                    </div>\
                    ');

                var ctx = document.getElementById(homeTeam).getContext('2d');

                var myChart = new Chart(ctx, {
                  type: 'doughnut',
                  data: {
                    labels: [homeTeam, awayTeam],
                    datasets: [{
                      backgroundColor: [
                        hue,
                        hueTwo,
                      ],
                      data: [200, 500]
                    , borderWidth: 0
                    }]
                  },
                  options: {
                        responsive: true
                    ,   maintainAspectRatio: true
                  }
                });

                // $('.bet-button').click(function(){
                //  if ($(this).hasClass('bet-button')){
                //  $(this).text('Place Bet');
                //  $(this).removeClass('bet-button').addClass('button-toggle');
                //  } else {
                //  $(this).removeClass('button-toggle').addClass('bet-button').text('Click To Place Bet');
                //  }
                // });

                }

            });

        });
    });
    $('.wrapper').on('click', '.bet-button', function() {
    var self = $(this);
    var gameId = self.attr('gameid');
    var awayVal = self.attr('.bet-input-away').val();
    var homeVal = self.attr('.bet-input-home').val();

    console.log(gameId);
    console.log(homeVal);
    console.log(awayVal);
    });
});
</code>```

答:
If you are trying to get the values of the inputs, you need to use val() on the inputs. But you are using attr of the main div. The way you are using attr is not correct. Also, it wil be much easier if you add the id for the game as a parent attribute of your main div. Try this:

```<code>$('.wrapper').append('\
                <div id="' + gameId + '" class="main-wrapper '+ gameId +' col-lg-6 col-md-6 col-sm-12">\
                <div class="game-cards">\
                <div class="chart-container">\
                <canvas id="'+ homeTeam +'" width="500" height="500"></canvas>\
                </div>\
                <div class="right-info">\
                <h4>' + awayTeam + '<br>' + " @ " + '<br>' + homeTeam +'</h4>\
                <h5 id="time-channel">'+ gameDate +' @ ' + gameTime  + '<br>' + ' On ' + network +'</h5>\
                <div class="total-points-live">\
                <h5>Total Points Bet</h5>\
                <h5 id="point-total">'+ pointTotal +'</h5>\
                <p>'+ awayTeam +'</p>\
                <input class="bet-input-away" data-team-type="'+ awayTeam +'" type="number" pattern="[0-9]*" name="betAmountAway" placeholder="Wager Amount">\
                <p>'+ homeTeam +'</p>\
                <input class="bet-input-home" data-team-type="'+ homeTeam +'" type="number" pattern="[0-9]*" name="betAmountHome" placeholder="Wager Amount">\
                <p class="bet-button" gameid="'+ gameId +'">Click To Place Bet</p>\
                </div>\
                </div>\
                </div>\
');

$('.wrapper').on('click', '.bet-button', function() {
    var self = $(this);
    var gameId = self.attr('gameid');
    var awayVal = $('#' + gameId + ' input[name=betAmountAway]');
    var homeVal = $('#' + gameId + ' input[name=betAmountHome]');
    console.log(gameId);
    console.log(homeVal);
    console.log(awayVal);
});
</code>```

Body:
I'm trying to get the value out of each specific dynamically created divs input, but I'm having a hard time getting them. I want to get the input value for "this" specific input on my button click, but it's just giving me the first divs input value no matter what button I click. Any help would be greatly appreciated!

    getGames().done(function(results){
        $.each(results, function (i, gameData){
            $.each(gameData, function(key, game){

                var gamesHome = game.home_team_conference;
                var gamesAway = game.away_team_conference;

                if(gamesHome == "Big 12" || gamesAway == "Big 12"){
                    // console.log(this);
                    var gameId = game.id;
                    var homeTeam = game.home_team;
                    var awayTeam = game.away_team;
                    var pointTotal = game.total_points_bet;
                    var gameTime = game.game_time_hour;
                    var gameDate = game.game_time_date;
                    var gameId = game.id;
                    var network = game.broadcast_network;
                    var hue = 'rgb(' + (Math.floor(Math.random() * 256)) + ',' + (Math.floor(Math.random() * 256)) + ',' + (Math.floor(Math.random() * 256)) + ')';
                    var hueTwo = 'rgb(' + (Math.floor(Math.random() * 256)) + ',' + (Math.floor(Math.random() * 256)) + ',' + (Math.floor(Math.random() * 256)) + ')';
                    var self = $(this);

                $('.wrapper').append('\

\

\

\
                    <canvas id="'+ homeTeam +'" width="500" height="500"></canvas>\

\

\

' + awayTeam + '
' + " @ " + '
' + homeTeam +'
\

'+ gameDate +' @ ' + gameTime  + '
' + ' On ' + network +'
\

\

Total Points Bet
\

'+ pointTotal +'
\

'+ awayTeam +'
\
                    <input class="bet-input-away" data-team-type="'+ awayTeam +'" type="number" pattern="[0-9]*" name="betAmountAway" placeholder="Wager Amount">\

'+ homeTeam +'
\
                    <input class="bet-input-home" data-team-type="'+ homeTeam +'" type="number" pattern="[0-9]*" name="betAmountHome" placeholder="Wager Amount">\

Click To Place Bet
\

\

\

\
                    ');

                var ctx = document.getElementById(homeTeam).getContext('2d');

                var myChart = new Chart(ctx, {
                  type: 'doughnut',
                  data: {
                    labels: [homeTeam, awayTeam],
                    datasets: [{
                      backgroundColor: [
                        hue,
                        hueTwo,
                      ],
                      data: [200, 500]
                    , borderWidth: 0
                    }]
                  },
                  options: {
                        responsive: true
                    ,   maintainAspectRatio: true
                  }
                });

                // $('.bet-button').click(function(){
                //  if ($(this).hasClass('bet-button')){
                //  $(this).text('Place Bet');
                //  $(this).removeClass('bet-button').addClass('button-toggle');
                //  } else {
                //  $(this).removeClass('button-toggle').addClass('bet-button').text('Click To Place Bet');
                //  }
                // });

                }

            });

        });
    });
    $('.wrapper').on('click', '.bet-button', function() {
    var self = $(this);
    var gameId = self.attr('gameid');
    var awayVal = self.attr('.bet-input-away').val();
    var homeVal = self.attr('.bet-input-home').val();

    console.log(gameId);
    console.log(homeVal);
    console.log(awayVal);
    });
});

Body:
If you are trying to get the values of the inputs, you need to use val() on the inputs. But you are using attr of the main div. The way you are using attr is not correct. Also, it wil be much easier if you add the id for the game as a parent attribute of your main div. Try this:

$('.wrapper').append('\
                <div id="' + gameId + '" class="main-wrapper '+ gameId +' col-lg-6 col-md-6 col-sm-12">\
                <div class="game-cards">\
                <div class="chart-container">\
                <canvas id="'+ homeTeam +'" width="500" height="500"></canvas>\
                </div>\
                <div class="right-info">\
                <h4>' + awayTeam + '<br>' + " @ " + '<br>' + homeTeam +'</h4>\
                <h5 id="time-channel">'+ gameDate +' @ ' + gameTime  + '<br>' + ' On ' + network +'</h5>\
                <div class="total-points-live">\
                <h5>Total Points Bet</h5>\
                <h5 id="point-total">'+ pointTotal +'</h5>\
                <p>'+ awayTeam +'</p>\
                <input class="bet-input-away" data-team-type="'+ awayTeam +'" type="number" pattern="[0-9]*" name="betAmountAway" placeholder="Wager Amount">\
                <p>'+ homeTeam +'</p>\
                <input class="bet-input-home" data-team-type="'+ homeTeam +'" type="number" pattern="[0-9]*" name="betAmountHome" placeholder="Wager Amount">\
                <p class="bet-button" gameid="'+ gameId +'">Click To Place Bet</p>\
                </div>\
                </div>\
                </div>\
');

$('.wrapper').on('click', '.bet-button', function() {
    var self = $(this);
    var gameId = self.attr('gameid');
    var awayVal = $('#' + gameId + ' input[name=betAmountAway]');
    var homeVal = $('#' + gameId + ' input[name=betAmountHome]');
    console.log(gameId);
    console.log(homeVal);
    console.log(awayVal);
});


问:
Javascript bugs in event handling
I am trying to write a script which fill data(after i run the code in chrome console) in the registration form of a website.

I want a function in pure javascript which exactly work like a jquery function. See the code

Javascript:

```<code>var lastName = document.getElementById('lastName');
var event = document.createEvent('HTMLEvents');
var event2 = document.createEvent('HTMLEvents');
  event.initEvent('focus', true,false);
  lastName.dispatchEvent(event);
  lastName.value = 'Khan';
  event2.initEvent('blur');
  lastName.dispatchEvent(event2);
</code>```

JQuery:

```<code>$('#lastName').focus();
$('#lastName').val("lastName");
$('#lastName').blur();
</code>```

The problem is that JavaScript actually does not focus the field, where jQuery focus the field.
So because of that when i try to submit the form it doesn't validate.

答:
You should be able to use lastName.focus() if you need the event.

https://developer.mozilla.org/en-US/docs/Web/Events/focus

Title: Javascript bugs in event handling

Body:
I am trying to write a script which fill data(after i run the code in chrome console) in the registration form of a website.

I want a function in pure javascript which exactly work like a jquery function. See the code

Javascript:

var lastName = document.getElementById('lastName');
var event = document.createEvent('HTMLEvents');
var event2 = document.createEvent('HTMLEvents');
  event.initEvent('focus', true,false);
  lastName.dispatchEvent(event);
  lastName.value = 'Khan';
  event2.initEvent('blur');
  lastName.dispatchEvent(event2);

JQuery:

$('#lastName').focus();
$('#lastName').val("lastName");
$('#lastName').blur();

The problem is that JavaScript actually does not focus the field, where jQuery focus the field.
So because of that when i try to submit the form it doesn't validate.


问:
Navigate to specific page after a given time of user inactivity
I'm trying to navigate or to show Home page component in React application after a given time period of user inactivity.

I have working automaticRefresh function which detects idle time by DOM events and reloads application after 2 minutes. Function is called in index.js file.

automaticRefresh

```<code>export default function () {
  let timer;

  window.onload = timerReset;
  document.onkeypress = timerReset;
  document.onmousemove = timerReset;
  document.onmousedown = timerReset;
  document.ontouchstart = timerReset;
  document.onclick = timerReset;
  document.onscroll = timerReset;
  document.onkeypress = timerReset;

  function timerElapsed() {
    window.location.reload();
    // Navigate or show Home page component
  };

  function timerReset() {
    clearTimeout(timer);
    timer = setTimeout(timerElapsed, 2 * 60 * 1000); // 2 mins
  }
}
</code>```

As you can see in timerElapsed function I set page reload and it's working fine, but I had a new task to change that could navigate to Home page.
Already in App container I have all my components logic which Statement or Home component to show.

App container

```<code>import React, { Component } from 'react';
// Components
import Header from './components/Header';
import Home from './components/Home';
import Statement from './components/Statement';

class App extends Component {
  render() {
    const statement = this.props.statement !== null;

    return (
      <div>
        <Header />

        { statement ? <Statement /> : <Home /> }
      </div>
    );
  }
}
</code>```

So how to show Home component after period of inactivity in React without Router?

答:
I posted a response but realized after that you don't want to use a router.  In which case, you do window.location = "http://yoururl.com".

This will only work if it's a real destination and not a react route.  If it is a react route you want to hit, you need a router.

Body:
I'm trying to navigate or to show Home page component in React application after a given time period of user inactivity.

I have working automaticRefresh function which detects idle time by DOM events and reloads application after 2 minutes. Function is called in index.js file.

automaticRefresh

export default function () {
  let timer;

  window.onload = timerReset;
  document.onkeypress = timerReset;
  document.onmousemove = timerReset;
  document.onmousedown = timerReset;
  document.ontouchstart = timerReset;
  document.onclick = timerReset;
  document.onscroll = timerReset;
  document.onkeypress = timerReset;

  function timerElapsed() {
    window.location.reload();
    // Navigate or show Home page component
  };

  function timerReset() {
    clearTimeout(timer);
    timer = setTimeout(timerElapsed, 2 * 60 * 1000); // 2 mins
  }
}

As you can see in timerElapsed function I set page reload and it's working fine, but I had a new task to change that could navigate to Home page.
Already in App container I have all my components logic which Statement or Home component to show.

App container

import React, { Component } from 'react';
// Components
import Header from './components/Header';
import Home from './components/Home';
import Statement from './components/Statement';

class App extends Component {
  render() {
    const statement = this.props.statement !== null;

    return (

        { statement ? <Statement /> : <Home /> }

    );
  }
}

So how to show Home component after period of inactivity in React without Router?


问:
How to toggle readonly state of check box in javascript
I understood that adding readonly attribute to check box does not make it readonly. Also adding disable attribute will not post the value.

On this SO post there are different options suggested to make the check box readonly.

However, i want to toggle the readonly state of the check box on some button click, and also post the value on form submit.

So as suggested i added "return false" on click event. Works fine. However how do i toggle this behavior?

```<code><button type="button" id="btn">Toggle</button>
<input type="checkbox" value="false" onClick="return false;" name="CheckBox1" />

$(document).ready(function() {

   $("#btn").click(function()
   {
      //how do i toggle readonly here
   })

});
</code>```

答:
One way to do it is to toggle a classname on the checkbox, then test for the presence of that classname when the user tries to change the checkbox state.

(You could use a data attribute instead, but this way has the added benefit of letting you give the user some visual cue that the input is readonly.)

$("#btn").on("click", function() {
  $('input[name="CheckBox1"]').toggleClass("readonly");
});

$('input[name="CheckBox1"]').on("click", function() {
  if ($(this).hasClass('readonly')) {return false}
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.readonly {
  opacity: 0.5;
}</code>```

<button type="button" id="btn">Toggle</button>
<input type="checkbox" value="false" name="CheckBox1" />```

Body:
I understood that adding readonly attribute to check box does not make it readonly. Also adding disable attribute will not post the value.

On this SO post there are different options suggested to make the check box readonly.

However, i want to toggle the readonly state of the check box on some button click, and also post the value on form submit.

So as suggested i added "return false" on click event. Works fine. However how do i toggle this behavior?

<button type="button" id="btn">Toggle</button>
<input type="checkbox" value="false" onClick="return false;" name="CheckBox1" />

$(document).ready(function() {

   $("#btn").click(function()
   {
      //how do i toggle readonly here
   })

});

Body:
One way to do it is to toggle a classname on the checkbox, then test for the presence of that classname when the user tries to change the checkbox state.

(You could use a data attribute instead, but this way has the added benefit of letting you give the user some visual cue that the input is readonly.)

$("#btn").on("click", function() {
  $('input[name="CheckBox1"]').toggleClass("readonly");
});

$('input[name="CheckBox1"]').on("click", function() {
  if ($(this).hasClass('readonly')) {return false}
});

.readonly {
  opacity: 0.5;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button type="button" id="btn">Toggle</button>
<input type="checkbox" value="false" name="CheckBox1" />


问:
how to get Session in javascript from ASP.NET MVC
I have some belows , please help me how i can get Session in Javascript code from Controller ?

```<code>public ActionResult Login(FormCollection f)
    {
        string sAcount = f["txtAccount"].ToString();
        string sPassword = f.Get("txtPassword").ToString();

        tblCustom cs = db.tblCustoms.SingleOrDefault(n=>n.Account==sAccount && n.Password==sPassword);

        if (cs != null)
        {

            Session["Account"] = cs;

            return View();

        }

        return View();

    }
</code>```

and JS code is

```<code>        <script >

       $('#btnSendMsg').click(function () {

                  var msg = $("#txtMessage").val();

                  alert('Hello' + Session["Account"] );
                 });

    <script/>
</code>```

the result is alert stil is not working, help me.

答:
Although this doesn't directly answer your question, the preferred approach is to create ViewModels while passing and retrieving parameters.

Create a LoginViewModel:

```<code>public class LoginViewModel {
   public tblCustoms Customs { get; set; }
   //other stuff you have, you might consider moving account and password here too,
   //instead of capturing with textbox names

   //public string Account { get; set; }
   //public string Password { get; set }
}
</code>```

Pass that instead to the view.

```<code>public ActionResult Login(FormCollection f)
{
    string sAcount = f["txtAccount"].ToString();
    string sPassword = f.Get("txtPassword").ToString();

    var cs = db.tblCustoms.SingleOrDefault(n=>n.Account==sAccount && n.Password==sPassword);

    if (cs != null)
    {
        Session["Account"] = cs;

        //return View(); you don't need this line
    }

    return View(new LoginViewModel() { Customs = cs });

}
</code>```

Add to top of your view:

```<code>@model YourNameSpace.LoginViewModel
</code>```

And in the javascript:

```<code><script>
   $('#btnSendMsg').click(function () {
        var msg = $("#txtMessage").val();
        alert('Hello ' + @Model.Customs );
    });
<script/>
</code>```

As an alternative to all of these, you can use ViewBag.
In the controller method, assign it to any name:

```<code>ViewBag.Customs = cs;
</code>```

Then call it in the view:

```<code>alert('Hello ' + @ViewBag.Customs );
</code>```

In order to use Session in your view, try this:

```<code>@Session["Account"].ToString();
</code>```

Body:
I have some belows , please help me how i can get Session in Javascript code from Controller ?

public ActionResult Login(FormCollection f)
    {
        string sAcount = f["txtAccount"].ToString();
        string sPassword = f.Get("txtPassword").ToString();

        tblCustom cs = db.tblCustoms.SingleOrDefault(n=>n.Account==sAccount && n.Password==sPassword);

        if (cs != null)
        {

            Session["Account"] = cs;

            return View();

        }

        return View();

    }

and JS code is

Body:
Although this doesn't directly answer your question, the preferred approach is to create ViewModels while passing and retrieving parameters.

Create a LoginViewModel:

public class LoginViewModel {
   public tblCustoms Customs { get; set; }
   //other stuff you have, you might consider moving account and password here too,
   //instead of capturing with textbox names

   //public string Account { get; set; }
   //public string Password { get; set }
}

Pass that instead to the view.

public ActionResult Login(FormCollection f)
{
    string sAcount = f["txtAccount"].ToString();
    string sPassword = f.Get("txtPassword").ToString();

    var cs = db.tblCustoms.SingleOrDefault(n=>n.Account==sAccount && n.Password==sPassword);

    if (cs != null)
    {
        Session["Account"] = cs;

        //return View(); you don't need this line
    }

    return View(new LoginViewModel() { Customs = cs });

}

Add to top of your view:

@model YourNameSpace.LoginViewModel

And in the javascript:

<script>
   $('#btnSendMsg').click(function () {
        var msg = $("#txtMessage").val();
        alert('Hello ' + @Model.Customs );
    });
<script/>

As an alternative to all of these, you can use ViewBag.
In the controller method, assign it to any name:

ViewBag.Customs = cs;

Then call it in the view:

alert('Hello ' + @ViewBag.Customs );

In order to use Session in your view, try this:

@Session["Account"].ToString();


问:
Python Remote Procedure Call (Without the Remote Part)
I have a Python server which is not running as root, which fronts an application I am developing. However there are some application features which require access to RAW sockets which means root privileges.

Obviously I do not want to run the main server as root, and so my solution is to create a daemon process or command line script which runs as root providing guarded access to said features.

However I want put aside stdin/stdout communication and use an RPC style of interaction such as Pyro. But this exposes the RPC interface to anyone with network access to the machine, whereas I know that the process calling the RPC methods will be another process on the same machine.

Is there not a sort of inter-process procedure call standard which could be used in a similar (local machine only) fashion? I imagine the server doing something like this:

```<code># Server not running as root
pythonically, returned, values = other_process_running_as_root.some_method()
</code>```

And the process running as root exposing a method:

```<code># Daemon running as root
@expose_this_method
def some_method():
    # Play with RAW sockets
    return pythonically, returned, values
</code>```

Is anything like this possible?

答:
This is an easy problem. You should be able to get what you want from any RPC mechanism that can use Unix sockets, or use regular TCP sockets but only accept connections from the loopback interface (listen on 127.0.0.1).

The multiprocessing library in the Python standard library supports local IPC, too. http://docs.python.org/library/multiprocessing.html#module-multiprocessing.connection

Body:
I have a Python server which is not running as root, which fronts an application I am developing. However there are some application features which require access to RAW sockets which means root privileges.

Obviously I do not want to run the main server as root, and so my solution is to create a daemon process or command line script which runs as root providing guarded access to said features.

However I want put aside stdin/stdout communication and use an RPC style of interaction such as Pyro. But this exposes the RPC interface to anyone with network access to the machine, whereas I know that the process calling the RPC methods will be another process on the same machine.

Is there not a sort of inter-process procedure call standard which could be used in a similar (local machine only) fashion? I imagine the server doing something like this:

# Server not running as root
pythonically, returned, values = other_process_running_as_root.some_method()

And the process running as root exposing a method:

# Daemon running as root
@expose_this_method
def some_method():
    # Play with RAW sockets
    return pythonically, returned, values

Is anything like this possible?

ContentLicense: CC BY-SA 2.5


问:
SQL UNION and MERGE
I'm having multiple select statements involving many tables and Joins. All the select statements have the same Headers. I'm trying to combine all this into a single result set. So which approach is better SQL UNION or MERGE?
I know UNION is A+B. So if a column is NULL in Table A and it has a value in TABLE B then UNION will give me two rows right? So if I want to combine all the rows into a single row based on the id should I use MERGE? I have an option to do this in SQL or SSIS.

```<code>SELECT ID, NAME, VitalName as VitalName FROM TABLE A
UNION
SELECT ID, NAME, VitalReadings as VitalName FROM TABLE B
</code>```

TableA

```<code>+----+------+-----------+
| ID | Name | VitalName |
+----+------+-----------+
|  1 | AAA  | HeartRate |
|  2 |      | Systolic  |
|  3 |      | Diastolic |
+----+------+-----------+
</code>```

TableB

```<code>+----+------+---------------+
| ID | Name | VitalReadings |
+----+------+---------------+
|  1 | AAA  | HeartRate     |
|  2 | BBB  | Systolic      |
+----+------+---------------+
</code>```

Expected Result

```<code>+----+------+---------------+
| ID | Name | VitalName     |
+----+------+---------------+
|  1 | AAA  | HeartRate     |
|  2 | BBB  | Systolic      |
|  3 |      | Diastolic     |
+----+------+---------------+
</code>```

答:
GROUP BY the UNION's result. Use MAX() to return the NAME:

```<code>select ID, MAX(NAME), VitalName
from
(
    SELECT ID, NAME, VitalName as VitalName FROM TABLE A
    UNION ALL
    SELECT ID, NAME, VitalReadings as VitalName FROM TABLE B
) dt
group by ID, VitalName
</code>```

Title: SQL UNION and MERGE

Body:
I'm having multiple select statements involving many tables and Joins. All the select statements have the same Headers. I'm trying to combine all this into a single result set. So which approach is better SQL UNION or MERGE?
I know UNION is A+B. So if a column is NULL in Table A and it has a value in TABLE B then UNION will give me two rows right? So if I want to combine all the rows into a single row based on the id should I use MERGE? I have an option to do this in SQL or SSIS.

SELECT ID, NAME, VitalName as VitalName FROM TABLE A
UNION
SELECT ID, NAME, VitalReadings as VitalName FROM TABLE B

TableA

+----+------+-----------+
| ID | Name | VitalName |
+----+------+-----------+
|  1 | AAA  | HeartRate |
|  2 |      | Systolic  |
|  3 |      | Diastolic |
+----+------+-----------+

TableB

+----+------+---------------+
| ID | Name | VitalReadings |
+----+------+---------------+
|  1 | AAA  | HeartRate     |
|  2 | BBB  | Systolic      |
+----+------+---------------+

Expected Result

+----+------+---------------+
| ID | Name | VitalName     |
+----+------+---------------+
|  1 | AAA  | HeartRate     |
|  2 | BBB  | Systolic      |
|  3 |      | Diastolic     |
+----+------+---------------+

Body:
GROUP BY the UNION's result. Use MAX() to return the NAME:

select ID, MAX(NAME), VitalName
from
(
    SELECT ID, NAME, VitalName as VitalName FROM TABLE A
    UNION ALL
    SELECT ID, NAME, VitalReadings as VitalName FROM TABLE B
) dt
group by ID, VitalName


问:
Lingo call to ActionScript not working
I have a Flash sprite in my Director project. Under the Properties of that sprite, under both the Member and the Sprite tabs, it has as its name "Assessment". In my Lingo script, I have the following call:

```<code>sprite("Assessment").displayGrade(75, 3, 4)
</code>```

where displayGrade is a function defined in the Flash object's ActionScript as a method taking 3 numbers as parameters. However, I get an error on this line, and cannot determine why. Am I calling the Flash object's method incorrectly?

答:
Try this:

set up a container-content reference to your swf,
that is the Flash main timeline:

```<code>global swfTL
on beginSprite me
swfTL = getvariable(sprite('yourFlashSprite'),'_level0',False)
end
</code>```

then call

swfTL.displayGrade(75, 3, 4)

Hope it helps.

OwnerDisplayName: Elie

Title: Lingo call to ActionScript not working

Body:
I have a Flash sprite in my Director project. Under the Properties of that sprite, under both the Member and the Sprite tabs, it has as its name "Assessment". In my Lingo script, I have the following call:

sprite("Assessment").displayGrade(75, 3, 4)

where displayGrade is a function defined in the Flash object's ActionScript as a method taking 3 numbers as parameters. However, I get an error on this line, and cannot determine why. Am I calling the Flash object's method incorrectly?

Body:
Try this:

set up a container-content reference to your swf,
that is the Flash main timeline:

global swfTL
on beginSprite me
swfTL = getvariable(sprite('yourFlashSprite'),'_level0',False)
end

then call

swfTL.displayGrade(75, 3, 4)

Hope it helps.

OwnerDisplayName: vyger


问:
How can I check if an object from one list is in another nested list?
say that I have a nested list like this for example:

```<code>List = [['a','d','b'],['a','x','w','t','d'],['g','c','d','z']]
</code>```

and what I want to do is find the object in the List that all the smaller lists share, so for the example List I gave 'd' would be the object they all share.

here is what I have done so far:

```<code>def related(List):
    for item in List[0]:
      for i in range(1, len(List)):
        if item in List[i]:
            return item
</code>```

the problem I am having is that when I do:

```<code>related([['a','d','b'],['a','x','w','t','d'],['g','c','d','z']])
</code>```

'a' is returned, but that isn't the correct answer since 'a' isn't in all the lists and only in the first 2 lists. The correct answer with that list should be 'd'.

My function basically just stops running once it finds the same object in just 1 of the lists.

Will someone be able to send me towards the right path on what I can do to get my code working correctly? Thank You!!!

答:
What you're looking for here is the intersection of these lists.  Python lists don't have an intersection functionality built-in, but sets do.  We can do

```<code>def in_common(l):
    if not l:
        return set()
    return set(l[0]).intersection(*l[1:])
</code>```

This converts the first element to a set, and then finds the intersection of that set with the rest of the elements in the list.

```<code>in_common([['a','d','b'],['a','x','w','t','d'],['g','c','d','z']])
</code>```

returns

```<code>{'d'}
</code>```

the set containing 'd'

Body:
say that I have a nested list like this for example:

List = [['a','d','b'],['a','x','w','t','d'],['g','c','d','z']]

and what I want to do is find the object in the List that all the smaller lists share, so for the example List I gave 'd' would be the object they all share.

here is what I have done so far:

def related(List):
    for item in List[0]:
      for i in range(1, len(List)):
        if item in List[i]:
            return item

the problem I am having is that when I do:

related([['a','d','b'],['a','x','w','t','d'],['g','c','d','z']])

'a' is returned, but that isn't the correct answer since 'a' isn't in all the lists and only in the first 2 lists. The correct answer with that list should be 'd'.

My function basically just stops running once it finds the same object in just 1 of the lists.

Will someone be able to send me towards the right path on what I can do to get my code working correctly? Thank You!!!

Body:
What you're looking for here is the intersection of these lists.  Python lists don't have an intersection functionality built-in, but sets do.  We can do

def in_common(l):
    if not l:
        return set()
    return set(l[0]).intersection(*l[1:])

This converts the first element to a set, and then finds the intersection of that set with the rest of the elements in the list.

in_common([['a','d','b'],['a','x','w','t','d'],['g','c','d','z']])

returns

{'d'}

the set containing 'd'


答:
Finally! Got the code running to give me what I want!

```<code>expected_list = []

for b1, b2 in enumerate(list1):
    for l1, l2 in enumerate(list2):
        replace = None
        bp1 = list1[b1][0]
        bp2 = list1[b1][1]
        lp1 = list2[l1][0]
        lp2 = list2[l1][1]
        d = numpy.sqrt((bp1 - lp1) * (bp1 - lp1) + (bp2 - lp2) * (bp2 - lp2))
        if(len(expected_list) == 0 ):
            expected_list.append((int(list2[l1][2]), int(list1[b1][2]), d))
        else:
            for d1, d2 in enumerate(expected_list):
                if (expected_list[d1][0] == int(list2[l1][2]) and expected_list[d1][1] == int(list1[b1][2])):
                    min_distance = min(expected_list[d1][2],d)
                    replace = d1

            if (replace == None):
                expected_list.append((int(list2[l1][2]), int(list1[b1][2]), d))
            else:
                expected_list[replace] = (int(list2[l1][2]), int(list1[b1][2]), min_distance)

print(expected_list)
</code>```

If anybody can help me optimize the code, I will be grateful :)

Title: Replace a list of tuples based on condition

Body:
My program has two lists
List 1 [(x-coordinate,y-coordinate,List1_id)] (list of tuples)
List 2 [(x-coordinate,y-coordinate,List2_id)] (list of tuples)

So, now I have a code that runs to compute the distance between all the points in List 1 and List 2. So, my resulting list is
ResultList = [(List1_id, List2_id, distance)]

Since the dataset is too big, my ResultList is about 4gb long. I don't need all the distances. I need only minimum distance of a given combination of list ids

So, my resulting list should be
[(List1_id1, List2_id1, min_distance),(List1_id1, List1_id2, min_distance),(List1_id2, List2_id1, min_distance) and so on..]

from

[(List1_id1, List2_id1, distance),(List1_id1, List1_id2, distance),(List1_id2, List2_id1, distance), (List1_id1, List2_id1, distance), (List1_id1, List2_id1, distance), (List1_id1, List1_id2, distance) and so on..]

I hope this makes sense :|

So, currently, I calculate the distance and append to a new list. I need to apply a logic that when I append to the list, the new element must be added only if the distance is minimum for any combination of list IDs. This will make sure that my list is not GBs long

Edit 2 - Some data
List 1 - [(99363.044,441277.027,8),(99373.343,441272.8,8),(99354.918,441288.428,8),(99362.324,441291.766,8),(99360.426,441264.083,8),(99369.039,441287.165,5),(99364.127,441288.681,5)]

List 2 - [(99360.05,441264.68,42,0),(99360.05,441264.69,42,0),(99360.05,441264.7,42,0),(99360.15,441264.58,42,0),(99360.15,441264.62,42,0),(99361.26,441279.93,53,0),(99361.26,441280.14,53,0),(99361.26,441279.9,53,0),(99361.26,441279.81,53,0),(99354.55,441271.69,63,0),(99354.55,441275.66,63,0),(99354.55,441271.66,63,0),(99354.55,441275.64,63,0),(99354.55,441275.48,63,0),(99354.55,441270.59,63,0),(99354.55,441275.44,63,0),(99354.55,441271.06,63,0),(99354.55,441272.84,63,0),(99355.32,441273.42,63,0),(99355.32,441275.26,63,0),(99355.32,441274.48,63,0),(99355.32,441274.95,63,0),(99358.02,441284.35,68,0),(99358.02,441284.36,68,0),(99358.02,441284.4,68,0),(99358.02,441284.49,68,0),(99358.02,441283.97,68,0),(99358.16,441284.34,68,0),(99358.16,441284.36,68,0),(99358.16,441284,68,0)]

Obtained result
[(42, 5, 24.334954489354597), (42, 5, 24.387460917433867), (63, 5, 16.052616297632952), (42, 8, 12.74005043161773), (42, 8, 24.286417356220991), (42, 8, 0.56849362356923416), (42, 8, 24.276643260552106), (63, 8, 9.5884464330723027), (53, 8, 16.078644376965897), (42, 5, 24.196659810778854), (68, 5, 7.3672335377565004), (63, 8, 8.6337271789140431), (68, 8, 8.5137754257193521), (63, 5, 17.619914017943259), (42, 5, 24.27131117180317), (42, 5, 24.426926331373604), (63, 5, 22.01503454456742), (63, 8, 12.79329386827386), (68, 8, 8.8889518504529388), (53, 8, 14.029817853416182), (63, 8, 18.977524838601038), (53, 8, 10.700041495254004), (63, 8, 10.641936149028002), (68, 8, 20.383346266049983), (63, 8, 12.965015426166449), (42, 8, 12.695101614399849), (68, 5, 11.239807204741309), (68, 8, 8.5700539671281586), (63, 8, 10.047523326678597), (53, 8, 11.913607849829605), (53, 8, 3.5879555460002752), (42, 8, 27.161359170695093), (63, 8, 18.21630785860641), (68, 8, 20.40322241706173), (68, 5, 11.339046961713443), (53, 8, 3.4073545456772449), (63, 8, 21.556583959454493), (42, 8, 27.232913762585632), (63, 5, 18.684758119918691), (53, 8, 15.86893080835191), (63, 8, 17.930534069001059), (42, 5, 24.234094701462343), (42, 5, 24.344813205268306), (42, 8, 0.72254065632100728), (42, 8, 0.71402030785190995), (63, 8, 18.08240448612629), (63, 8, 17.902037649371213), (68, 8, 5.4310374699841022), (68, 8, 5.0840129818797895), (53, 8, 13.969215761813532), (63, 8, 8.6032973329956892), (68, 8, 8.8105814223397942), (68, 8, 8.4536732844420808), (63, 8, 18.827544954127116), (53, 8, 14.014595570349684), (68, 8, 20.45896686056269), (63, 5, 16.710225911093556), (63, 8, 18.0336609982418), (68, 8, 8.9051688361531518), (68, 8, 19.194476523198581), (63, 8, 9.1217270842880183), (42, 8, 15.571639252163617), (63, 5, 18.613713922803964), (63, 8, 19.637508294091823), (63, 5, 18.513690771945917), (68, 5, 11.360615564297584), (53, 8, 10.62768780119729), (42, 5, 24.215229629293152), (68, 8, 8.8807040824213157), (68, 8, 5.1237181811943104), (53, 5, 10.623467701270917), (63, 8, 18.922498487236851), (42, 8, 27.181289005499924), (53, 5, 9.3227855279266194), (68, 8, 8.8119039940279258), (68, 5, 7.7129093084233054), (68, 8, 20.045489392894488), (53, 8, 10.436086814504577), (63, 8, 15.592343249160891), (53, 5, 9.2086747146265946), (68, 8, 20.419244966454769), (63, 8, 10.657532782006815), (53, 8, 3.3818316043413272), (42, 8, 12.779007981828714), (53, 8, 11.883728034595848), (53, 8, 11.67458658795881), (68, 8, 8.5744662807839234), (63, 5, 20.055387555449311), (63, 8, 10.031530541240986), (68, 8, 5.1157626997569583), (63, 8, 22.557882258733933), (63, 5, 20.374904809561844), (68, 5, 11.234797105421109), (63, 5, 16.309056686388619), (68, 8, 19.082900434672979), (42, 8, 27.171324075208528), (63, 5, 18.50124714715599), (53, 5, 9.237188425017159), (63, 8, 12.95322847790688), (63, 5, 16.31268248936852), (63, 5, 18.368919020974811), (63, 8, 17.371898226750695), (68, 8, 19.0707915147892), (42, 8, 24.296191635748073), (63, 8, 18.983130642747213), (53, 5, 10.481577457599492), (68, 5, 11.472854309196546), (42, 8, 15.523132705735247), (68, 8, 8.9964962624199476), (63, 5, 16.341450669976716), (68, 5, 7.4580433090399447), (68, 8, 19.273049291685261), (68, 8, 20.409314662665938), (63, 8, 9.4698999466550209), (63, 8, 15.01338296324063), (63, 8, 8.6064978359273443), (63, 8, 12.982846567676086), (68, 8, 8.9219787603546088), (63, 5, 18.164250218470507), (42, 8, 12.685383912192332), (63, 5, 20.46956789964668), (68, 8, 20.548345067189207), (68, 5, 7.4067489494241725), (63, 8, 8.5247067398202496), (63, 5, 19.504179295708195), (42, 8, 15.544248100166255), (68, 8, 5.4879639211748898), (53, 8, 12.003250892992714), (68, 8, 8.5132946031419188), (68, 8, 8.5658188166784157), (68, 8, 5.2018446728271828), (42, 8, 15.576849777784778), (42, 8, 24.376108959405205), (42, 8, 0.60377562059008572), (63, 8, 22.117267281472209), (63, 8, 11.583127600088826), (68, 8, 8.4963363869476058), (53, 8, 15.749097910686972), (68, 5, 11.370417142742211), (63, 8, 8.640984029603004), (68, 8, 5.2175001676950679), (63, 5, 21.221124993745853), (63, 8, 7.9235386665163343), (42, 8, 27.272786289620047), (63, 8, 13.953791886111953), (63, 8, 18.19011074731587), (63, 8, 17.884023932012049), (63, 8, 20.46041426753143), (63, 8, 18.101130600034072), (68, 5, 7.3789816370214911), (63, 8, 10.545730178644387), (63, 8, 18.793042568984102), (68, 5, 11.372888199574382), (63, 8, 12.288065958504605), (63, 5, 21.663382607511704), (63, 8, 21.52860543555683), (68, 5, 11.330042630100078), (63, 8, 10.380420270870811), (68, 8, 19.188455617881456), (63, 8, 17.841795537434088), (42, 8, 12.704819754729604), (63, 8, 12.773302157274143), (63, 8, 16.742044916927171), (63, 8, 13.174134810306763), (63, 5, 19.530319249824927), (63, 8, 12.787056932713549), (68, 8, 20.032014501780179), (53, 8, 10.603629944515824), (53, 5, 10.705553045026424), (42, 8, 24.41517822994124), (53, 8, 3.3057139924644763), (63, 8, 8.7674640005297135), (42, 5, 24.325095888783526), (63, 8, 18.825752282435211), (68, 8, 18.866994699738399), (63, 8, 18.873379374124106), (63, 5, 18.638850447371869), (42, 5, 24.205944435179109), (42, 8, 15.566433406511978), (68, 5, 7.5839864187451367), (63, 8, 19.006379165948232), (68, 8, 5.0130078795250803), (63, 8, 18.651053911255637), (63, 8, 8.1331042658944277), (68, 8, 8.793942517452491), (63, 8, 16.77203768184846), (53, 5, 10.643921551735795), (42, 8, 0.70553880121043167), (63, 8, 18.046298013735743), (53, 5, 9.0093490330572585), (63, 8, 9.6121706705780792), (68, 5, 7.4810754574348568), (63, 5, 19.419989340877574), (68, 8, 18.96215254129423), (63, 8, 12.993212381867547), (63, 8, 12.82259665590326), (63, 5, 16.163705330153071), (63, 5, 16.179821074381103), (68, 5, 7.4868558153549847), (63, 8, 7.9983813987434456), (68, 8, 8.5312585237825154), (53, 8, 14.13769744337263), (63, 8, 12.006786622597852), (63, 5, 18.510975392951089), (68, 8, 19.218593314821081), (53, 8, 15.838972346753351), (63, 8, 18.150785905839268), (63, 5, 21.19921569302317), (63, 8, 19.009377922477256), (63, 8, 13.483993770395951)]

Expected result
[(42, 5, 24.334954489354597),(63, 5, 16.052616297632952), (42, 8, 12.74005043161773),(63, 8, 9.5884464330723027), (53, 8, 16.078644376965897),(68, 8, 8.5137754257193521),(53, 5, 10.623467701270917),(68, 5, 7.3672335377565004)]

Of course in the expected result, the values don't reflect the true minimum but they should be from the obtained result. I hope you get what I mean

Body:
Finally! Got the code running to give me what I want!

expected_list = []

for b1, b2 in enumerate(list1):
    for l1, l2 in enumerate(list2):
        replace = None
        bp1 = list1[b1][0]
        bp2 = list1[b1][1]
        lp1 = list2[l1][0]
        lp2 = list2[l1][1]
        d = numpy.sqrt((bp1 - lp1) * (bp1 - lp1) + (bp2 - lp2) * (bp2 - lp2))
        if(len(expected_list) == 0 ):
            expected_list.append((int(list2[l1][2]), int(list1[b1][2]), d))
        else:
            for d1, d2 in enumerate(expected_list):
                if (expected_list[d1][0] == int(list2[l1][2]) and expected_list[d1][1] == int(list1[b1][2])):
                    min_distance = min(expected_list[d1][2],d)
                    replace = d1

            if (replace == None):
                expected_list.append((int(list2[l1][2]), int(list1[b1][2]), d))
            else:
                expected_list[replace] = (int(list2[l1][2]), int(list1[b1][2]), min_distance)

print(expected_list)

If anybody can help me optimize the code, I will be grateful :)


问:
how do i count no of dates from weeks on the given date list
I want to find the number of dates from 1st week, 2nd week, 3 rd week and 4th week from the given dates list</p>

```<code>[2017-11-22 21:41:39.0, 2017-11-27 23:15:26.0, 2017-11-27 23:26:23.0,
 2017-11-28 19:50:18.0, 2017-11-29 16:14:33.0] are dates

//By Using map
Map<Integer, List<Date>> map;
map = inboxOutboxentityList.stream()
    .collect(Collectors.groupingBy(element ->
         element.getDate().get(weekFields.weekOfWeekBasedYear())
    )
);
</code>```

答:
If you can, just forget about the long outdated Date class and solve your problem in pure java.time. Your code is not far from working.

```<code>    List<LocalDateTime> entities = Arrays.asList(
            LocalDateTime.of(2017, Month.NOVEMBER, 22, 21, 41, 39),
            LocalDateTime.of(2017, Month.NOVEMBER, 27, 23, 15, 26),
            LocalDateTime.of(2017, Month.NOVEMBER, 27, 23, 26, 23),
            LocalDateTime.of(2017, Month.NOVEMBER, 28, 19, 50, 18),
            LocalDateTime.of(2017, Month.NOVEMBER, 29, 16, 14, 33));
    Map<Integer, Long> countPerWeek = entities.stream()
            .collect(Collectors.groupingBy(
                    ldt -> ldt.get(WeekFields.ISO.weekOfWeekBasedYear()),
                    Collectors.counting()));
    System.out.println(countPerWeek);
</code>```

This prints:

```<code>{48=4, 47=1}
</code>```

So the count is 1 for week 47 and 4 for week 48. I believe this was what you intended. Please substitute a different WeekFields object if required.

If you are getting a list of Date objects, you will need to convert them into some modern class first. There are plenty of questions and answers about how to do that, happy searcing. As you have probably already realized, you can do it in the same series of stream operations.

Body:
I want to find the number of dates from 1st week, 2nd week, 3 rd week and 4th week from the given dates list

[2017-11-22 21:41:39.0, 2017-11-27 23:15:26.0, 2017-11-27 23:26:23.0,
 2017-11-28 19:50:18.0, 2017-11-29 16:14:33.0] are dates

//By Using map
Map<Integer, List<Date>> map;
map = inboxOutboxentityList.stream()
    .collect(Collectors.groupingBy(element ->
         element.getDate().get(weekFields.weekOfWeekBasedYear())
    )
);

Body:
If you can, just forget about the long outdated Date class and solve your problem in pure java.time. Your code is not far from working.

    List<LocalDateTime> entities = Arrays.asList(
            LocalDateTime.of(2017, Month.NOVEMBER, 22, 21, 41, 39),
            LocalDateTime.of(2017, Month.NOVEMBER, 27, 23, 15, 26),
            LocalDateTime.of(2017, Month.NOVEMBER, 27, 23, 26, 23),
            LocalDateTime.of(2017, Month.NOVEMBER, 28, 19, 50, 18),
            LocalDateTime.of(2017, Month.NOVEMBER, 29, 16, 14, 33));
    Map<Integer, Long> countPerWeek = entities.stream()
            .collect(Collectors.groupingBy(
                    ldt -> ldt.get(WeekFields.ISO.weekOfWeekBasedYear()),
                    Collectors.counting()));
    System.out.println(countPerWeek);

This prints:

{48=4, 47=1}

So the count is 1 for week 47 and 4 for week 48. I believe this was what you intended. Please substitute a different WeekFields object if required.

If you are getting a list of Date objects, you will need to convert them into some modern class first. There are plenty of questions and answers about how to do that, happy searcing. As you have probably already realized, you can do it in the same series of stream operations.


问:
Capture successful prestashop order in google analytics
I use Prestashop V1.6.1.11, and PayU payment module. I have configured the Google Analytics module.
Currently the successful order is not captured in analytics.
I think this is because the payment module, on successful payment is redirecting to order-detail page when logged in or guest-tracking page for guest users instead of order-confirmation page.
In the goal url's of Google Analytics I have added /order-detail and /guest-tracking as goals but it doesn't help.
Is there a way to capture order confirmation in this case?

Thanks for your help.

答:
You could add the code manually to send an event to Google Analytics on your /order-detail, /order-detail and /guest-tracking pages and then use that event to trigger your successful order goal.

For example:

```<code>ga('send', 'event', 'Order', 'Successful');
</code>```

Body:
You could add the code manually to send an event to Google Analytics on your /order-detail, /order-detail and /guest-tracking pages and then use that event to trigger your successful order goal.

For example:

ga('send', 'event', 'Order', 'Successful');


问:
Getting zero when calculating percentage of two buttons pressed
I've two buttons one is light side button and other is called dark side button. When any of the button is pressed do this:

```<code>    lightSideInt = lightSideInt! + 1
    totalClicks = totalClicks!+1

    let lightPercent = (lightSideInt!/totalClicks!) * 100
    let darkPercent = (darkSideInt!/totalClicks!) * 100

    darkSideButton.setTitle("\(darkPercent)%",for: .normal)
    lightSideButton.setTitle("\(lightPercent)%",for: .normal)
</code>```

And same for the dark button except for the darkSideInt = darkSideInt! + 1 everything is same. darkSideInt, lightSideInt & totalClicks are global variables.

Now what happens is that when I press the button for the first time it give one button title 100% and the other 0% and after that use has to dismiss the screen and then come on this screen again. So this time as the variables are global they already have the value so when I press the button I can see the increment is happening successfully but the button title is 0% and no matter how many times I press the button it remains the same.

These are the global variables:

```<code>var darkSideInt: Int?
var lightSideInt: Int?
var totalClicks: Int?
</code>```

答:
When applying the / operator to two Ints, the result will be of type Int as well, hence your issue. You need to convert both variables to Double before applying the division.

```<code>let lightPercent = Int(Double(lightSideInt)/Double(totalClicks) * 100)
let darkPercent = Int(Double(darkSideInt)/Double(totalClicks) * 100)

darkSideButton.setTitle("\(darkPercent)%",for: .normal)
lightSideButton.setTitle("\(lightPercent)%",for: .normal)
</code>```

It doesn't make sense to define lightSideInt and darkSideInt as optionals if you are going to force unwrap the value assigned to them. Just define them as non-Optionals and then you can get rid of the force unwraps in the percentage calculations.

Body:
I've two buttons one is light side button and other is called dark side button. When any of the button is pressed do this:

    lightSideInt = lightSideInt! + 1
    totalClicks = totalClicks!+1

    let lightPercent = (lightSideInt!/totalClicks!) * 100
    let darkPercent = (darkSideInt!/totalClicks!) * 100

    darkSideButton.setTitle("\(darkPercent)%",for: .normal)
    lightSideButton.setTitle("\(lightPercent)%",for: .normal)

And same for the dark button except for the darkSideInt = darkSideInt! + 1 everything is same. darkSideInt, lightSideInt & totalClicks are global variables.

Now what happens is that when I press the button for the first time it give one button title 100% and the other 0% and after that use has to dismiss the screen and then come on this screen again. So this time as the variables are global they already have the value so when I press the button I can see the increment is happening successfully but the button title is 0% and no matter how many times I press the button it remains the same.

These are the global variables:

var darkSideInt: Int?
var lightSideInt: Int?
var totalClicks: Int?

Body:
When applying the / operator to two Ints, the result will be of type Int as well, hence your issue. You need to convert both variables to Double before applying the division.

let lightPercent = Int(Double(lightSideInt)/Double(totalClicks) * 100)
let darkPercent = Int(Double(darkSideInt)/Double(totalClicks) * 100)

darkSideButton.setTitle("\(darkPercent)%",for: .normal)
lightSideButton.setTitle("\(lightPercent)%",for: .normal)

It doesn't make sense to define lightSideInt and darkSideInt as optionals if you are going to force unwrap the value assigned to them. Just define them as non-Optionals and then you can get rid of the force unwraps in the percentage calculations.


问:
IEnumerable from IEnumerator
I have writen about custom IEnumerator. Whats the simplest way to make IEnumerable from it ? Ideal solution (one line of code) would be if there was some class for that purpose. Or do I have to create my own ?

答:
I would really approach this the other way around; while you can (as per Mike P's excellent answer) wrap an enumerator to pretend to be enumerable, there are some things that you can't really do - for example, it is hoped (although, to be fair, not insisted) that you can obtain multiple enumerators from an enumerable, ideally isolated and repeatable. So if I do:

```<code>Assert.AreEqual(sequence.Sum(), sequence.Sum());
</code>```

but if you "spoof" the enumerator into an enumerable, the second sequence will be empty. Or if you do them in parallel - just bizarre. And there are methods that process them in parallel - consider:

```<code>Assert.IsTrue(sequence.SequenceEqual(sequence));
</code>```

this works both enumerators forward at the same time, so if you only have one enumerator, you are fairly scuppered.

There is a reset on enumerators, but this is largely a design mistake and shouldn't be used (it is even a formal requirement in the spec that iterator blocks throw an exception if you call it).

A better (IMO) question is "how do I get an enumerator from an enumerable", in which case the answer is "call GetEnumerator(), and remember to check to dispose to iterator" - or in simpler terms "use foreach".

Title: IEnumerable from IEnumerator

Body:
I would really approach this the other way around; while you can (as per Mike P's excellent answer) wrap an enumerator to pretend to be enumerable, there are some things that you can't really do - for example, it is hoped (although, to be fair, not insisted) that you can obtain multiple enumerators from an enumerable, ideally isolated and repeatable. So if I do:

Assert.AreEqual(sequence.Sum(), sequence.Sum());

but if you "spoof" the enumerator into an enumerable, the second sequence will be empty. Or if you do them in parallel - just bizarre. And there are methods that process them in parallel - consider:

Assert.IsTrue(sequence.SequenceEqual(sequence));

this works both enumerators forward at the same time, so if you only have one enumerator, you are fairly scuppered.

There is a reset on enumerators, but this is largely a design mistake and shouldn't be used (it is even a formal requirement in the spec that iterator blocks throw an exception if you call it).

A better (IMO) question is "how do I get an enumerator from an enumerable", in which case the answer is "call GetEnumerator(), and remember to check to dispose to iterator" - or in simpler terms "use foreach".


问:
Attempting to remove "www" and force "https" on domain and trying to make it do both
```<code>RewriteEngine On
    #Remove www
    RewriteCond %{HTTP_HOST} ^www\.(.+)
    RewriteCond %{HTTPS}s/%1 ^(on(s)|offs)/(.+)
    RewriteRule ^ http%2://%3%{REQUEST_URI} [L,R=301]
    #force https
    RewriteCond %{HTTPS} off
    RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
    #ignore folder for removing slash & removing .html
    RewriteRule ^(whmcs) - [L]
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule ^(.*)/$ /$1 [L,R]
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteRule ^([^\.]+)$ $1.html [NC,L]
</code>```

So this is my current code. Here is my results:

website.com --> https://website.com

http://website.com --> https://website.com

www.website.com --> https://website.com

http://www.website.com --> https://website.com

All good except...

https://www.website.com --> https://www.website.com <--No good.

I have been researching and attempting to rewrite this to no success. Please any help and if you would be so kind to leave documentation so I could read further. Either way I need a solution. Thank you!

答:
I had the same issue before, here is how i fixed it.</p>

```<code>### WWW & HTTPS

#Remove WWW
RewriteEngine on
RewriteCond %{HTTP_HOST} ^www\.(.*)$ [NC]
RewriteRule ^(.*)$ http://%1%{REQUEST_URI} [R=301,QSA,NC,L]

# ensure https
RewriteCond %{HTTP:X-Forwarded-Proto} !https
RewriteCond %{HTTPS} off
RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

### WWW & HTTPS
</code>```

Body:
RewriteEngine On
    #Remove www
    RewriteCond %{HTTP_HOST} ^www\.(.+)
    RewriteCond %{HTTPS}s/%1 ^(on(s)|offs)/(.+)
    RewriteRule ^ http%2://%3%{REQUEST_URI} [L,R=301]
    #force https
    RewriteCond %{HTTPS} off
    RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
    #ignore folder for removing slash & removing .html
    RewriteRule ^(whmcs) - [L]
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule ^(.*)/$ /$1 [L,R]
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteRule ^([^\.]+)$ $1.html [NC,L]

So this is my current code. Here is my results:

website.com --> https://website.com

http://website.com --> https://website.com

www.website.com --> https://website.com

http://www.website.com --> https://website.com

All good except...

https://www.website.com --> https://www.website.com <--No good.

I have been researching and attempting to rewrite this to no success. Please any help and if you would be so kind to leave documentation so I could read further. Either way I need a solution. Thank you!

Body:
I had the same issue before, here is how i fixed it.

### WWW & HTTPS

#Remove WWW
RewriteEngine on
RewriteCond %{HTTP_HOST} ^www\.(.*)$ [NC]
RewriteRule ^(.*)$ http://%1%{REQUEST_URI} [R=301,QSA,NC,L]

# ensure https
RewriteCond %{HTTP:X-Forwarded-Proto} !https
RewriteCond %{HTTPS} off
RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

### WWW & HTTPS


问:
From FBSDKGraphRequest to Storyboard
i'm total beginner in coding, but i have a big question :)

I dont know how to get information to display on Main Storyboard form FBSDKGraphRequest.

What i should do next to get picture to Storyboard? I hope someone can help me :)

Using Swift 3, Xcode 8

Facebook login is working and code is:

```<code>    func getFBUserData(){
    if((FBSDKAccessToken.current()) != nil){
        FBSDKGraphRequest(graphPath: "me", parameters: ["fields": "id, name, first_name, last_name, picture.type(large), email"]).start(completionHandler: { (connection, result, error) -> Void in
            if (error == nil){
                self.dict = result as? [String : AnyObject]
                print(result!)
                print(self.dict)
            }
        })
    }
</code>```

答:
I see it as four steps -- my apologies to you if you already know some of this.

Drag an UIImageView from the object library in interface builder to a view in your storyboard.

Connect the UIImageView to your code as an IBOutlet and name it. Do this by control dragging from your new UIImageView to your code, and then in the popup specify an outlet and name the UIImageView. In my case I named it 'facebookPicture'

Get the URL for the image from the FaceBook result. The following sample code drills down into the result dictionary step by step. There are many ways to shorten this.

```<code>@IBOutlet var facebookPicture: UIImageView!

func getFBUserID(){
 if((FBSDKAccessToken.current()) != nil) {
    FBSDKGraphRequest(graphPath: "me", parameters: ["fields": "id, name, first_name, last_name, picture.type(large), email"]).start(
        completionHandler: {
            [weak self] (connection, result, error) -> Void in
            guard let strongSelf = self else { return }
            if let error = error {
                print("Failed to download FB user with error:. \(error)")
            }
            if (error == nil) {
                let resultDictSwift = result as! Dictionary<String, Any>
                if let picture = resultDictSwift["picture"] as? Dictionary<String, Any> {
                    if let pictureData = picture["data"] as? Dictionary<String, Any> {
                        if let pictureURL = NSURL(string: (pictureData["url"] as? String)! ) {
                            strongSelf.downloadImage(url: pictureURL as URL)
                        }
                    }
                }
                print(result!)
                let FBID = resultDictSwift["id"]
                strongSelf.facebookID = FBID as! String?
                print("User FB id: \(strongSelf.facebookID!)")
            }
        })
    }
}
</code>```

Download the image from the URL location. The following does this asynchronously and uses a previous stack overflow answer here When the download is complete, it sets the result of the download to be the image in your UIImageView

```<code>func getDataFromUrl(url: URL, completion: @escaping (Data?, URLResponse?, Error?) -> ()) {
URLSession.shared.dataTask(with: url) { data, response, error in
    completion(data, response, error)
    }.resume()
}

func downloadImage(url: URL) {
    print("Download Started")
    getDataFromUrl(url: url) { data, response, error in
    guard let data = data, error == nil else { return }
    print(response?.suggestedFilename ?? url.lastPathComponent)
    print("Download Finished")
    DispatchQueue.main.async() {
        self.facebookPicture.image = UIImage(data: data)
    }
   }
 }
</code>```

I hope this helps!

Title: From FBSDKGraphRequest to Storyboard

Body:
i'm total beginner in coding, but i have a big question :)

I dont know how to get information to display on Main Storyboard form FBSDKGraphRequest.

What i should do next to get picture to Storyboard? I hope someone can help me :)

Using Swift 3, Xcode 8

Facebook login is working and code is:

    func getFBUserData(){
    if((FBSDKAccessToken.current()) != nil){
        FBSDKGraphRequest(graphPath: "me", parameters: ["fields": "id, name, first_name, last_name, picture.type(large), email"]).start(completionHandler: { (connection, result, error) -> Void in
            if (error == nil){
                self.dict = result as? [String : AnyObject]
                print(result!)
                print(self.dict)
            }
        })
    }

Body:
I see it as four steps -- my apologies to you if you already know some of this.

Drag an UIImageView from the object library in interface builder to a view in your storyboard.

Connect the UIImageView to your code as an IBOutlet and name it. Do this by control dragging from your new UIImageView to your code, and then in the popup specify an outlet and name the UIImageView. In my case I named it 'facebookPicture'

Get the URL for the image from the FaceBook result. The following sample code drills down into the result dictionary step by step. There are many ways to shorten this.

@IBOutlet var facebookPicture: UIImageView!

func getFBUserID(){
 if((FBSDKAccessToken.current()) != nil) {
    FBSDKGraphRequest(graphPath: "me", parameters: ["fields": "id, name, first_name, last_name, picture.type(large), email"]).start(
        completionHandler: {
            [weak self] (connection, result, error) -> Void in
            guard let strongSelf = self else { return }
            if let error = error {
                print("Failed to download FB user with error:. \(error)")
            }
            if (error == nil) {
                let resultDictSwift = result as! Dictionary<String, Any>
                if let picture = resultDictSwift["picture"] as? Dictionary<String, Any> {
                    if let pictureData = picture["data"] as? Dictionary<String, Any> {
                        if let pictureURL = NSURL(string: (pictureData["url"] as? String)! ) {
                            strongSelf.downloadImage(url: pictureURL as URL)
                        }
                    }
                }
                print(result!)
                let FBID = resultDictSwift["id"]
                strongSelf.facebookID = FBID as! String?
                print("User FB id: \(strongSelf.facebookID!)")
            }
        })
    }
}

Download the image from the URL location. The following does this asynchronously and uses a previous stack overflow answer here When the download is complete, it sets the result of the download to be the image in your UIImageView

func getDataFromUrl(url: URL, completion: @escaping (Data?, URLResponse?, Error?) -> ()) {
URLSession.shared.dataTask(with: url) { data, response, error in
    completion(data, response, error)
    }.resume()
}

func downloadImage(url: URL) {
    print("Download Started")
    getDataFromUrl(url: url) { data, response, error in
    guard let data = data, error == nil else { return }
    print(response?.suggestedFilename ?? url.lastPathComponent)
    print("Download Finished")
    DispatchQueue.main.async() {
        self.facebookPicture.image = UIImage(data: data)
    }
   }
 }

I hope this helps!


问:
Clojure Even List within even counts
Currently I am trying to partition my lists in clojure into even splits of even values.
To explain.

I have

```<code>(def a '(1 2 3 4 5 6 7 8 9 10))
</code>```

What I want to do is give it a partition function and create even lists that are even in count.
so if I were to split my list by 2 I would want it to look like

```<code>((1 2 3 4 5 6) (7 8 9 10)) or
((1 2 3 4)(5 6 7 8 9 10)) producing 2 lists with even counts.
</code>```

or if I want to split by 4 into even lists it would look something like

```<code>((1 2)(3 4)(5 6)(7 8 9 10))
</code>```

I will always be splitting by even (ex. 2,4,8,16,32). but I want every return list to have even counts without remainders.

I am at a lost and have created numerous parition functions all which don't work. Any help is appreciated.

答:
Here is how I would do it:</p>

```<code>(def a '(1 2 3 4 5 6 7 8 9 10))

(defn trunc-to-even
  "Truncates a value the largest even int less than or equal to value"
  [val]
  (* 2 (Math/floor (/ val 2))))

(defn even-lists [some-list]
  (let [half-even (trunc-to-even (/ (count some-list) 2))]
    (split-at half-even some-list )))

(println (even-lists a))

;=>  [(1 2 3 4) (5 6 7 8 9 10)]
</code>```

Title: Clojure Even List within even counts

Body:
Currently I am trying to partition my lists in clojure into even splits of even values.
To explain.

I have

(def a '(1 2 3 4 5 6 7 8 9 10))

What I want to do is give it a partition function and create even lists that are even in count.
so if I were to split my list by 2 I would want it to look like

((1 2 3 4 5 6) (7 8 9 10)) or
((1 2 3 4)(5 6 7 8 9 10)) producing 2 lists with even counts.

or if I want to split by 4 into even lists it would look something like

((1 2)(3 4)(5 6)(7 8 9 10))

I will always be splitting by even (ex. 2,4,8,16,32). but I want every return list to have even counts without remainders.

I am at a lost and have created numerous parition functions all which don't work. Any help is appreciated.

Body:
Here is how I would do it:

(def a '(1 2 3 4 5 6 7 8 9 10))

(defn trunc-to-even
  "Truncates a value the largest even int less than or equal to value"
  [val]
  (* 2 (Math/floor (/ val 2))))

(defn even-lists [some-list]
  (let [half-even (trunc-to-even (/ (count some-list) 2))]
    (split-at half-even some-list )))

(println (even-lists a))

;=>  [(1 2 3 4) (5 6 7 8 9 10)]


问:
Change Galaxy S8 Navigation Bar Color Programmatically
Since galaxy s8 home/back/recent buttons are now soft keys, so i need to change the back color of the buttons within my application only.</p>

答:
The question asked for programmatically which Dhruv Patel answered correctly

but for anyone else who stumbles upon this and is wondering how to do this in xml, open up styles.xml from /res/values-v21/styles.xml (if your minSdk is less than 21, otherwise just /res/values/styles.xml) and under your theme that you use in your  or  in AndroidManifest (I'm using 'AppTheme' across the entire ),

AndroidManifest.xml

```<code>    ...
    <application
        android:name=".MyApp"
        android:icon="@drawable/appicon"
        android:label="@string/app_name"
        android:theme="@style/AppTheme">
</code>```

insert the line under a theme in the styles.xml

```<code>    <item name="android:navigationBarColor">@android:color/black</item>
</code>```

and change the color to whatever you want so it looks like

styles.xml

```<code>    <resources>
    <style name="AppTheme" parent="Theme.AppCompat.DayNight.DarkActionBar">
        <!-- Other items -->
        <item name="android:textColorHint">@color/hint_gray</item>
        <item name="android:buttonStyle">@style/RobotoButtonStyle</item>

        <item name="android:navigationBarColor">@android:color/black</item>
    </style>
    </resources>
</code>```

if your minSdk is less than 21 and you  don't have the styles-v21 setup you can just insert the line item in styles.xml and Android Studio's built-in tools will show the error and help create the directory

Body:
The question asked for programmatically which Dhruv Patel answered correctly

but for anyone else who stumbles upon this and is wondering how to do this in xml, open up styles.xml from /res/values-v21/styles.xml (if your minSdk is less than 21, otherwise just /res/values/styles.xml) and under your theme that you use in your  or  in AndroidManifest (I'm using 'AppTheme' across the entire ),

AndroidManifest.xml

    ...
    <application
        android:name=".MyApp"
        android:icon="@drawable/appicon"
        android:label="@string/app_name"
        android:theme="@style/AppTheme">

insert the line under a theme in the styles.xml

    <item name="android:navigationBarColor">@android:color/black</item>

and change the color to whatever you want so it looks like

styles.xml

    <resources>
    <style name="AppTheme" parent="Theme.AppCompat.DayNight.DarkActionBar">
        <!-- Other items -->
        <item name="android:textColorHint">@color/hint_gray</item>
        <item name="android:buttonStyle">@style/RobotoButtonStyle</item>

        <item name="android:navigationBarColor">@android:color/black</item>
    </style>
    </resources>

if your minSdk is less than 21 and you  don't have the styles-v21 setup you can just insert the line item in styles.xml and Android Studio's built-in tools will show the error and help create the directory