问:
Side-car Traefik container route to ports in Kuberenets
I am running a NodeJS image in my Kubernetes Pod, while exposing a specific port (9080), and running Traefik as a side-car container as reverse proxy. How do I specify Traefik route from the Deployment template.

Deployment

```<code>apiVersion: apps/v1beta1
kind: Deployment
metadata:
  labels:
    app: web
  name: web-controller
spec:
  replicas: 1
  selector:
     matchLabels:
       app: web
  template:
    metadata:
      labels:
        app: web
    spec:
      containers:
      - image: "nodeJS-image"
        name: web
        ports:
        - containerPort: 9080
          name: http-server
      - image: "traefik-image"
        name: traefik-proxy
        ports:
        - containerPort: 80
          name: traefik-proxy
        - containerPort: 8080
          name: traefik-ui
        args:
        - --web
        - --kubernetes
</code>```

答:
If I understand correctly, you want to forward requests hitting the Traefik container to the Node.js application living in the same pod. Given that the application is configured statically from Traefik's perspective, you can simply mount a proper file provider configuration into the Traefik pod (presumably via a ConfigMap) pointing at the side car container.

The most simple way to achieve this (as documented) is to append the following file provider configuration directly at the bottom of Traefik's TOML configuration file:

```<code>[file]

[backends.backend.servers.server]
url = "http://127.0.0.1:9080"
[frontends.frontend]
backend = "backend"
[frontends.frontend.routes.route]
host = "machine-echo.example.com"
</code>```

If you mount the TOML configuration file into the Traefik pod under a path other than the default one (/etc/traefik.toml), you will also need to pass the --configFile option in the manifest referencing the correct location of the file.

After that, any request hitting the Traefik container on port 80 with a host header of machine-echo.example.com should get forwarded to the Node.js side car container on port 9080.

Body:
I am running a NodeJS image in my Kubernetes Pod, while exposing a specific port (9080), and running Traefik as a side-car container as reverse proxy. How do I specify Traefik route from the Deployment template.

Deployment

apiVersion: apps/v1beta1
kind: Deployment
metadata:
  labels:
    app: web
  name: web-controller
spec:
  replicas: 1
  selector:
     matchLabels:
       app: web
  template:
    metadata:
      labels:
        app: web
    spec:
      containers:
      - image: "nodeJS-image"
        name: web
        ports:
        - containerPort: 9080
          name: http-server
      - image: "traefik-image"
        name: traefik-proxy
        ports:
        - containerPort: 80
          name: traefik-proxy
        - containerPort: 8080
          name: traefik-ui
        args:
        - --web
        - --kubernetes

Body:
If I understand correctly, you want to forward requests hitting the Traefik container to the Node.js application living in the same pod. Given that the application is configured statically from Traefik's perspective, you can simply mount a proper file provider configuration into the Traefik pod (presumably via a ConfigMap) pointing at the side car container.

The most simple way to achieve this (as documented) is to append the following file provider configuration directly at the bottom of Traefik's TOML configuration file:

[file]

[backends.backend.servers.server]
url = "http://127.0.0.1:9080"
[frontends.frontend]
backend = "backend"
[frontends.frontend.routes.route]
host = "machine-echo.example.com"

If you mount the TOML configuration file into the Traefik pod under a path other than the default one (/etc/traefik.toml), you will also need to pass the --configFile option in the manifest referencing the correct location of the file.

After that, any request hitting the Traefik container on port 80 with a host header of machine-echo.example.com should get forwarded to the Node.js side car container on port 9080.


来源: stackexchange

问:
pyspark tsv duplicate columns
I am trying to read a tsv file in pyspark using spark_csv package. My spark version is 1.6.3. In my dataset, two columns have same name. I am using following code to read the data.

```<code>temp=sqlContext.read.load(data_file,
               format='com.databricks.spark.csv',
               header='true',
               delimiter='\t',
               mode='FAILFAST',
               codec="org.apache.hadoop.io.compress.GzipCodec").cache()
</code>```

When I read using above code, I get the following exception:

```<code>pyspark.sql.utils.IllegalArgumentException: u"The header contains a duplicate entry: 'member_id' in [member_status, md5_hash_email, member_id, first_name, last_name, email_daily_double, email_personal_coupon_reminder, email_personal_shopping_offers, email_site_wide_sales, email_hot_deals_daily_newsletter, is_referral, traffic_source, traffic_source_type, traffic_source_subtype, signup_date_id, email_domain_group, first_order_date, first_shopping_date, is_mobile, is_tablet, is_pc, first_order_id, member_engaged, last_visit_date, last_order_date, last_shopping_date, total_order_amount, total_commission_amount, total_rebate_amount, total_cash_payments, number_of_cash_payments, life_cycle_stage, total_orders, member_id]"
</code>```

So, I would like to know if there is someway to drop the duplicate column before start. I know that I can specify schema before hand. But I want it to be dynamic so that I may handle any schema at run time.
Thanks

答:
This has been fixed in recent versions of spark -
 https://issues.apache.org/jira/browse/SPARK-16896

If you cannot upgrade, you will have to construct the header yourself.

ContentLicense: CC BY-SA 3.0

Title: pyspark tsv duplicate columns

Body:
I am trying to read a tsv file in pyspark using spark_csv package. My spark version is 1.6.3. In my dataset, two columns have same name. I am using following code to read the data.

temp=sqlContext.read.load(data_file,
               format='com.databricks.spark.csv',
               header='true',
               delimiter='\t',
               mode='FAILFAST',
               codec="org.apache.hadoop.io.compress.GzipCodec").cache()

When I read using above code, I get the following exception:

pyspark.sql.utils.IllegalArgumentException: u"The header contains a duplicate entry: 'member_id' in [member_status, md5_hash_email, member_id, first_name, last_name, email_daily_double, email_personal_coupon_reminder, email_personal_shopping_offers, email_site_wide_sales, email_hot_deals_daily_newsletter, is_referral, traffic_source, traffic_source_type, traffic_source_subtype, signup_date_id, email_domain_group, first_order_date, first_shopping_date, is_mobile, is_tablet, is_pc, first_order_id, member_engaged, last_visit_date, last_order_date, last_shopping_date, total_order_amount, total_commission_amount, total_rebate_amount, total_cash_payments, number_of_cash_payments, life_cycle_stage, total_orders, member_id]"

So, I would like to know if there is someway to drop the duplicate column before start. I know that I can specify schema before hand. But I want it to be dynamic so that I may handle any schema at run time.
Thanks


问:
Ruby regex to match a space without a leading comma
How can I match a space without a leading comma?

My use case is I would like to split a string on space without a leading comma e.g. "id 10, 11"

答:
You could use the regular expression

```<code>r = /(?<!,) /
</code>```

which reads, "match one space not preceded by a space" ((?!,) being a negative lookbehind).

```<code>"fe, fi, fo and fum".split r
   #=> ["fe, fi, fo", "and", "fum"]
"fe, fi,     fo\nand fum".split r
   #=> ["fe, fi, ", "", "", "", "fo\nand", "fum"]
</code>```

If one wishes to break on one or more spaces not preceded by a comma, use

```<code>r = /(?<!,) +/
"fe, fi,     fo\nand fum".split r
  #=> ["fe, fi, ", "fo\nand", "fum"]
</code>```

To split on one or more whitespace characters not preceded by a comma, use

```<code>r = /(?<!,)\s+/
"fe, fi,     fo\nand fum".split r
  #=> ["fe, fi, ", "fo", "and", "fum"]
</code>```

It may prudent to first perform String#lstrip.

```<code>r = /(?<!,)\s+/
" fe, fi,     fo\nand fum ".split r
  #=> ["", "fe, fi, ", "fo", "and", "fum"]
" fe, fi,     fo\nand fum ".lstrip.split r
  #=> ["fe, fi, ", "fo", "and", "fum"]
</code>```

Depending on requirements, one could instead take @elyvn's advice and write

```<code>r = /(?<=[^,])\s+/
</code>```

which reads, "match one or more whitespace characters preceded by a character other than a comma" ((?<=[^,]) being positive lookbehind).

```<code>" fe, fi,     fo\nand fum ".split r
  #=> [" fe, fi, ", "fo", "and", "fum"]
</code>```

Body:
You could use the regular expression

r = /(?<!,) /

which reads, "match one space not preceded by a space" ((?!,) being a negative lookbehind).

"fe, fi, fo and fum".split r
   #=> ["fe, fi, fo", "and", "fum"]
"fe, fi,     fo\nand fum".split r
   #=> ["fe, fi, ", "", "", "", "fo\nand", "fum"]

If one wishes to break on one or more spaces not preceded by a comma, use

r = /(?<!,) +/
"fe, fi,     fo\nand fum".split r
  #=> ["fe, fi, ", "fo\nand", "fum"]

To split on one or more whitespace characters not preceded by a comma, use

r = /(?<!,)\s+/
"fe, fi,     fo\nand fum".split r
  #=> ["fe, fi, ", "fo", "and", "fum"]

It may prudent to first perform String#lstrip.

r = /(?<!,)\s+/
" fe, fi,     fo\nand fum ".split r
  #=> ["", "fe, fi, ", "fo", "and", "fum"]
" fe, fi,     fo\nand fum ".lstrip.split r
  #=> ["fe, fi, ", "fo", "and", "fum"]

Depending on requirements, one could instead take @elyvn's advice and write

r = /(?<=[^,])\s+/

which reads, "match one or more whitespace characters preceded by a character other than a comma" ((?<=[^,]) being positive lookbehind).

" fe, fi,     fo\nand fum ".split r
  #=> [" fe, fi, ", "fo", "and", "fum"]


问:
Smalltalk copy of object and work on a variables
Hi I need to do a small program in Smalltalk, but I am not sure what I am doing wrong.
So, I have an abstract class Class1, which has few subclasses for example Class2.

What I want to do is to create object in method Class1 class as a copy of them self, work on it and after return in. I know it is might to sound weird but I am horrible in explanation.

My method looks like this:
(value is a variable from Class1)

```<code>|temp|

temp:= self DeepCopy.
1 to: temp >> arrayName size do:
[i: | tenp >> arrayName at i: put (temp >> arrayName at: i) + 10].

^temp
</code>```

This is my first program in Smalltalk and of course it is not working, maybe you know this language and you could help me a little bit.

Thank you

//////////////////////////////////////////////////////////////////// Edit

my method

```<code>move: vector

    | temp |
    temp :=self deepCopy.

    1 to: temp points size do:
    [:i |  temp points at: i put: ( temp points at: i) + vector].

    ^temp .
</code>```

And usage

```<code>geo_1:=(Triangle new) initialize 10.
geo_2:= geo_1 move: 2@2
</code>```

答:
If I understand you correctly, what you want is to clone an object, modify the clone, and then return the modified copy. Am I right? If so, let me provide you with some guidance:

You could indeed implement the cloning mechanism using deepCopy. Note however that case matters in Smalltalk so please don't send the DeepCopy message because (most likely) it will not exist, use deepCopy instead:

```<code>temp := self deepCopy.
</code>```

Names are crucial for readability. Therefore, avoid the use of of generic variables such as temp. In this case I would suggest renaming the temporary to clone, which better reflects your intention:

```<code>| clone |
clone := self deepCopy.
</code>```

See what I mean? The name clone on the left tells the reader what you are doing. The expression self deepCopy tells how you are doing it.

In Smalltalk you access an object property by sending it a message. There is no dot notation or >> or anything for this. To send an message just leave a space in between:

```<code>clone arrayName
</code>```

As a good friend of mine says, In Smalltalk the send operator is the white space.

Try not to compose keyword messages. Use temporaries instead and give them revealing names:

```<code> value := clone arrayName at: i.
 clone arrayName at i: put: value + 10
</code>```

Note that the name value that I'm using is not a good one because is too generic. If your array contains prices you should use price instead. If your array contains points, use point, etc.

Regarding item 3 above, the only way to access an object property from the outside is to send the object a message. In your case, you want to read the points of your object, so you need to provide a #points method that answers with the collection of points the object somehow has. For example, if your class has a points instance variable define a method with that name as

```<code>points
  ^points
</code>```

(in the items above I've used arrayName instead because that was the selector you used initially in your question.)

Body:
Hi I need to do a small program in Smalltalk, but I am not sure what I am doing wrong.
So, I have an abstract class Class1, which has few subclasses for example Class2.

What I want to do is to create object in method Class1 class as a copy of them self, work on it and after return in. I know it is might to sound weird but I am horrible in explanation.

My method looks like this:
(value is a variable from Class1)

|temp|

temp:= self DeepCopy.
1 to: temp >> arrayName size do:
[i: | tenp >> arrayName at i: put (temp >> arrayName at: i) + 10].

^temp

This is my first program in Smalltalk and of course it is not working, maybe you know this language and you could help me a little bit.

Thank you

//////////////////////////////////////////////////////////////////// Edit

my method

move: vector

    | temp |
    temp :=self deepCopy.

    1 to: temp points size do:
    [:i |  temp points at: i put: ( temp points at: i) + vector].

    ^temp .

And usage

geo_1:=(Triangle new) initialize 10.
geo_2:= geo_1 move: 2@2

Body:
If I understand you correctly, what you want is to clone an object, modify the clone, and then return the modified copy. Am I right? If so, let me provide you with some guidance:

You could indeed implement the cloning mechanism using deepCopy. Note however that case matters in Smalltalk so please don't send the DeepCopy message because (most likely) it will not exist, use deepCopy instead:

temp := self deepCopy.

Names are crucial for readability. Therefore, avoid the use of of generic variables such as temp. In this case I would suggest renaming the temporary to clone, which better reflects your intention:

| clone |
clone := self deepCopy.

See what I mean? The name clone on the left tells the reader what you are doing. The expression self deepCopy tells how you are doing it.

In Smalltalk you access an object property by sending it a message. There is no dot notation or >> or anything for this. To send an message just leave a space in between:

clone arrayName

As a good friend of mine says, In Smalltalk the send operator is the white space.

Try not to compose keyword messages. Use temporaries instead and give them revealing names:

 value := clone arrayName at: i.
 clone arrayName at i: put: value + 10

Note that the name value that I'm using is not a good one because is too generic. If your array contains prices you should use price instead. If your array contains points, use point, etc.

Regarding item 3 above, the only way to access an object property from the outside is to send the object a message. In your case, you want to read the points of your object, so you need to provide a #points method that answers with the collection of points the object somehow has. For example, if your class has a points instance variable define a method with that name as

points
  ^points

(in the items above I've used arrayName instead because that was the selector you used initially in your question.)


问:
PHP not loading extension even they exists
My PHP is in the path c:\php on a Windows 2012 server
I added c:\php to the PATH variable.

I added php_pdo_sqlsrv_56_ts.dll in c:\php\ext directory

I added following lines in c:\php\php.ini file:

```<code>extension_dir = "c:\php\ext"
extension=php_pdo_sqlsrv_56_ts.dll
</code>```

But the following command gives me warning that it cannot find the module whereas it exists there:

```<code>php --ini
PHP Warning:  PHP Startup: Unable to load dynamic library 'c:\php\ext\php_sqlsrv_56_ts.dll' - The specified module could not be found. in Unknown on line 0

PHP Warning:  PHP Startup: Unable to load dynamic library 'c:\php\ext\php_pdo_sqlsrv_56_ts.dll' - The specified module could not be found. in Unknown on line 0

Configuration File (php.ini) Path: C:\Windows

Loaded Configuration File:         C:\php\php.ini
</code>```

答:
This might be a Windows problem whereby a DLL is reported as "not existing" if itself requires another DLL that is not found. So for example:

```<code>php_someextusingssl.dll    - the file exists
</code>```

But php_someextusingssl.dll requires ssleay32.dll, and that is not found at run time. So the error you get is "Cannot load php_someextusingssl.dll: file not found". The file not being found is not php_someextusingssl.dll, it is ssleay32.dll.

How do you solve this problem: get hold of some utility such as DEPENDS.EXE, and open the misbehaving extension. It should display the extension and all the DLLs on which it depends. IF I am right, then one or more will be marked red as "missing". Those are the DLLs you need to make available.

UPDATE 1: chances are that the missing files are among those listed on Microsoft SQL Server Driver page.

UPDATE 2: I've downloaded a copy of the Microsoft driver. Yours depends on ODBC32.DLL, MSVCP110.DLL and MSVCR110.DLL. The latter two are part of the Microsoft Visual C++ 2010 SP1 Redistributable for x86, which you can find here. The first is part of the ODBC32 driver listed as per Update 1.

Body:
My PHP is in the path c:\php on a Windows 2012 server
I added c:\php to the PATH variable.

I added php_pdo_sqlsrv_56_ts.dll in c:\php\ext directory

I added following lines in c:\php\php.ini file:

extension_dir = "c:\php\ext"
extension=php_pdo_sqlsrv_56_ts.dll

But the following command gives me warning that it cannot find the module whereas it exists there:

php --ini
PHP Warning:  PHP Startup: Unable to load dynamic library 'c:\php\ext\php_sqlsrv_56_ts.dll' - The specified module could not be found. in Unknown on line 0

PHP Warning:  PHP Startup: Unable to load dynamic library 'c:\php\ext\php_pdo_sqlsrv_56_ts.dll' - The specified module could not be found. in Unknown on line 0

Configuration File (php.ini) Path: C:\Windows

Loaded Configuration File:         C:\php\php.ini

Body:
This might be a Windows problem whereby a DLL is reported as "not existing" if itself requires another DLL that is not found. So for example:

php_someextusingssl.dll    - the file exists

But php_someextusingssl.dll requires ssleay32.dll, and that is not found at run time. So the error you get is "Cannot load php_someextusingssl.dll: file not found". The file not being found is not php_someextusingssl.dll, it is ssleay32.dll.

How do you solve this problem: get hold of some utility such as DEPENDS.EXE, and open the misbehaving extension. It should display the extension and all the DLLs on which it depends. IF I am right, then one or more will be marked red as "missing". Those are the DLLs you need to make available.

UPDATE 1: chances are that the missing files are among those listed on Microsoft SQL Server Driver page.

UPDATE 2: I've downloaded a copy of the Microsoft driver. Yours depends on ODBC32.DLL, MSVCP110.DLL and MSVCR110.DLL. The latter two are part of the Microsoft Visual C++ 2010 SP1 Redistributable for x86, which you can find here. The first is part of the ODBC32 driver listed as per Update 1.


问:
How do I handle decoding two possible types for one key in Swift?
I have a Codable struct that is used to decode incoming JSON. Unfortunately, sometimes one of its key's value is a string, and sometimes it is a float. I was able to cobble a couple of do/try/catch blocks below to get it to work, but is there a better way to handle this?</p>

```<code>struct Project: Codable {
    public let version: Float

    init(from decoder: Decoder) throws {
        var decodedVersion: Float = 1.0
        do {
            decodedVersion = try values.decode(Float.self, forKey: .version)
        } catch {
            do {
                if let inVersion = try Float(values.decode(String.self, forKey: .version)) {
                    decodedVersion = inVersion
                }
            } catch {
                throw error
            }
        }
        version = decodedVersion
    }
}
</code>```

答:
If in your JSON the value associated to a key can be sometimes a Float and sometimes a String (besides fixing this error on the backend ) you could follow this approach.

Let's say this is your "funny" JSON

```<code>let data = """
[
{
    "magicField": "one"
},
{
    "magicField":1
}
]
""".data(using: .utf8)!
</code>```

Good, how can we elegantly represent this kind of data in Swift?

```<code>struct Element:Decodable {
    let magicField: ???
}
</code>```

We want magicField to always have a value, sometimes a Float and sometimes a String.

We can solve this with Quantum Mechanics... or with an Enum

Let's define this type

```<code>enum QuantumValue: Decodable {

    case float(Float), string(String)

    init(from decoder: Decoder) throws {
        if let float = try? decoder.singleValueContainer().decode(Float.self) {
            self = .float(float)
            return
        }

        if let string = try? decoder.singleValueContainer().decode(String.self) {
            self = .string(string)
            return
        }

        throw QuantumError.missingValue
    }

    enum QuantumError:Error {
        case missingValue
    }
}
</code>```

As you can see a value of type QuantumValue can hold a Float or a String. Always 1 and exactly 1 value.

Element

We can now define the general element of our JSON

```<code>struct Element:Decodable {
    let magicField: QuantumValue
}
</code>```

Decoding

That's it. Let's finally decode the JSON.

```<code>if let elms = try? JSONDecoder().decode([Element].self, from: data) {
    print(elms)
}
</code>```

Result

```<code>[
Element(magicField: QuantumValue.string("one")),
Element(magicField: QuantumValue.float(1.0))
]
</code>```

Update (to answer Rob’s comment)

```<code>switch magicField {
    case .string(let text):
        println(text)
    case .float(let num):
        println(num)
}
</code>```

Body:
I have a Codable struct that is used to decode incoming JSON. Unfortunately, sometimes one of its key's value is a string, and sometimes it is a float. I was able to cobble a couple of do/try/catch blocks below to get it to work, but is there a better way to handle this?

struct Project: Codable {
    public let version: Float

    init(from decoder: Decoder) throws {
        var decodedVersion: Float = 1.0
        do {
            decodedVersion = try values.decode(Float.self, forKey: .version)
        } catch {
            do {
                if let inVersion = try Float(values.decode(String.self, forKey: .version)) {
                    decodedVersion = inVersion
                }
            } catch {
                throw error
            }
        }
        version = decodedVersion
    }
}

Body:
If in your JSON the value associated to a key can be sometimes a Float and sometimes a String (besides fixing this error on the backend ) you could follow this approach.

Let's say this is your "funny" JSON

let data = """
[
{
    "magicField": "one"
},
{
    "magicField":1
}
]
""".data(using: .utf8)!

Good, how can we elegantly represent this kind of data in Swift?

struct Element:Decodable {
    let magicField: ???
}

We want magicField to always have a value, sometimes a Float and sometimes a String.

We can solve this with Quantum Mechanics... or with an Enum

Let's define this type

enum QuantumValue: Decodable {

    case float(Float), string(String)

    init(from decoder: Decoder) throws {
        if let float = try? decoder.singleValueContainer().decode(Float.self) {
            self = .float(float)
            return
        }

        if let string = try? decoder.singleValueContainer().decode(String.self) {
            self = .string(string)
            return
        }

        throw QuantumError.missingValue
    }

    enum QuantumError:Error {
        case missingValue
    }
}

As you can see a value of type QuantumValue can hold a Float or a String. Always 1 and exactly 1 value.

Element

We can now define the general element of our JSON

struct Element:Decodable {
    let magicField: QuantumValue
}

Decoding

That's it. Let's finally decode the JSON.

if let elms = try? JSONDecoder().decode([Element].self, from: data) {
    print(elms)
}

Result

[
Element(magicField: QuantumValue.string("one")),
Element(magicField: QuantumValue.float(1.0))
]

Update (to answer Rob’s comment)

switch magicField {
    case .string(let text):
        println(text)
    case .float(let num):
        println(num)
}

ContentLicense: CC BY-SA 4.0


问:
Using Cassandra with Spring boot gradle. Which API to use to connect?
Hi I am starting a new Spring Boot project using Cassandra.
I am doing my study on it but I have some doubt on the below issues:

Using Spring Boot, which would be the best API for connecting to Cassandra ?
Eg:Datstax or Astyanax ? Are Datastax and CQL3 different ?
(As of now some '13 answers have a rift between Datastax and Astyanax. Its inconclusive.)

Is Python required to run Cassandra ?

Where can I get good reading material on Cassandra ? And its usage/integration with Spring/Spring Boot

Also, going forward we will be integrating Apache Kafka with this project.
I have gone through some old answers, but the are 5 years old. So I am looking for a more concluding answer.

Thanks for help !!

答:
Spring Boot has native support for Datastax driver with spring-data.
Easy way to start is to check my sample apps:
http://valchkou.com/spring-boot-cassandra.html

Spring Data Cassandra Documentation
https://projects.spring.io/spring-data-cassandra/

The best Cassandra Documentation provided by Datastax.
Python is not required to run cassandra.
JRE 8 is required.

Spring Boot has support for kafka.
https://docs.spring.io/spring-kafka/reference/htmlsingle/


问:
SQL Query for paramaterized dynamic table
One of the product teams I manage has an abundance of queries that use dynamic sql queries injecting the table in using concatenation. While it has sanitisation, I am trying to completely remove dynamic sql.

Is there a way to parameterise the table name?
I am trying to think of how I can query a table something like:

```<code>SELECT * FROM (SELECT DISTINCT Table_Name FROM INFORMATION_SCHEMA.Tables WHERE Table_Name = :queryParam)
</code>```

Is this possible?

答:
I am trying to completely remove dynamic sql.

You can't do it without Dynamic SQL.

Is this possible?

No, it's not possible, you cannot parameterize identifiers in SQL queries.

Why?

From the Books online page for Variables, Variables can be used only in expressions, not in place of object names or keywords. To construct dynamic SQL statements, use EXECUTE.

This is the only way to do it:

```<code>DECLARE @Column SysName = N'Table_Name',
        @Param NVARCHAR(128) = N'ParamValue';

DECLARE @SQL NVARCHAR(MAX)=N'SELECT *
                             FROM(
                                   SELECT '+ QUOTENAME(@Column) +
                                   'FROM INFORMATION_SCHEMA.Tables
                                    WHERE ' + QUOTENAME(@Column) + ' = @Param
                                 ) T';
EXECUTE sp_executesql @SQl,
                      N'@Param NVARCHAR(128)',
                      @Param;
</code>```

Body:
One of the product teams I manage has an abundance of queries that use dynamic sql queries injecting the table in using concatenation. While it has sanitisation, I am trying to completely remove dynamic sql.

Is there a way to parameterise the table name?
I am trying to think of how I can query a table something like:

SELECT * FROM (SELECT DISTINCT Table_Name FROM INFORMATION_SCHEMA.Tables WHERE Table_Name = :queryParam)

Is this possible?

Body:
I am trying to completely remove dynamic sql.

You can't do it without Dynamic SQL.

Is this possible?

No, it's not possible, you cannot parameterize identifiers in SQL queries.

Why?

From the Books online page for Variables, Variables can be used only in expressions, not in place of object names or keywords. To construct dynamic SQL statements, use EXECUTE.

This is the only way to do it:

DECLARE @Column SysName = N'Table_Name',
        @Param NVARCHAR(128) = N'ParamValue';

DECLARE @SQL NVARCHAR(MAX)=N'SELECT *
                             FROM(
                                   SELECT '+ QUOTENAME(@Column) +
                                   'FROM INFORMATION_SCHEMA.Tables
                                    WHERE ' + QUOTENAME(@Column) + ' = @Param
                                 ) T';
EXECUTE sp_executesql @SQl,
                      N'@Param NVARCHAR(128)',
                      @Param;


问:
SynchronizingObject vs. Invoke
In my form's class, I've added a method to "fade" it out. This makes use of System.Timers.Timer and the Elapsed event uses a delegate to change the form's opacity. This was the code:

```<code>public void FadeOut()
{
    // Timer for transition
    Timer fade = new Timer();

    // Transition code
    fade.Elapsed += delegate
    {
        this.Opacity += 0.05;

        if (this.Opacity >= .95)
        {
            this.Opacity = 1;
            fade.Enabled = false;
            fade.Dispose();
        }
    };

    fade.Interval = 100;
    fade.Enabled = true;
}
</code>```

This caused a "Cross-thread operation not valid" error, which is a common hurdle I see. So I looked around for solutions and the first ones to come up involved using .BeginInvoke and blocks of code to keep the call to the same thread as the control. But I found this looked really bulky, so I kept looking and then discovered the SynchronizingObject property of System.Timers.Timer. This seems better because it only needed one extra line of code:

```<code>// Timer for transition
Timer fade = new Timer();
fade.SynchronizingObject = this;
</code>```

The code runs fine now. But I'm really confused, how come a lot of solutions are suggesting the use of BeginInvoke/Invoke when all that's needed is to set SynchronizingObject to the form control?

答:
The point is the SCOPE of code. The whole event handler? or just the UI changing code.

timer.SynchronizingObject make the event handler to be called on the thread of given object. If you set this to 'this' in 'Form1' class, This means that all of your code for processing timer event is run by that same thread of 'Form1' instance even though you created a thread based timer.  So this does NOTHING. SAME as windows form timer.

The reason you want to do this is because you want to access UI controls and make some changes in Form1, but the whole UI hangs if you use windows form timer. Because they all get executed on the same thread.

To avoid this, you use a threading based timer. Your event handler is called on another thread that comes from some system thread pool. This solves the problem of hanging UI. However, this brings up another problem. Cross-thread accessing UI controls exception. On some versions of Visual Studio, you can disable this checking on debug builds. But there is no way you can just bypass this checking on release builds. This thread checking is just by design to safeguard from crashes caused by multi-threading. THEN you need to use all those invoke and delegation stuff.

The important part here is that it is the only few lines of code that is redirected to be run on the Form1 thread. Not the whole event handler. Most of the event handling code is run on another thread. And that includes code like doing something on network or disk.

This makes the DIFFERENCE.

BUT, all these apply to windows form apps only. For WPF, just use dispatcher timer. (This is why you cannot find Windows.Threading in WinForm because you can't used dispatcher timer in WinForm, but available in WPF)

Title: SynchronizingObject vs. Invoke

Body:
In my form's class, I've added a method to "fade" it out. This makes use of System.Timers.Timer and the Elapsed event uses a delegate to change the form's opacity. This was the code:

public void FadeOut()
{
    // Timer for transition
    Timer fade = new Timer();

    // Transition code
    fade.Elapsed += delegate
    {
        this.Opacity += 0.05;

        if (this.Opacity >= .95)
        {
            this.Opacity = 1;
            fade.Enabled = false;
            fade.Dispose();
        }
    };

    fade.Interval = 100;
    fade.Enabled = true;
}

This caused a "Cross-thread operation not valid" error, which is a common hurdle I see. So I looked around for solutions and the first ones to come up involved using .BeginInvoke and blocks of code to keep the call to the same thread as the control. But I found this looked really bulky, so I kept looking and then discovered the SynchronizingObject property of System.Timers.Timer. This seems better because it only needed one extra line of code:

// Timer for transition
Timer fade = new Timer();
fade.SynchronizingObject = this;

The code runs fine now. But I'm really confused, how come a lot of solutions are suggesting the use of BeginInvoke/Invoke when all that's needed is to set SynchronizingObject to the form control?


问:
Single.zip completing before onSuccess
I want to combine the response of 2 singles in one object

```<code>override fun buildUseCase(params: Int): Single<EventDetails> {
    return eventDetailsComponent.getEventDetails(params)
        .zipWith(bookingComponent.getBookingPage(bookingParams), BiFunction { details, page ->
              return@BiFunction details.apply { booking_page = page } })
}
</code>```

But when I subscribe I'm not receiving onSuccess cause one of the singles completes before the other

```<code>fun loadEventDetails(id: Int) {
 usecase.execute(id)
.doOnSubscribe(onSubscribe)
.observeOn(SchedulerProvider.mainThread)
.subscribeBy(onSuccess = { details -> setValues(details) },onError = onError)
.addTo(subscriptions)
}
</code>```

What should I do to combine those calls? or to receive onSuccess in the end?

答: Apparently I forgot to observeOn the main thread

Title: Single.zip completing before onSuccess

Body:
I want to combine the response of 2 singles in one object

override fun buildUseCase(params: Int): Single<EventDetails> {
    return eventDetailsComponent.getEventDetails(params)
        .zipWith(bookingComponent.getBookingPage(bookingParams), BiFunction { details, page ->
              return@BiFunction details.apply { booking_page = page } })
}

But when I subscribe I'm not receiving onSuccess cause one of the singles completes before the other

fun loadEventDetails(id: Int) {
 usecase.execute(id)
.doOnSubscribe(onSubscribe)
.observeOn(SchedulerProvider.mainThread)
.subscribeBy(onSuccess = { details -> setValues(details) },onError = onError)
.addTo(subscriptions)
}

What should I do to combine those calls? or to receive onSuccess in the end?


问:
App Icons not included in build from Xcode
I can't see iOS AppIcon when installing the build from the latest Xcode Beta. What could be the possible error?

I have included the required icon sizes including 1024x1024.

答:
1- Add this code to Podfile:

```<code>post_install do |installer|
    copy_pods_resources_path = "Pods/Target Support Files/Pods-IconTest/Pods-IconTest-resources.sh"
    string_to_replace = '--compile "${BUILT_PRODUCTS_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}"'
    assets_compile_with_app_icon_arguments = '--compile "${BUILT_PRODUCTS_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}" --app-icon "${ASSETCATALOG_COMPILER_APPICON_NAME}" --output-partial-info-plist "${BUILD_DIR}/assetcatalog_generated_info.plist"'
    text = File.read(copy_pods_resources_path)
    new_contents = text.gsub(string_to_replace, assets_compile_with_app_icon_arguments)
    File.open(copy_pods_resources_path, "w") {|file| file.puts new_contents }
end
</code>```

2- pod install

note: make sure you replace this:
Pods-IconTest/Pods-IconTest-resources.sh

as IconTest is the name of your app

or you can get this path by searching for .sh: (check image)

Body:
1- Add this code to Podfile:

post_install do |installer|
    copy_pods_resources_path = "Pods/Target Support Files/Pods-IconTest/Pods-IconTest-resources.sh"
    string_to_replace = '--compile "${BUILT_PRODUCTS_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}"'
    assets_compile_with_app_icon_arguments = '--compile "${BUILT_PRODUCTS_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}" --app-icon "${ASSETCATALOG_COMPILER_APPICON_NAME}" --output-partial-info-plist "${BUILD_DIR}/assetcatalog_generated_info.plist"'
    text = File.read(copy_pods_resources_path)
    new_contents = text.gsub(string_to_replace, assets_compile_with_app_icon_arguments)
    File.open(copy_pods_resources_path, "w") {|file| file.puts new_contents }
end

2- pod install

note: make sure you replace this:
Pods-IconTest/Pods-IconTest-resources.sh

as IconTest is the name of your app

or you can get this path by searching for .sh: (check image)


问:
Are these NotePad++ features available in TextMate?
I'm a NotePad++ user, new to TextMate.

There are some features that I really like in NP++ but couldn't figure out if TextMate support them.

Double click on a variable and have all instances highlighted

View 2 text windows side by side

Drag a file onto another opened Window

For this one, I don't know how to generate a screenshot ;-p. Basically, you can drag a file from Windows Explorer and drop it into NP++ to have it opened.

答:
View 2 text windows side by side

I just tried this and it doesn't seem to recognize this functionality.  the only time any sort of "add" icon came up was when I dragged the file into an open document and then released, but that resulted in adding the contents of the file into the document.

I just did a quick google search for "textmate split view" and it still doesn't seem to be supported according to some of the answers i found (one from macromates wiki).

Double click on a variable and have all instances highlighted

This also doesn't seem to be supported. This post suggests using the command + f (find), put the word into find, then command + g to jump to the next instance of that word.

There are definitely some things that can be added to textmate to make it more robust.  If you are looking for something similar and are on a windows machine, you should check out e text editor.  I loved that editor when I was working on a windows machine - split view is supported, but not sure about the highlighting.  One thing that e also beats out textmate is the real time regular expression highlighting.

ContentLicense: CC BY-SA 2.5


问:
How to get calendar date from only year and julian day (yday) in R
I have a data set that has column containing year, and a column containing the ordinal (yday) day for each year. I would like to convert this information into a calendar date, so I can better filter the data set. The data looks like this, but is from 1980-2016 and has an entry for each day of the year:

year  yday  temp

1980     1   0.5

1980     2  -5.0

1980     3  -3.5

1980     4   1.0

1980     5  -1.0

```<code>temps<-structure(list(year = c(1980L, 1980L, 1980L, 1980L, 1980L), yday = 1:5,
    temp = c(0.5, -5, -3.5, 1, -1)), row.names = c(NA, -5L), class = c("tbl_df",
"tbl", "data.frame"), .Names = c("year", "yday", "temp"))
</code>```

I tried the following code, but could not get the correct calendar date:
Convert day of year to date

Body:
I have a data set that has column containing year, and a column containing the ordinal (yday) day for each year. I would like to convert this information into a calendar date, so I can better filter the data set. The data looks like this, but is from 1980-2016 and has an entry for each day of the year:

year  yday  temp

1980     1   0.5

1980     2  -5.0

1980     3  -3.5

1980     4   1.0

1980     5  -1.0

temps<-structure(list(year = c(1980L, 1980L, 1980L, 1980L, 1980L), yday = 1:5,
    temp = c(0.5, -5, -3.5, 1, -1)), row.names = c(NA, -5L), class = c("tbl_df",
"tbl", "data.frame"), .Names = c("year", "yday", "temp"))

I tried the following code, but could not get the correct calendar date:
Convert day of year to date

Body:
You could start with January 1st, then calculate it by adding your yday values.

with(temps, as.Date(paste0(year, "-01-01")) + (yday - 1))
# [1] "1980-01-01" "1980-01-02" "1980-01-03" "1980-01-04" "1980-01-05"


问:
C# Compare two lists with objects
i'm making simple program, and i'm stuck on simple question. How can i compare two lists with objects , find that object and print all class elements that belongs to that object?

```<code> List<Skaitytojas> MyObjectList = new List<Skaitytojas>();
 List<Knyga> KnyguList = new List<Knyga>();

 private void button2_Click(object sender, EventArgs e)
    {
        Reader reader = new Reader();

        reader._surname = Convert.ToString(textBox1.Text);
        reader._id = Convert.ToInt32(textBox2.Text);

        MyObjectList.Add(reader);
        MessageBox.Show("you created new user");
    }

private void button4_Click(object sender, EventArgs e)
    {
        Book new_book = new Book();

       new_book.book_id = Convert.ToInt32(textBox3.Text);
        new_book.date1 = Convert.ToString(textBox4.Text);
        new_book.date2 = Convert.ToString(textBox5.Text);
        new_book.date3 = Convert.ToString(textBox6.Text);
       new_book._id2 = Convert.ToInt32(textBox7.Text);

        BookList.Add(new_book);
        MessageBox.Show("you added new book!");
    }
</code>```

I want to compare reader._id with new_book.id2, its gonna be same number , and if i find it i want to print all information about it: book id,date1,date2 etc.
But i don't know how to do it, i tried it this way:

```<code>public void print_book(int x, ListBox f)
    {
        List<Book> BookList = new List<Book>();
        foreach (var k in BookList)
        {
            if (x == k._id2)
            {
                f.Items.Add(x);
            }
        }
    }
</code>```

Call function with button

```<code>private void button3_Click(object sender, EventArgs e)
    {

        int x = Convert.ToInt32(textBox2.Text);
        Metodai m = new Metodai();
        m.print_book(x, this.listBox1);
    }
</code>```

When i try to do this function the list is still empty, whats wrong with it? Maybe there is another way to do it? Can you help me?

答:
The line

```<code>foreach (var k in BookList)
</code>```

You've just instantiated BookList in the line before so it's looping through nothing.

Title: C# Compare two lists with objects

Body:
i'm making simple program, and i'm stuck on simple question. How can i compare two lists with objects , find that object and print all class elements that belongs to that object?

 List<Skaitytojas> MyObjectList = new List<Skaitytojas>();
 List<Knyga> KnyguList = new List<Knyga>();

 private void button2_Click(object sender, EventArgs e)
    {
        Reader reader = new Reader();

        reader._surname = Convert.ToString(textBox1.Text);
        reader._id = Convert.ToInt32(textBox2.Text);

        MyObjectList.Add(reader);
        MessageBox.Show("you created new user");
    }

private void button4_Click(object sender, EventArgs e)
    {
        Book new_book = new Book();

       new_book.book_id = Convert.ToInt32(textBox3.Text);
        new_book.date1 = Convert.ToString(textBox4.Text);
        new_book.date2 = Convert.ToString(textBox5.Text);
        new_book.date3 = Convert.ToString(textBox6.Text);
       new_book._id2 = Convert.ToInt32(textBox7.Text);

        BookList.Add(new_book);
        MessageBox.Show("you added new book!");
    }

I want to compare reader._id with new_book.id2, its gonna be same number , and if i find it i want to print all information about it: book id,date1,date2 etc.
But i don't know how to do it, i tried it this way:

public void print_book(int x, ListBox f)
    {
        List<Book> BookList = new List<Book>();
        foreach (var k in BookList)
        {
            if (x == k._id2)
            {
                f.Items.Add(x);
            }
        }
    }

Call function with button

private void button3_Click(object sender, EventArgs e)
    {

        int x = Convert.ToInt32(textBox2.Text);
        Metodai m = new Metodai();
        m.print_book(x, this.listBox1);
    }

When i try to do this function the list is still empty, whats wrong with it? Maybe there is another way to do it? Can you help me?

Body:
The line

foreach (var k in BookList)

You've just instantiated BookList in the line before so it's looping through nothing.


问:
Swift: Cannot convert value of type '[Any]' to specified type 'NSString'
General: I have a collections view app with several items from several plist depending which one the user picked. The plist is an array containing several arrays with multiple strings inside each array.

Problem: When inplementing a search bar to search through my collections (or plist), I get this error when following a tutorial.

I know this search bar code is meant to look for a string and not the string inside an array inside another array in the plist. So I'm looking for help to fix my error and the code.

Error:

Cannot convert value of type '[Any]' to specified type 'NSString'

This is the code what is causing the error.

```<code>func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {

    filtered = car.filter({ (text) -> Bool in
        let tmp: NSString = text // <-- ** Error is here **
        let range = tmp.range(of: searchText, options: NSString.CompareOptions.caseInsensitive)
        return range.location != NSNotFound
    })

    if(filtered.count == 0){
        searchActive = false;
    } else {
        searchActive = true;
    }

    self.finalCollectView.reloadData()
}
</code>```

Rest of my code for SearchBar

```<code>func createSearchBar() {

    let mySearchBar = UISearchBar()
    mySearchBar.showsCancelButton = false
    mySearchBar.placeholder = "Search"
    mySearchBar.delegate = self
    mySearchBar.alpha = 1
    mySearchBar.tintColor = UIColor.black
    mySearchBar.searchFieldBackgroundPositionAdjustment = UIOffset(horizontal: 5, vertical: 0)

    self.navigationItem.titleView = mySearchBar
}

func searchBarTextDidBeginEditing(_ searchBar: UISearchBar) {
    searchActive = true;
}

func searchBarTextDidEndEditing(_ searchBar: UISearchBar) {
    searchActive = false;
}

func searchBarCancelButtonClicked(_ searchBar: UISearchBar) {
    searchActive = false;
}

func searchBarSearchButtonClicked(_ searchBar: UISearchBar) {
    searchActive = false;
}
</code>```

Code for plist

```<code>var filtered = [[Any]]()
var searchActive: Bool = false
var car = [[Any]]()
@IBOutlet weak var finalCollectView: UICollectionView!

override func viewDidLoad() {
    super.viewDidLoad()

    self.finalCollectView.delegate = self
    self.finalCollectView.dataSource = self

    readList(titlePlist: "car")
}

func readList(titlePlist: String) {

    let url = Bundle.main.url(forResource: titlePlist, withExtension: "plist")!
    do {
        let data = try Data(contentsOf:url)
        let sections = try PropertyListSerialization.propertyList(from: data, format: nil) as! [[Any]]

        car = sections

    } catch {
        print("This error must never occur: Reading plist", error)
    }
</code>```

How the plist looks like

```<code><plist>
    <array>
        <array>
            <string>Name1</string>
            <string>Description</string>
        </array>
        <array>
            <string>Name2</string>
            <string>Description</string>
        </array>
        <array>
            <string>Name3</string>
            <string>Description</string>
        </array>
    </array>
</plist>
</code>```

Search bar needs to search through the first string in each array. Thank you!

答:
In your func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String), modify filtering to:

```<code>filtered = car.filter({ (anArray) -> Bool in
    guard let firstString = (anArray.first as? String) else{
       return false
    }
    let tmp: NSString = firstString as NSString
    let range = tmp.range(of: searchText, options: NSString.CompareOptions.caseInsensitive)
    return range.location != NSNotFound
})
</code>```

Body:
General: I have a collections view app with several items from several plist depending which one the user picked. The plist is an array containing several arrays with multiple strings inside each array.

Problem: When inplementing a search bar to search through my collections (or plist), I get this error when following a tutorial.

I know this search bar code is meant to look for a string and not the string inside an array inside another array in the plist. So I'm looking for help to fix my error and the code.

Error:

Cannot convert value of type '[Any]' to specified type 'NSString'

This is the code what is causing the error.

func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {

    filtered = car.filter({ (text) -> Bool in
        let tmp: NSString = text // <-- ** Error is here **
        let range = tmp.range(of: searchText, options: NSString.CompareOptions.caseInsensitive)
        return range.location != NSNotFound
    })

    if(filtered.count == 0){
        searchActive = false;
    } else {
        searchActive = true;
    }

    self.finalCollectView.reloadData()
}

Rest of my code for SearchBar

func createSearchBar() {

    let mySearchBar = UISearchBar()
    mySearchBar.showsCancelButton = false
    mySearchBar.placeholder = "Search"
    mySearchBar.delegate = self
    mySearchBar.alpha = 1
    mySearchBar.tintColor = UIColor.black
    mySearchBar.searchFieldBackgroundPositionAdjustment = UIOffset(horizontal: 5, vertical: 0)

    self.navigationItem.titleView = mySearchBar
}

func searchBarTextDidBeginEditing(_ searchBar: UISearchBar) {
    searchActive = true;
}

func searchBarTextDidEndEditing(_ searchBar: UISearchBar) {
    searchActive = false;
}

func searchBarCancelButtonClicked(_ searchBar: UISearchBar) {
    searchActive = false;
}

func searchBarSearchButtonClicked(_ searchBar: UISearchBar) {
    searchActive = false;
}

Code for plist

var filtered = [[Any]]()
var searchActive: Bool = false
var car = [[Any]]()
@IBOutlet weak var finalCollectView: UICollectionView!

override func viewDidLoad() {
    super.viewDidLoad()

    self.finalCollectView.delegate = self
    self.finalCollectView.dataSource = self

    readList(titlePlist: "car")
}

func readList(titlePlist: String) {

    let url = Bundle.main.url(forResource: titlePlist, withExtension: "plist")!
    do {
        let data = try Data(contentsOf:url)
        let sections = try PropertyListSerialization.propertyList(from: data, format: nil) as! [[Any]]

        car = sections

    } catch {
        print("This error must never occur: Reading plist", error)
    }

How the plist looks like

<plist>
    <array>
        <array>
            <string>Name1</string>
            <string>Description</string>
        </array>
        <array>
            <string>Name2</string>
            <string>Description</string>
        </array>
        <array>
            <string>Name3</string>
            <string>Description</string>
        </array>
    </array>
</plist>

Search bar needs to search through the first string in each array. Thank you!

Body:
In your func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String), modify filtering to:

filtered = car.filter({ (anArray) -> Bool in
    guard let firstString = (anArray.first as? String) else{
       return false
    }
    let tmp: NSString = firstString as NSString
    let range = tmp.range(of: searchText, options: NSString.CompareOptions.caseInsensitive)
    return range.location != NSNotFound
})


问:
Converting Binary to Decimal in python (without built in binary function)
Alrighty, first post here, so please forgive and ignore if the question is not workable;

Background:
I'm in computer science 160.  I haven't taken any computer related classes since high school, so joining this class was a big shift for me. It all seemed very advanced.  We have been working in Python and each week we are prompted to write a program.

I have been working with this problem for over a week and am having a hard time even starting.

The prompt is to read an integer containing only 1's and 0's,
process the binary number digit by digit and report the decimal equivalent.  Now, I have gotten some tips from a classmate and it sent me at least in a direction.

Set up a couple of counters;
using the % operator to check the remainder of the number divided by 2, and slicing off the last number (to the right) to move on to and process the next digit.

I am having an incredibly hard time wrapping my head around what formula to use on the binary digits themselves which will convert the number to decimal.

```<code>setbitval = 0
counter = 0

user = int(input("enter a binary value. "))

if user % 2 == 1:
        user = (user/10) - .1
        setbitval += 1
</code>```

This is all I've got so far.. My thinking is getting in the way.  I've searched and searched, even through these forums.

Any information or thoughts are extremely appreciated,

T

Edit: okay guys, everyone's help has been extremely useful but I'm having a problem checking if the user input is not a binary number.

```<code>for i in reversed(bits):
decimal += 2**counter * int(i)

counter += 1
</code>```

This is the formula someone here gave me and I've been trying different iterations of "for i in bits:  if i in bits: != 0 or 1" and also "if i in bits: >= 1 or <=0".

Any thoughts?

答:
To convert binary value to decimal you need to do the following:

Take the least significant bit and multiply it by 2^0, then take the next least significant beat and multiply it by 2^1, next one by 2^2 and so on...

Let's say, for example you need to convert a number 1010 to decimal:

You would have 0*2^0 + 1*2^1 + 0*2^2 + 1*2^3 = 0 + 2 + 0 + 8 = 10

So in your python code, you need to:

read the int that the user inputted (representing the binary value).

convert that int and convert it to string, so you can break it into list of digits

make a list of digits from the string you created (a list int python can be created from a string not an int, that's why you need the conversion to string first)

go trough that list of bits in reverse and multiply every bit by 2^k, k being the counter starting from 0

Here's the code that demonstrates what I just tried to explain:

```<code>user_input = int(input("enter a binary value"))

bits = list(str(user_input))

decimal = 0

counter = 0

for i in reversed(bits):
    decimal += 2**counter * int(i)
    counter+=1

print 'The decimal value is: ', decimal
</code>```

Body:
Alrighty, first post here, so please forgive and ignore if the question is not workable;

Background:
I'm in computer science 160.  I haven't taken any computer related classes since high school, so joining this class was a big shift for me. It all seemed very advanced.  We have been working in Python and each week we are prompted to write a program.

I have been working with this problem for over a week and am having a hard time even starting.

The prompt is to read an integer containing only 1's and 0's,
process the binary number digit by digit and report the decimal equivalent.  Now, I have gotten some tips from a classmate and it sent me at least in a direction.

Set up a couple of counters;
using the % operator to check the remainder of the number divided by 2, and slicing off the last number (to the right) to move on to and process the next digit.

I am having an incredibly hard time wrapping my head around what formula to use on the binary digits themselves which will convert the number to decimal.

setbitval = 0
counter = 0

user = int(input("enter a binary value. "))

if user % 2 == 1:
        user = (user/10) - .1
        setbitval += 1

This is all I've got so far.. My thinking is getting in the way.  I've searched and searched, even through these forums.

Any information or thoughts are extremely appreciated,

T

Edit: okay guys, everyone's help has been extremely useful but I'm having a problem checking if the user input is not a binary number.

for i in reversed(bits):
decimal += 2**counter * int(i)

counter += 1

This is the formula someone here gave me and I've been trying different iterations of "for i in bits:  if i in bits: != 0 or 1" and also "if i in bits: >= 1 or <=0".

Any thoughts?

Body:
To convert binary value to decimal you need to do the following:

Take the least significant bit and multiply it by 2^0, then take the next least significant beat and multiply it by 2^1, next one by 2^2 and so on...

Let's say, for example you need to convert a number 1010 to decimal:

You would have 0*2^0 + 1*2^1 + 0*2^2 + 1*2^3 = 0 + 2 + 0 + 8 = 10

So in your python code, you need to:

read the int that the user inputted (representing the binary value).

convert that int and convert it to string, so you can break it into list of digits

make a list of digits from the string you created (a list int python can be created from a string not an int, that's why you need the conversion to string first)

go trough that list of bits in reverse and multiply every bit by 2^k, k being the counter starting from 0

Here's the code that demonstrates what I just tried to explain:

user_input = int(input("enter a binary value"))

bits = list(str(user_input))

decimal = 0

counter = 0

for i in reversed(bits):
    decimal += 2**counter * int(i)
    counter+=1

print 'The decimal value is: ', decimal


问:
Yii2 : Active Record add Not In condition
What is the active Record way of adding IN condition to an active Query
in yii 1.x you could use CDbCriteria like this

```<code>$cr = new CDbCriteria();
$cr->addNotInCondition('attribute', $array);
</code>```

There seem to be no equivalent API call in yii2 active record implementation, how to do this via active record ?

答:
For me the only working solution was :</p>

```<code>$query = MyModel::find()->where('`your-attribute` NOT IN(' . implode(',', $array) . ')')->all();
</code>```

Body:
What is the active Record way of adding IN condition to an active Query
in yii 1.x you could use CDbCriteria like this

$cr = new CDbCriteria();
$cr->addNotInCondition('attribute', $array);

There seem to be no equivalent API call in yii2 active record implementation, how to do this via active record ?

Body:
For me the only working solution was :

$query = MyModel::find()->where('`your-attribute` NOT IN(' . implode(',', $array) . ')')->all();


问:
Unable to get PHP syntax right
I am unsure how to get the correct syntax to add in some php to this :

```<code>    $day = $workDays[$weekIndex][($col - 1) % 7] == TRUE ? '<SPAN class="' . $class . '"onclick="Materialize.toast(\'<?= "Hello World"\')" >' . $dkey  .'</SPAN>' : $dkey; // Defines SPAN to style related days, otherwise defaults
</code>```

The hello world echo is the part that I cant get right.

答:
The problem is that you're using ' to echo out the , and " for your onclick. While you are correctly escaping your apostrophes, you're not escaping your quotation marks (").

As such, your PHP string is evaluating as:

```<code>onclick="Materialize.toast(\'<?= "
</code>```

To remedy this, also place backslashes (\) in front of your quotation marks. Also note that you'll need a space before the onclick (to separate it from the class):

```<code>$day = $workDays[$weekIndex][($col - 1) % 7] == TRUE ?
'<SPAN class="' . $class . '" onclick="Materialize.toast(\'<?= \"Hello World\"\')" >'
. $dkey  .'</SPAN>' : $dkey; // Defines SPAN to style related days, otherwise defaults
</code>```

Hope this helps! :)

Title: Unable to get PHP syntax right

Body:
I am unsure how to get the correct syntax to add in some php to this :

    $day = $workDays[$weekIndex][($col - 1) % 7] == TRUE ? '<SPAN class="' . $class . '"onclick="Materialize.toast(\'<?= "Hello World"\')" >' . $dkey  .'' : $dkey; // Defines SPAN to style related days, otherwise defaults

The hello world echo is the part that I cant get right.

Body:
The problem is that you're using ' to echo out the <span>, and " for your onclick. While you are correctly escaping your apostrophes, you're not escaping your quotation marks (").

As such, your PHP string is evaluating as:

onclick="Materialize.toast(\'<?= "

To remedy this, also place backslashes (\) in front of your quotation marks. Also note that you'll need a space before the onclick (to separate it from the class):

$day = $workDays[$weekIndex][($col - 1) % 7] == TRUE ?
'<SPAN class="' . $class . '" onclick="Materialize.toast(\'<?= \"Hello World\"\')" >'
. $dkey  .'</SPAN>' : $dkey; // Defines SPAN to style related days, otherwise defaults

Hope this helps! :)


问:
Too much nested class in my Swing class
I needed to use these nested class because nested class can use the variable from the class been nested. How do I move these class to a something.java to simplify my code and the class still have the control of the gui class , such as Jlabel?

this is the cleaned version to show the important part

```<code>public class GUI {

        public GUI(){

            VitaminDEngineStarter vdes = new VitaminDEngineStarter();
            Registry registry = null;
            try {
                registry = LocateRegistry.getRegistry();
            } catch (RemoteException e1) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
            }

            try {
                vd = (VitaminD)registry.lookup(VitaminD.SERVICE_NAME);
            } catch(Exception e) {
                e.printStackTrace();
            }

            SMS a = new SMS(5);
            try {
                arduino.connect("COM3");
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            System.out.println("connecting:"+ a.connect());
            System.out.println("connected? :" + a.checkConnect());
            System.out.println("signal: "+a.checkSignal());
            System.out.println("deliver report :" + a.DeliveryReportOn());
            SMS.Read read = a.new Read(arduino);

        }

        class ShowSense implements Runnable {

            @Override
            public void run() {
                String[] temp;
                String light = "";
                String temperature = "";
                String hum = "";
                String sens = "";
                boolean humanact = false;

                // TODO Auto-generated method stub
                while (true){
                    try {
                        humanact = vd.gethumanActivity();
                    } catch (RemoteException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                    sens = arduino.getSensor();
                    temp = sens.split(",");
                    light = temp[1];
                    temperature = temp[0];
                    hum = temp[2];

                    LightIntensity.setText(light);
                    Temperature.setText(temperature);
                    humidity.setText(hum);

                    if (humanact){
                        personActivity.setText("in place");
                    }
                    else{
                        personActivity.setText("absent");
                    }

                }
            }

        }

        private JPanel getInputs() {
            if (Inputs == null) {
                personActivity = new JLabel();
                personActivity.setBounds(new Rectangle(114, 137, 77, 27));
                personActivity.setText("");
                personActivityLabel = new JLabel();
                personActivityLabel.setBounds(new Rectangle(7, 137, 99, 25));
                personActivityLabel.setText("Person Activity:");
                humidity = new JLabel();
                humidity.setBounds(new Rectangle(106, 91, 84, 27));
                humidity.setText("");
                humidityLabel = new JLabel();
                humidityLabel.setBounds(new Rectangle(6, 92, 88, 26));
                humidityLabel.setText("Humidity:");
                Temperature = new JLabel();
                Temperature.setBounds(new Rectangle(101, 50, 89, 30));
                Temperature.setText("");
                TemperatureLabel = new JLabel();
                TemperatureLabel.setBounds(new Rectangle(4, 50, 91, 30));
                TemperatureLabel.setText("Temperature:");
                LightIntensity = new JLabel();
                LightIntensity.setBounds(new Rectangle(110, 6, 84, 34));
                lightLabel = new JLabel();
                lightLabel.setBounds(new Rectangle(5, 5, 97, 34));
                lightLabel.setText("Light Intensity:");
                Inputs = new JPanel();
                Inputs.setLayout(null);
                Inputs.setBounds(new Rectangle(14, 63, 200, 183));
                Inputs.add(lightLabel, null);
                Inputs.add(LightIntensity, null);
                Inputs.add(TemperatureLabel, null);
                Inputs.add(Temperature, null);
                Inputs.add(humidityLabel, null);
                Inputs.add(humidity, null);
                Inputs.add(personActivityLabel, null);
                Inputs.add(personActivity, null);
                th.start();
            }
            return Inputs;
        }

        class autopilotthread implements Runnable{

            /** The temp. */
            private String[] temp;

            /** The lightintensty. */
            private double lightintensty ;

            /** The temperature. */
            private double temperature ;

            /** The hum. */
            private double hum ;

            /** The sens. */
            private String sens = null;

            /** The humanact. */
            private double humanact;

            /** The result. */
            private boolean [] result = {false , false};

            /** The fan. */
            private boolean fan =false;

            /** The light. */
            private boolean light = false;

            /** The pstop. */
            boolean pstop = false;

            /* (non-Javadoc)
             * @see java.lang.Runnable#run()
             */
            @Override
            public void run() {
                System.out.println("thread start!");
                while(true){
                    System.out.println("thread loop!");
                        try {
                            if(vd.gethumanActivity()){
                                humanact = 250;
                            }else{
                                humanact = 0;
                            }
                        } catch (RemoteException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        }
                        sens = arduino.getSensor();
                        temp = sens.split(",");
                        lightintensty = Double.parseDouble(temp[1]);
                        temperature = Double.parseDouble(temp[0]);
                        hum = Double.parseDouble(temp[2]);
                        double [] out ={humanact ,lightintensty , hum, Time.now(),temperature };
                        System.out.println(""+out[0]+" "+out[1]+" "+out[2]+" "+out[3]+" "+out[4]);
                        result = Matlab.output(out);
                        light = result[1];
                        fan = result[0];
                        System.out.println("light:" + light);
                        System.out.println("fan:" + fan );
                        if(light){
                            try {X10.lightsOn();}
                            catch (IOException e) {e.printStackTrace();}

                        }else{
                            try {X10.lightsOff();}
                            catch (IOException e) {e.printStackTrace();}

                        }

                        if(fan){
                            try {X10.fanOn();}
                            catch (IOException e) {e.printStackTrace();}

                        }else{
                            try {X10.fanOff();}
                            catch (IOException e) {e.printStackTrace();}

                        }

                    try {TimeUnit.SECONDS.sleep(10);}
                    catch (InterruptedException e) {e.printStackTrace();}

                    if (pstop){
                        break;
                    }
                }
                System.out.println("thread stop!");

            }

        }

        class Pilotmouse implements MouseListener{

            /** The p thread. */
            autopilotthread pThread = null;

            /** The pt. */
            Thread pt = null;

            /**
             * Instantiates a new pilotmouse.
             */
            Pilotmouse(){

            }

            /* (non-Javadoc)
             * @see java.awt.event.MouseListener#mouseClicked(java.awt.event.MouseEvent)
             */
            @Override
            public void mouseClicked(MouseEvent arg0) {
                // TODO Auto-generated method stub

            }

            /* (non-Javadoc)
             * @see java.awt.event.MouseListener#mouseEntered(java.awt.event.MouseEvent)
             */
            @Override
            public void mouseEntered(MouseEvent arg0) {
                // TODO Auto-generated method stub

            }

            /* (non-Javadoc)
             * @see java.awt.event.MouseListener#mouseExited(java.awt.event.MouseEvent)
             */
            @Override
            public void mouseExited(MouseEvent arg0) {
                // TODO Auto-generated method stub

            }

            /* (non-Javadoc)
             * @see java.awt.event.MouseListener#mousePressed(java.awt.event.MouseEvent)
             */
            @Override
            public void mousePressed(MouseEvent arg0) {
                // TODO Auto-generated method stub

            }

            /* (non-Javadoc)
             * @see java.awt.event.MouseListener#mouseReleased(java.awt.event.MouseEvent)
             */
            @Override
            public void mouseReleased(java.awt.event.MouseEvent e) {
                if ((autopilotlable.getText().equalsIgnoreCase("off"))){
                    autopilotlable.setText("on");
                    pThread = new autopilotthread();
                    pt = new Thread(pThread);
                    pt.start();

                } else if ((autopilotlable.getText().equalsIgnoreCase("on"))){
                    autopilotlable.setText("off");
                    pThread.pstop = true;
                }
            }

        }

        private JButton getAutopilot() {

            if (autopilot == null) {
                autopilot = new JButton();
                autopilot.setBounds(new Rectangle(18, 14, 112, 28));
                autopilot.setText("Auto Pilot");

                autopilot.addMouseListener(new Pilotmouse());
            }
            return autopilot;
        }

        public static void main(String[] args) {
            SwingUtilities.invokeLater(new Runnable() {
                public void run() {
                    GUI application = new GUI();
                    application.getJFrame().setVisible(true);
                }
            });

        }

    }
</code>```

答: You could use Eclipse's Refactor->Move Type to New File... to move some of the inner classes to their own file.</p>

Title: Too much nested class in my Swing class

Body:
I needed to use these nested class because nested class can use the variable from the class been nested. How do I move these class to a something.java to simplify my code and the class still have the control of the gui class , such as Jlabel?

this is the cleaned version to show the important part

public class GUI {

        public GUI(){

            VitaminDEngineStarter vdes = new VitaminDEngineStarter();
            Registry registry = null;
            try {
                registry = LocateRegistry.getRegistry();
            } catch (RemoteException e1) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
            }

            try {
                vd = (VitaminD)registry.lookup(VitaminD.SERVICE_NAME);
            } catch(Exception e) {
                e.printStackTrace();
            }

            SMS a = new SMS(5);
            try {
                arduino.connect("COM3");
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            System.out.println("connecting:"+ a.connect());
            System.out.println("connected? :" + a.checkConnect());
            System.out.println("signal: "+a.checkSignal());
            System.out.println("deliver report :" + a.DeliveryReportOn());
            SMS.Read read = a.new Read(arduino);

        }

        class ShowSense implements Runnable {

            @Override
            public void run() {
                String[] temp;
                String light = "";
                String temperature = "";
                String hum = "";
                String sens = "";
                boolean humanact = false;

                // TODO Auto-generated method stub
                while (true){
                    try {
                        humanact = vd.gethumanActivity();
                    } catch (RemoteException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                    sens = arduino.getSensor();
                    temp = sens.split(",");
                    light = temp[1];
                    temperature = temp[0];
                    hum = temp[2];

                    LightIntensity.setText(light);
                    Temperature.setText(temperature);
                    humidity.setText(hum);

                    if (humanact){
                        personActivity.setText("in place");
                    }
                    else{
                        personActivity.setText("absent");
                    }

                }
            }

        }

        private JPanel getInputs() {
            if (Inputs == null) {
                personActivity = new JLabel();
                personActivity.setBounds(new Rectangle(114, 137, 77, 27));
                personActivity.setText("");
                personActivityLabel = new JLabel();
                personActivityLabel.setBounds(new Rectangle(7, 137, 99, 25));
                personActivityLabel.setText("Person Activity:");
                humidity = new JLabel();
                humidity.setBounds(new Rectangle(106, 91, 84, 27));
                humidity.setText("");
                humidityLabel = new JLabel();
                humidityLabel.setBounds(new Rectangle(6, 92, 88, 26));
                humidityLabel.setText("Humidity:");
                Temperature = new JLabel();
                Temperature.setBounds(new Rectangle(101, 50, 89, 30));
                Temperature.setText("");
                TemperatureLabel = new JLabel();
                TemperatureLabel.setBounds(new Rectangle(4, 50, 91, 30));
                TemperatureLabel.setText("Temperature:");
                LightIntensity = new JLabel();
                LightIntensity.setBounds(new Rectangle(110, 6, 84, 34));
                lightLabel = new JLabel();
                lightLabel.setBounds(new Rectangle(5, 5, 97, 34));
                lightLabel.setText("Light Intensity:");
                Inputs = new JPanel();
                Inputs.setLayout(null);
                Inputs.setBounds(new Rectangle(14, 63, 200, 183));
                Inputs.add(lightLabel, null);
                Inputs.add(LightIntensity, null);
                Inputs.add(TemperatureLabel, null);
                Inputs.add(Temperature, null);
                Inputs.add(humidityLabel, null);
                Inputs.add(humidity, null);
                Inputs.add(personActivityLabel, null);
                Inputs.add(personActivity, null);
                th.start();
            }
            return Inputs;
        }

        class autopilotthread implements Runnable{

            /** The temp. */
            private String[] temp;

            /** The lightintensty. */
            private double lightintensty ;

            /** The temperature. */
            private double temperature ;

            /** The hum. */
            private double hum ;

            /** The sens. */
            private String sens = null;

            /** The humanact. */
            private double humanact;

            /** The result. */
            private boolean [] result = {false , false};

            /** The fan. */
            private boolean fan =false;

            /** The light. */
            private boolean light = false;

            /** The pstop. */
            boolean pstop = false;

            /* (non-Javadoc)
             * @see java.lang.Runnable#run()
             */
            @Override
            public void run() {
                System.out.println("thread start!");
                while(true){
                    System.out.println("thread loop!");
                        try {
                            if(vd.gethumanActivity()){
                                humanact = 250;
                            }else{
                                humanact = 0;
                            }
                        } catch (RemoteException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        }
                        sens = arduino.getSensor();
                        temp = sens.split(",");
                        lightintensty = Double.parseDouble(temp[1]);
                        temperature = Double.parseDouble(temp[0]);
                        hum = Double.parseDouble(temp[2]);
                        double [] out ={humanact ,lightintensty , hum, Time.now(),temperature };
                        System.out.println(""+out[0]+" "+out[1]+" "+out[2]+" "+out[3]+" "+out[4]);
                        result = Matlab.output(out);
                        light = result[1];
                        fan = result[0];
                        System.out.println("light:" + light);
                        System.out.println("fan:" + fan );
                        if(light){
                            try {X10.lightsOn();}
                            catch (IOException e) {e.printStackTrace();}

                        }else{
                            try {X10.lightsOff();}
                            catch (IOException e) {e.printStackTrace();}

                        }

                        if(fan){
                            try {X10.fanOn();}
                            catch (IOException e) {e.printStackTrace();}

                        }else{
                            try {X10.fanOff();}
                            catch (IOException e) {e.printStackTrace();}

                        }

                    try {TimeUnit.SECONDS.sleep(10);}
                    catch (InterruptedException e) {e.printStackTrace();}

                    if (pstop){
                        break;
                    }
                }
                System.out.println("thread stop!");

            }

        }

        class Pilotmouse implements MouseListener{

            /** The p thread. */
            autopilotthread pThread = null;

            /** The pt. */
            Thread pt = null;

            /**
             * Instantiates a new pilotmouse.
             */
            Pilotmouse(){

            }

            /* (non-Javadoc)
             * @see java.awt.event.MouseListener#mouseClicked(java.awt.event.MouseEvent)
             */
            @Override
            public void mouseClicked(MouseEvent arg0) {
                // TODO Auto-generated method stub

            }

            /* (non-Javadoc)
             * @see java.awt.event.MouseListener#mouseEntered(java.awt.event.MouseEvent)
             */
            @Override
            public void mouseEntered(MouseEvent arg0) {
                // TODO Auto-generated method stub

            }

            /* (non-Javadoc)
             * @see java.awt.event.MouseListener#mouseExited(java.awt.event.MouseEvent)
             */
            @Override
            public void mouseExited(MouseEvent arg0) {
                // TODO Auto-generated method stub

            }

            /* (non-Javadoc)
             * @see java.awt.event.MouseListener#mousePressed(java.awt.event.MouseEvent)
             */
            @Override
            public void mousePressed(MouseEvent arg0) {
                // TODO Auto-generated method stub

            }

            /* (non-Javadoc)
             * @see java.awt.event.MouseListener#mouseReleased(java.awt.event.MouseEvent)
             */
            @Override
            public void mouseReleased(java.awt.event.MouseEvent e) {
                if ((autopilotlable.getText().equalsIgnoreCase("off"))){
                    autopilotlable.setText("on");
                    pThread = new autopilotthread();
                    pt = new Thread(pThread);
                    pt.start();

                } else if ((autopilotlable.getText().equalsIgnoreCase("on"))){
                    autopilotlable.setText("off");
                    pThread.pstop = true;
                }
            }

        }

        private JButton getAutopilot() {

            if (autopilot == null) {
                autopilot = new JButton();
                autopilot.setBounds(new Rectangle(18, 14, 112, 28));
                autopilot.setText("Auto Pilot");

                autopilot.addMouseListener(new Pilotmouse());
            }
            return autopilot;
        }

        public static void main(String[] args) {
            SwingUtilities.invokeLater(new Runnable() {
                public void run() {
                    GUI application = new GUI();
                    application.getJFrame().setVisible(true);
                }
            });

        }

    }


问:
WSO2 Identity server not returning errors in login
I am using WSO2 Identity Server V 5.3.0. I am calling login operation in AuthenticationAdmin Service.

When the user is unlocked, it just returns false where as in the logs it prints User is unlocked.

How to know whether the user is locked or unlocked and send that as a response for login operation?

答: I couldn't remmeber the exact name of the Admin service. But there is a one adminservice where you can check the claim values of a particular claim. SO what you need to do is call that admin service and check for the isLocked claim value of the user. AFAIR service for RemoteUserStoreManager service. Check more information on https://docs.wso2.com/display/IS530/Locking+a+Specific+User+Account</p>


问:
Overwrite a Spark DataFrame into location
I want to save my Spark DataFrame into directory using spark_write_* function like this:

```<code>spark_write_csv(df, "file:///home/me/dir/")
</code>```

but if the directory is already there I will get error:

```<code>ERROR: org.apache.spark.sql.AnalysisException: path file:/home/me/dir/ already exists.;
</code>```

When I'm working on the same data, I want to overwrite this dir - how can I achieve this? In documentation there is one parameter:

```<code>mode  Specifies the behavior when data or table already exists.
</code>```

but it doesn't say what value you should use.

答:
Parameter mode should simply have value "overwrite":

```<code>spark_write_csv(df, "file:///home/me/dir/", mode = "overwrite")
</code>```

Body:
I want to save my Spark DataFrame into directory using spark_write_* function like this:

spark_write_csv(df, "file:///home/me/dir/")

but if the directory is already there I will get error:

ERROR: org.apache.spark.sql.AnalysisException: path file:/home/me/dir/ already exists.;

When I'm working on the same data, I want to overwrite this dir - how can I achieve this? In documentation there is one parameter:

mode  Specifies the behavior when data or table already exists.

but it doesn't say what value you should use.

Body:
Parameter mode should simply have value "overwrite":

spark_write_csv(df, "file:///home/me/dir/", mode = "overwrite")


问:
Formula using Variables with VBA
I am wrestling with the syntax of this one line of some code. the formula with "IfError" seems to have the wrong syntax. I believe I have the quotes in the right places. </p>

```<code>    Dim j As Integer
    Dim MidPointE As String
    Dim Dist As String
    Dim Allocation As String

    MidPointE = "AM"
    Dist = "AN"
    Allocation = "AO"

   for J= 1 to 300
     Cells(j, Dist).Formula = "=IFERROR(" & MidPointE & j & " / " & MidPointE &  CustomerLast & ", "")"
    Cells(j, Allocation).Formula = "=" & Allocation & j & "* S" & CustomerLast

     Next J
</code>```

答:
Try this:

```<code> Cells(j, Dist).Formula = "=IFERROR(" & MidPointE & j & " / " & MidPointE &  CustomerLast & ", """")"
</code>```

Quotes inside a string literal must be escaped - and that's done by doubling them up.

Title: Formula using Variables with VBA

Body:
I am wrestling with the syntax of this one line of some code. the formula with "IfError" seems to have the wrong syntax. I believe I have the quotes in the right places.

    Dim j As Integer
    Dim MidPointE As String
    Dim Dist As String
    Dim Allocation As String

    MidPointE = "AM"
    Dist = "AN"
    Allocation = "AO"

   for J= 1 to 300
     Cells(j, Dist).Formula = "=IFERROR(" & MidPointE & j & " / " & MidPointE &  CustomerLast & ", "")"
    Cells(j, Allocation).Formula = "=" & Allocation & j & "* S" & CustomerLast

     Next J

Body:
Try this:

 Cells(j, Dist).Formula = "=IFERROR(" & MidPointE & j & " / " & MidPointE &  CustomerLast & ", """")"

Quotes inside a string literal must be escaped - and that's done by doubling them up.


问:
Modifying hoverformat in plotly
How would I make it so that when hovering over a plotly graph, the displayed value in the hoverbox can be divided by 1000 and have a "K" appended to it?

For instance, when hovering over "$10,000,000" in a plotly graph, what could be done so that "$10,000K" is displayed in the box?

Specifically, can anything be done with the "hoverformat" property? It currently looks like this:

```<code>hoverformat: ",.0f"
</code>```

I'm aware that this prints a float with 0 decimal places...but how would I specify the displayed value to be divided by 1000 and then have a "K" appended?

Thanks.

答:
You might consider using numeral for that purpose. Numeral is a library used to format numbers and you can find it here:

http://numeraljs.com/

You then could do something like

```<code>const number = 10000;
const formattedNumber = numeral(10000).format('$ 0.00 a');
</code>```

Title: Modifying hoverformat in plotly

Body:
How would I make it so that when hovering over a plotly graph, the displayed value in the hoverbox can be divided by 1000 and have a "K" appended to it?

For instance, when hovering over "$10,000,000" in a plotly graph, what could be done so that "$10,000K" is displayed in the box?

Specifically, can anything be done with the "hoverformat" property? It currently looks like this:

hoverformat: ",.0f"

I'm aware that this prints a float with 0 decimal places...but how would I specify the displayed value to be divided by 1000 and then have a "K" appended?

Thanks.

Body:
You might consider using numeral for that purpose. Numeral is a library used to format numbers and you can find it here:

http://numeraljs.com/

You then could do something like

const number = 10000;
const formattedNumber = numeral(10000).format('$ 0.00 a');


问:
Program terminates after another class is called
I am trying to design a Java Program which offers multiple things like Calculator and tetris game and many more. Both Calculator and Tetris game are written in Swing having GUI, but the main program is CLI. it presents options like press 1 for calculator , press 2 for tetris, etc. but as soon as I press 1 calculator launches in another window and my main program terminates. I want a method that my main program still gives options like press 1 for calculator , press 2 for tetris, etc. even when I close the GUI Calculator or Tetris Window. here's what I'm trying to do:</p>

```<code>if (input == 1)
    {
        new Calc();
        mainScreen();
    }
else if (input == 2)
    {
        new Tetris();
        mainScreen();
    }
    .
    .
    .
    And So On
</code>```

答:
i would suggest adding an do{...}while(..); loop around your program so that it repeats the actions and you can add an exit command that quits the program</p>

```<code>    String input;
    do{
        input = getInput();
        if (input.equals("1")) {
            new Calc();
            mainScreen();
        } else if (input.equals("2")) {
            new Tetris();
            mainScreen();
        }
    }while(!input.equals("exit"));
</code>```

Body:
I am trying to design a Java Program which offers multiple things like Calculator and tetris game and many more. Both Calculator and Tetris game are written in Swing having GUI, but the main program is CLI. it presents options like press 1 for calculator , press 2 for tetris, etc. but as soon as I press 1 calculator launches in another window and my main program terminates. I want a method that my main program still gives options like press 1 for calculator , press 2 for tetris, etc. even when I close the GUI Calculator or Tetris Window. here's what I'm trying to do:

if (input == 1)
    {
        new Calc();
        mainScreen();
    }
else if (input == 2)
    {
        new Tetris();
        mainScreen();
    }
    .
    .
    .
    And So On

Body:
i would suggest adding an do{...}while(..); loop around your program so that it repeats the actions and you can add an exit command that quits the program

    String input;
    do{
        input = getInput();
        if (input.equals("1")) {
            new Calc();
            mainScreen();
        } else if (input.equals("2")) {
            new Tetris();
            mainScreen();
        }
    }while(!input.equals("exit"));


问:
display automatic date in input
I am making a invoices page and I want the date to appear automatically as an input as well as the date of expiration (30 days later)

is there an automatic function?

I have this:

TD

can value change to something like todaysdate??? or 30 days later??

help! :D

答:
You need to use DateTime::add method.</p>

```<code><?php

  $date = new DateTime('2011-01-01');
  $date->add(new DateInterval('P30D'));
  echo $date->format('Y-m-d') . "\n";

?>
</code>```

Title: display automatic date in input

Body:
You need to use DateTime::add method.

<?php

  $date = new DateTime('2011-01-01');
  $date->add(new DateInterval('P30D'));
  echo $date->format('Y-m-d') . "\n";

?>


问:
Ruby regex to match a space without a leading comma
How can I match a space without a leading comma?

My use case is I would like to split a string on space without a leading comma e.g. "id 10, 11"

答:
No need for a regex, just split twice:</p>

```<code>"id 10, 11".split(",").first.split #=> ["id", "10"]
</code>```

Body:
No need for a regex, just split twice:

"id 10, 11".split(",").first.split #=> ["id", "10"]


答:
It's at the end here

```<code>& ", "")"
</code>```

The two quotes between the comma and ) end the string and start a new one.

```<code>'first string
","

'second string
")"
</code>```

Since you can't just throw two strings together like that, i would replace the two quotes with the CHR equivalent. Should look something like this:

```<code>Cells(j, Dist).Formula = "=IFERROR(" & MidPointE & j & " / " & MidPointE &  CustomerLast & ", "& CHR(034) & CHR(034) & ")"
'pretty sure 034 is the ascii code for "
</code>```

Title: Formula using Variables with VBA

Body:
It's at the end here

& ", "")"

The two quotes between the comma and ) end the string and start a new one.

'first string
","

'second string
")"

Since you can't just throw two strings together like that, i would replace the two quotes with the CHR equivalent. Should look something like this:

Cells(j, Dist).Formula = "=IFERROR(" & MidPointE & j & " / " & MidPointE &  CustomerLast & ", "& CHR(034) & CHR(034) & ")"
'pretty sure 034 is the ascii code for "


问:
How can i forward email based on the email subject?
I need to forward emails coming from the Contact form 7 plugin to a group of users based on the email subject.

Lets say that i have an email with the subject "Services page form", now i need to forward this to an email services@example.com.

But if the email subject is "Contact page form", then i will forward it to contact@example.com. Are there any suggestions how this could be done?

If there are any other ways to do this are welcomed too.

答: Create different forms to use on each page. Each form you create has its own individual settings for email delivery etc.</p>


问:
DSVM - Visual Studio - R - cannot use an installed package
I am running an R script on Visual Studio in a DSVM. I ran into a problem installing a package (RODBC) that was already installed. I get this message:

package 'RODBC' successfully unpacked and MD5 sums checked
Warning: cannot remove prior installation of package 'RODBC'

And if I try to load the library I get the message that it doesn’t exist.

Error in base::library(...): there is no package called 'RODBC'

In package manager it’s available but not installed.

But in the library path, in file explorer, the package is there and I cannot delete it – always get the message that the folder is in use even if VS is closed. I tried changing the permissions to full control and still no luck.

Please let me know if you have any suggestion on how to fix this problem.
Many thanks.

答: Please check the R tools for Visual Studio (RTVS) options and see if the R Engine (64 bit) setting is empty. If it is empty, you need to set it to the directory where the Microsoft R (or ML Server on latest Windows 2016 edition of DSVM ) is installed.</p>