问:
Unable to find encoder for type stored in a Dataset
I want to get the DataSet with the following content:

```<code>111,Array([123,1],[222,3]
222,Array([333,3],[444,3]
</code>```

This is my code of Spark 2.2.0 and Scala 2.11:

```<code>val spark = SparkSession
                    .builder()
                    .appName("SparkSessionZipsExample")
                    .config("spark.sql.warehouse.dir", inputPath)
                    .enableHiveSupport()
                    .getOrCreate()

val df = spark.read.parquet(inputPath)
df.createOrReplaceTempView("sample_data")
val rows = spark.sql("SELECT * FROM sample_data")

val result = rows.map{ row: Row => {
     val pk = row.get(row.fieldIndex("pk")).toString.toLong

     val r = spark.sql("SELECT pk FROM sample_data WHERE pk != " + pk)
     val productList = r.rdd.map(r => r(0).toString.toLong).collect()

     (row.get(row.fieldIndex("pk")).toString.toLong, productList)
}}
</code>```

But I get this error:

```<code>error: Unable to find encoder for type stored in a Dataset.  Primitive types (Int, String, etc) and Product types (case classes) are supported by importing spark.implicits._  Support for serializing other types will be added in future releases.
[ERROR]       val result = rows.map{ row: Row => {
</code>```

I tried to import sqlContext.implicits._, but it does not compile.

In maven I have this dependency:

```<code>    <dependency>
        <groupId>org.apache.spark</groupId>
        <artifactId>spark-sql_2.11</artifactId>
        <version>2.2.0</version>
    </dependency>
</code>```

UPDATE:

Finally I imported the implicits as follows: import spark.implicits._, but I get this error in the runtime:

```<code>   java.lang.NullPointerException
        at org.apache.spark.sql.SparkSession.sessionState$lzycompute(SparkSession.scala:128)
        at org.apache.spark.sql.SparkSession.sessionState(SparkSession.scala:126)
        at org.apache.spark.sql.SparkSession.sql(SparkSession.scala:623)
        at org.test.Compute$$anonfun$1.apply(ComputeNumSim.scala:68)
        at org.test.Compute$$anonfun$1.apply(ComputeNumSim.scala:61)
        at scala.collection.Iterator$class.foreach(Iterator.scala:893)
        at scala.collection.AbstractIterator.foreach(Iterator.scala:1336)
        at org.apache.spark.rdd.RDD$$anonfun$foreach$1$$anonfun$apply$28.apply(RDD.scala:918)
        at org.apache.spark.rdd.RDD$$anonfun$foreach$1$$anonfun$apply$28.apply(RDD.scala:918)
        at org.apache.spark.SparkContext$$anonfun$runJob$5.apply(SparkContext.scala:2062)
        at org.apache.spark.SparkContext$$anonfun$runJob$5.apply(SparkContext.scala:2062)
        at org.apache.spark.scheduler.ResultTask.runTask(ResultTask.scala:87)
        at org.apache.spark.scheduler.Task.run(Task.scala:108)
        at org.apache.spark.executor.Executor$TaskRunner.run(Executor.scala:335)
        at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
        at java.lang.Thread.run(Thread.java:748)
</code>```

答:
You cannot store RDD in  Dataset or any other distributed collection in another distribute collection. You shouldn't be even possible to access DataFrame in map, but there seems to be an interesting loophole related to Datasets backed by local collections.

In this case you should join both Datasets by key:

```<code>rows.alias("rows").join(
  spark.table("sample_data").alias("sample"),
  $"rows.pk" =!= $"sample.pl"
)
</code>```

or more explicitly

```<code>rows.alias("rows")
  .crossJoin(spark.table("sample_data").alias("sample"))
  .where($"rows.pk" =!= $"sample.pk")
</code>```

Body:
I want to get the DataSet with the following content:

111,Array([123,1],[222,3]
222,Array([333,3],[444,3]

This is my code of Spark 2.2.0 and Scala 2.11:

val spark = SparkSession
                    .builder()
                    .appName("SparkSessionZipsExample")
                    .config("spark.sql.warehouse.dir", inputPath)
                    .enableHiveSupport()
                    .getOrCreate()

val df = spark.read.parquet(inputPath)
df.createOrReplaceTempView("sample_data")
val rows = spark.sql("SELECT * FROM sample_data")

val result = rows.map{ row: Row => {
     val pk = row.get(row.fieldIndex("pk")).toString.toLong

     val r = spark.sql("SELECT pk FROM sample_data WHERE pk != " + pk)
     val productList = r.rdd.map(r => r(0).toString.toLong).collect()

     (row.get(row.fieldIndex("pk")).toString.toLong, productList)
}}

But I get this error:

error: Unable to find encoder for type stored in a Dataset.  Primitive types (Int, String, etc) and Product types (case classes) are supported by importing spark.implicits._  Support for serializing other types will be added in future releases.
[ERROR]       val result = rows.map{ row: Row => {

I tried to import sqlContext.implicits._, but it does not compile.

In maven I have this dependency:

    <dependency>
        <groupId>org.apache.spark</groupId>
        <artifactId>spark-sql_2.11</artifactId>
        <version>2.2.0</version>
    </dependency>

UPDATE:

Finally I imported the implicits as follows: import spark.implicits._, but I get this error in the runtime:

   java.lang.NullPointerException
        at org.apache.spark.sql.SparkSession.sessionState$lzycompute(SparkSession.scala:128)
        at org.apache.spark.sql.SparkSession.sessionState(SparkSession.scala:126)
        at org.apache.spark.sql.SparkSession.sql(SparkSession.scala:623)
        at org.test.Compute$$anonfun$1.apply(ComputeNumSim.scala:68)
        at org.test.Compute$$anonfun$1.apply(ComputeNumSim.scala:61)
        at scala.collection.Iterator$class.foreach(Iterator.scala:893)
        at scala.collection.AbstractIterator.foreach(Iterator.scala:1336)
        at org.apache.spark.rdd.RDD$$anonfun$foreach$1$$anonfun$apply$28.apply(RDD.scala:918)
        at org.apache.spark.rdd.RDD$$anonfun$foreach$1$$anonfun$apply$28.apply(RDD.scala:918)
        at org.apache.spark.SparkContext$$anonfun$runJob$5.apply(SparkContext.scala:2062)
        at org.apache.spark.SparkContext$$anonfun$runJob$5.apply(SparkContext.scala:2062)
        at org.apache.spark.scheduler.ResultTask.runTask(ResultTask.scala:87)
        at org.apache.spark.scheduler.Task.run(Task.scala:108)
        at org.apache.spark.executor.Executor$TaskRunner.run(Executor.scala:335)
        at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
        at java.lang.Thread.run(Thread.java:748)

Body:
You cannot store RDD in  Dataset or any other distributed collection in another distribute collection. You shouldn't be even possible to access DataFrame in map, but there seems to be an interesting loophole related to Datasets backed by local collections.

In this case you should join both Datasets by key:

rows.alias("rows").join(
  spark.table("sample_data").alias("sample"),
  $"rows.pk" =!= $"sample.pl"
)

or more explicitly

rows.alias("rows")
  .crossJoin(spark.table("sample_data").alias("sample"))
  .where($"rows.pk" =!= $"sample.pk")


来源: stackexchange

问:
passing array and checking the values
While creating a group with user ids, I am checking if the entered id exists in database. If it exists, group should be created, if not it should pop out an error.

I am passing array with user ids to a function user_check, but it is not getting checked. Here is my code:

```<code><?php

    function user_check($user_id)
    {
        $u1 = mysqli_query($con, "SELECT uid from users where uid<>'" . $_SESSION['user_id'] . "'");
        while ($row = mysqli_fetch_array($u1)) {
            $users = $row['uid'];
            echo "users" . $users;
            $users1 = sort($users);
            $users2 = sort($user_id);
            printf($users1);
            if ($user1 == $user2) {
                echo "same";
            } else {
                echo "not same";
            }
        }
    }
</code>```

答:
Given a list of user_ids (that you have validated/filtered already) you could write a function something like the following (untested): </p>

```<code>function all_users_exist(array $user_ids, Mysqli $con)
{
    $result_uids = [];
    $ids         = implode(',', $user_ids);
    $sql         = "SELECT uid from users WHERE uid IN ($ids)";
    $result      = $con->query($sql);
    if($result)
        while ($row = $result->fetch_array(MYSQLI_ASSOC))
            $result_uids[] = $row['uid'];
    sort($user_ids);
    sort($result_uids);

    return $user_ids == $result_uids;
}
</code>```

ContentLicense: CC BY-SA 3.0

Title: passing array and checking the values

Body:
While creating a group with user ids, I am checking if the entered id exists in database. If it exists, group should be created, if not it should pop out an error.

I am passing array with user ids to a function user_check, but it is not getting checked. Here is my code:

<?php

    function user_check($user_id)
    {
        $u1 = mysqli_query($con, "SELECT uid from users where uid<>'" . $_SESSION['user_id'] . "'");
        while ($row = mysqli_fetch_array($u1)) {
            $users = $row['uid'];
            echo "users" . $users;
            $users1 = sort($users);
            $users2 = sort($user_id);
            printf($users1);
            if ($user1 == $user2) {
                echo "same";
            } else {
                echo "not same";
            }
        }
    }

Body:
Given a list of user_ids (that you have validated/filtered already) you could write a function something like the following (untested):

function all_users_exist(array $user_ids, Mysqli $con)
{
    $result_uids = [];
    $ids         = implode(',', $user_ids);
    $sql         = "SELECT uid from users WHERE uid IN ($ids)";
    $result      = $con->query($sql);
    if($result)
        while ($row = $result->fetch_array(MYSQLI_ASSOC))
            $result_uids[] = $row['uid'];
    sort($user_ids);
    sort($result_uids);

    return $user_ids == $result_uids;
}


问:
Convert existing rails column from string to array
I've an existing rails application and one of column's has existing semi-colon separated string. I want to convert the same into an array with an empty array as default.

Also, for rows which already have data in the semi-colon separated string format we need it to get converted into a proper array.

Database: psql or PostgreSQL

Framework: Rails 4.2

答:
I solved it like this:</p>

```<code>class ChangeQualificationToArray < ActiveRecord::Migration

  def change
    change_column :coaches, :qualifications, "varchar[] USING (string_to_array(qualifications, ';'))"
  end

end
</code>```

Body:
I solved it like this:

class ChangeQualificationToArray < ActiveRecord::Migration

  def change
    change_column :coaches, :qualifications, "varchar[] USING (string_to_array(qualifications, ';'))"
  end

end


问:
Bind Stroke from the property in ItemSources
I have a collection of the object say MyModel.cs. The collection is called Some. In MyModel it has a property Color which is Brush type.

The Color is Red for all now.

Now I have

```<code><MyControl: x:Name="control1" ItemsSource="{Binding Some}" Stroke="Red">
</code>```

But you see I hardcode the stroke. What I want is something like
     Stroke = "{Binding Some.Color}"

How?

答:
If MyControl inherits from Selector, set IsSynchronizedWithCurrentItem="True" and bind to Some/Color. The slash or virgule (/) means to use the Color property from the "current item" in the collection:

```<code><MyControl
    IsSynchronizedWithCurrentItem="True"
    x:Name="control1"
    ItemsSource="{Binding Some}"
    Stroke="{Binding Some/Color}"
    />
</code>```

This will use the selected item's Color brush for Stroke. You're quite understandably reluctant to provide any hints about what you're trying to do, but that's a fair guess.

If MyControl does not inherit from Selector, use mm8's solution.

Body:
I have a collection of the object say MyModel.cs. The collection is called Some. In MyModel it has a property Color which is Brush type.

The Color is Red for all now.

Now I have

<MyControl: x:Name="control1" ItemsSource="{Binding Some}" Stroke="Red">

But you see I hardcode the stroke. What I want is something like
     Stroke = "{Binding Some.Color}"

How?

Body:
If MyControl inherits from Selector, set IsSynchronizedWithCurrentItem="True" and bind to Some/Color. The slash or virgule (/) means to use the Color property from the "current item" in the collection:

<MyControl
    IsSynchronizedWithCurrentItem="True"
    x:Name="control1"
    ItemsSource="{Binding Some}"
    Stroke="{Binding Some/Color}"
    />

This will use the selected item's Color brush for Stroke. You're quite understandably reluctant to provide any hints about what you're trying to do, but that's a fair guess.

If MyControl does not inherit from Selector, use mm8's solution.


问:
Instantiating view frame so that it fits with navigation bar / tab bar?
I have an app where sometimes views are in navigation controllers, sometimes not, and sometimes in a tab bar and navigation controller.

I create my views programatically using code such as this:

```<code>let contact = ContactFormViewController(contactFormView: ContactFormView.init(frame: UIScreen.main.bounds))
</code>```

however this is causing frames to always be as large as the screen, meaning when there is a navigation bar or tab bar the view is pushed off the visible screen and doesnt fit.

Is there a method to adapt the view height to always show it all on screen regardless of parent elements like the nav bar or tab bar? or would it be a case of always creating views with manual subtractions like this, which seems poor as it needs to assume hardcoded elements:

```<code>let attendees = AttendeesViewController(attendeesView: AttendeesView.init(frame: CGRect(x: 0, y: 0, width: UIScreen.main.bounds.width, height: UIScreen.main.bounds.height-55)))
</code>```

thanks for any guidance as its a major issue in my app

答: The solution was to set the frame to CGRect.zero and then in the init method of the controller, apply layout constraints to the view class to map it to self.view

Body:
I have an app where sometimes views are in navigation controllers, sometimes not, and sometimes in a tab bar and navigation controller.

I create my views programatically using code such as this:

let contact = ContactFormViewController(contactFormView: ContactFormView.init(frame: UIScreen.main.bounds))

however this is causing frames to always be as large as the screen, meaning when there is a navigation bar or tab bar the view is pushed off the visible screen and doesnt fit.

Is there a method to adapt the view height to always show it all on screen regardless of parent elements like the nav bar or tab bar? or would it be a case of always creating views with manual subtractions like this, which seems poor as it needs to assume hardcoded elements:

let attendees = AttendeesViewController(attendeesView: AttendeesView.init(frame: CGRect(x: 0, y: 0, width: UIScreen.main.bounds.width, height: UIScreen.main.bounds.height-55)))

thanks for any guidance as its a major issue in my app


问:
Two pseudo elements ::before with different properties
Used two pseudo elements ::before with different border properties (see js fiddle). Despite "you can use only one ::before and one ::after pseudo element" this actualy worked. Why?

https://jsfiddle.net/8L7zou3e/1/

```<code>.el {
    position: relative;
    margin: 100px 0 0 500px;
    width: 300px;
    height: 100px;
    background-color: #AA4343;
}
.el:before {
    content: '';
    display: inline-block;
    width: 0;
    height: 0;
    border-top: 50px solid #e86d0a;
    border-left: 50px solid transparent;
    position: absolute;
    top: 0;
    left: -50px;
}

.el:before {
    content: '';
    display: inline-block;
    width: 0;
    height: 0;
    border-bottom: 50px solid #e86d0a;
    border-left: 50px solid transparent;
    position: absolute;
    top: 0px;
    left: -50px;
}
</code>```

答:
You seem to have only one pseudo element.

And that's here in the UI:

Your CSS cascades to:

.el:before {
  content: '';
  display: inline-block;
  width: 0;
  height: 0;
  border-top: 50px solid #e86d0a;
  border-left: 50px solid transparent;
  position: absolute;
  border-bottom: 50px solid #e86d0a;
  border-left: 50px solid transparent;
  top: 0;
  left: -50px;
}
```

See the way Chrome has treated your combined CSS:

Body:
Used two pseudo elements ::before with different border properties (see js fiddle). Despite "you can use only one ::before and one ::after pseudo element" this actualy worked. Why?

https://jsfiddle.net/8L7zou3e/1/

.el {
    position: relative;
    margin: 100px 0 0 500px;
    width: 300px;
    height: 100px;
    background-color: #AA4343;
}
.el:before {
    content: '';
    display: inline-block;
    width: 0;
    height: 0;
    border-top: 50px solid #e86d0a;
    border-left: 50px solid transparent;
    position: absolute;
    top: 0;
    left: -50px;
}

.el:before {
    content: '';
    display: inline-block;
    width: 0;
    height: 0;
    border-bottom: 50px solid #e86d0a;
    border-left: 50px solid transparent;
    position: absolute;
    top: 0px;
    left: -50px;
}

Body:
You seem to have only one pseudo element.

And that's here in the UI:

Your CSS cascades to:

.el:before {
  content: '';
  display: inline-block;
  width: 0;
  height: 0;
  border-top: 50px solid #e86d0a;
  border-left: 50px solid transparent;
  position: absolute;
  border-bottom: 50px solid #e86d0a;
  border-left: 50px solid transparent;
  top: 0;
  left: -50px;
}

See the way Chrome has treated your combined CSS:


问:
Making Junit Reuse Tomcat context.xml
I am not an expert in java but right now I have inherited some code that I need to make work. My goal is to run the source test suite. The (creation of the) beans needed for the tests require some environment settings. These settings are in tomcat-root-dir/conf/context.xml. These environment settings are used by tomcat to deploy the web application.

I want to reuse tomcat-root-dir/conf/context.xml with junit, or otherwise make the testsuite work. Is there some standard way to parse context.xml for junit? I would appreciate if you could help me with this.

答:
TomcatJNDI solves this problem. It can process Tomcat's configuration files and creates the same JNDI environment as Tomcat does, but without starting a server. So you can run classes with dependencies on Tomcat's JNDI environment in e. g. JUnit tests.

```<code>TomcatJNDI tomcatJNDI = new TomcatJNDI();
tomcatJNDI.processContextXml(new File("tomcat-root-dir/conf/context.xml");
tomcatJNDI.start();
</code>```

Then your classes can lookup the DataSource as when they would run in Tomcat.

More about TomcatJNDI can be found here.

ContentLicense: CC BY-SA 2.5

Title: Making Junit Reuse Tomcat context.xml

Body:
TomcatJNDI solves this problem. It can process Tomcat's configuration files and creates the same JNDI environment as Tomcat does, but without starting a server. So you can run classes with dependencies on Tomcat's JNDI environment in e. g. JUnit tests.

TomcatJNDI tomcatJNDI = new TomcatJNDI();
tomcatJNDI.processContextXml(new File("tomcat-root-dir/conf/context.xml");
tomcatJNDI.start();

Then your classes can lookup the DataSource as when they would run in Tomcat.

More about TomcatJNDI can be found here.


问:
Most efficient way to find the index of the only '1' bit in a char variable (in C)
This is an interview question:

You are given a char variable named ch, when you know that it represents a number that in its binary form, only one of its eight bits will be equal to '1'. I.E. , the only possible values for ch are: 0x1, 0x2, 0x4, 0x8, 0x10, 0x20, 0x40, 0x80.

Given the variable ch, I need to write the most efficient code to get the index of that '1' bit. For example: if ch == 0x1 -> result is 0. if ch == 0x4 -> result is 2.

The obvious way is to use switch-case, but I need something more efficient.

Is there any bit manipulation you can do here for efficient implementation?

答:
write the most efficient code to get the index of that '1' bit.

The most efficient code would be to somehow map the value of ch to its bit index, i.e.:

```<code>0x01 -> 0
0x02 -> 1
0x04 -> 2
0x08 -> 3
...
</code>```

Naive Mapping Table

The most simple and naive solution would require a lookup in a mapping table with all possible values of ch. For 8-bit numbers (char) we need a table with 28= 256 elements:

```<code>char naive_table[256];

naive_table[0x01] = 0;
naive_table[0x02] = 1;
naive_table[0x04] = 2;
naive_table[0x08] = 3;
naive_table[0x10] = 4;
naive_table[0x20] = 5;
naive_table[0x40] = 6;
naive_table[0x80] = 7;
</code>```

The lookup in this table is also simple:

```<code>index = naive_table[ch];
</code>```

Hash Function + Mapping Table

The previous solution is simple and fast, but most of the element of naive_table are wasted. Taking into account that ch is a power of two, for any n-bit number there are just n possible indexes.

So, instead of using a mapping table with 28 elements, we could use a table with just 8 elements and a hash function which would map the value of ch to a unique index of the mapping table.

The perfect candidate for such a hash function would be a function using the de Bruijn sequence. There is a paper "Using de Bruijn Sequences to Index a 1 in a Computer Word" which states:

A length-n de Bruijn sequence, where n is an exact power of 2, is a cyclic sequence of n 0's and 1's such that every 0-1 sequence of length lg n occurs exactly once as a contiguous substring.

For example, a length-8 de Bruijn sequence is 00011101. Each 3-bit number occurs exactly once as a contiguous substring: starting from the leftmost 3 bits and moving a 3-bit window right one bit at a time, we have 000, 001, 011, 111, 110, 101, 010 (wrapping around), 100 (also wrapping around).

The hash function is computed by: h(x)=(x * deBruijn)>>(n - lg n)

So, let us try this hash function to get a unique index in our compact lookup table:

```<code>h(ch) = ((ch * 00011101b) >> (8 - 3)) & 0x7
h(ch) = ((ch * 29) >> 5) & 0x7
</code>```

Let us calculate the hashes for all values of ch and make sure the hash function works as expected, i.e. all the hashes are unique:

```<code>ch    h(ch)
0x01  ((1 * 29) >> 5) & 0x7 = 0
0x02  ((2 * 29) >> 5) & 0x7 = 1
0x04  ((4 * 29) >> 5) & 0x7 = 3
0x08  ((8 * 29) >> 5) & 0x7 = 7
0x10  ((16 * 29) >> 5) & 0x7 = 6
0x20  ((32 * 29) >> 5) & 0x7 = 5
0x40  ((64 * 29) >> 5) & 0x7 = 2
0x80  ((64 * 29) >> 5) & 0x7 = 4
</code>```

So the hash function works fine and produces unique hashes for each power of two value of ch.

Now let us create a compact mapping table using the hash values from the table above:

```<code>char compact_table[8];

compact_table[0] = 0;
compact_table[1] = 1;
compact_table[3] = 2;
compact_table[7] = 3;
compact_table[6] = 4;
compact_table[5] = 5;
compact_table[2] = 6;
compact_table[4] = 7;
</code>```

Now for the lookup we use a hash value as an index:

```<code>h = ((ch * 29) >> 5) & 0x7;
index = compact_table[h];
</code>```

Hash Function + Bit String

The previous version is nearly perfect: there are no more wasted elements in the mapping table. But since all the indexes are within 0-7 (i.e. just 3-bit values), there is still a room for improvement. Let us use a bit string instead of the mapping table so the most significant bits of each element are not wasted.

First, let us create such a bit string using all the values of ch and the hash values from the previous version:

```<code>ch    h(sh)  index
0x01  0      0 (000b)
0x02  1      1 (001b)
0x04  3      2 (010b)
0x08  7      3 (011b)
0x10  6      4 (100b)
0x20  5      5 (101b)
0x40  2      6 (110b)
0x80  4      7 (111b)
</code>```

Now let us order this table by the hash value:

```<code>ch    h(sh)  index
0x01  0      0 (000b)
0x02  1      1 (001b)
0x40  2      6 (110b)
0x04  3      2 (010b)
0x80  4      7 (111b)
0x20  5      5 (101b)
0x10  6      4 (100b)
0x08  7      3 (011b)
</code>```

So the bit string will be a reversed concatenation of those 3-bit indexes:

```<code>011 100 101 111 010 110 001 000 = 0x72f588
</code>```

Now let us lookup in this bit string just like we did previously. Note that our indexes are 3-bit, so we need to multiply our hash value by 3:

```<code>char naive_table[256];

naive_table[0x01] = 0;
naive_table[0x02] = 1;
naive_table[0x04] = 2;
naive_table[0x08] = 3;
naive_table[0x10] = 4;
naive_table[0x20] = 5;
naive_table[0x40] = 6;
naive_table[0x80] = 7;
</code>```0

Or in short:

```<code>char naive_table[256];

naive_table[0x01] = 0;
naive_table[0x02] = 1;
naive_table[0x04] = 2;
naive_table[0x08] = 3;
naive_table[0x10] = 4;
naive_table[0x20] = 5;
naive_table[0x40] = 6;
naive_table[0x80] = 7;
</code>```1

There are no divisions/modulos/conditions in the code, so it should perform fast on any CPU.

The prove of concept code:

```<code>char naive_table[256];

naive_table[0x01] = 0;
naive_table[0x02] = 1;
naive_table[0x04] = 2;
naive_table[0x08] = 3;
naive_table[0x10] = 4;
naive_table[0x20] = 5;
naive_table[0x40] = 6;
naive_table[0x80] = 7;
</code>```2

Body:
write the most efficient code to get the index of that '1' bit.

The most efficient code would be to somehow map the value of ch to its bit index, i.e.:

0x01 -> 0
0x02 -> 1
0x04 -> 2
0x08 -> 3
...

Naive Mapping Table

The most simple and naive solution would require a lookup in a mapping table with all possible values of ch. For 8-bit numbers (char) we need a table with 28= 256 elements:

char naive_table[256];

naive_table[0x01] = 0;
naive_table[0x02] = 1;
naive_table[0x04] = 2;
naive_table[0x08] = 3;
naive_table[0x10] = 4;
naive_table[0x20] = 5;
naive_table[0x40] = 6;
naive_table[0x80] = 7;

The lookup in this table is also simple:

index = naive_table[ch];

Hash Function + Mapping Table

The previous solution is simple and fast, but most of the element of naive_table are wasted. Taking into account that ch is a power of two, for any n-bit number there are just n possible indexes.

So, instead of using a mapping table with 28 elements, we could use a table with just 8 elements and a hash function which would map the value of ch to a unique index of the mapping table.

The perfect candidate for such a hash function would be a function using the de Bruijn sequence. There is a paper "Using de Bruijn Sequences to Index a 1 in a Computer Word" which states:

A length-n de Bruijn sequence, where n is an exact power of 2, is a cyclic sequence of n 0's and 1's such that every 0-1 sequence of length lg n occurs exactly once as a contiguous substring.

For example, a length-8 de Bruijn sequence is 00011101. Each 3-bit number occurs exactly once as a contiguous substring: starting from the leftmost 3 bits and moving a 3-bit window right one bit at a time, we have 000, 001, 011, 111, 110, 101, 010 (wrapping around), 100 (also wrapping around).

The hash function is computed by: h(x)=(x * deBruijn)>>(n - lg n)

So, let us try this hash function to get a unique index in our compact lookup table:

h(ch) = ((ch * 00011101b) >> (8 - 3)) & 0x7
h(ch) = ((ch * 29) >> 5) & 0x7

Let us calculate the hashes for all values of ch and make sure the hash function works as expected, i.e. all the hashes are unique:

ch    h(ch)
0x01  ((1 * 29) >> 5) & 0x7 = 0
0x02  ((2 * 29) >> 5) & 0x7 = 1
0x04  ((4 * 29) >> 5) & 0x7 = 3
0x08  ((8 * 29) >> 5) & 0x7 = 7
0x10  ((16 * 29) >> 5) & 0x7 = 6
0x20  ((32 * 29) >> 5) & 0x7 = 5
0x40  ((64 * 29) >> 5) & 0x7 = 2
0x80  ((64 * 29) >> 5) & 0x7 = 4

So the hash function works fine and produces unique hashes for each power of two value of ch.

Now let us create a compact mapping table using the hash values from the table above:

char compact_table[8];

compact_table[0] = 0;
compact_table[1] = 1;
compact_table[3] = 2;
compact_table[7] = 3;
compact_table[6] = 4;
compact_table[5] = 5;
compact_table[2] = 6;
compact_table[4] = 7;

Now for the lookup we use a hash value as an index:

h = ((ch * 29) >> 5) & 0x7;
index = compact_table[h];

Hash Function + Bit String

The previous version is nearly perfect: there are no more wasted elements in the mapping table. But since all the indexes are within 0-7 (i.e. just 3-bit values), there is still a room for improvement. Let us use a bit string instead of the mapping table so the most significant bits of each element are not wasted.

First, let us create such a bit string using all the values of ch and the hash values from the previous version:

ch    h(sh)  index
0x01  0      0 (000b)
0x02  1      1 (001b)
0x04  3      2 (010b)
0x08  7      3 (011b)
0x10  6      4 (100b)
0x20  5      5 (101b)
0x40  2      6 (110b)
0x80  4      7 (111b)

Now let us order this table by the hash value:

ch    h(sh)  index
0x01  0      0 (000b)
0x02  1      1 (001b)
0x40  2      6 (110b)
0x04  3      2 (010b)
0x80  4      7 (111b)
0x20  5      5 (101b)
0x10  6      4 (100b)
0x08  7      3 (011b)

So the bit string will be a reversed concatenation of those 3-bit indexes:

011 100 101 111 010 110 001 000 = 0x72f588

Now let us lookup in this bit string just like we did previously. Note that our indexes are 3-bit, so we need to multiply our hash value by 3:

h = ((ch * 29) >> 5) & 0x7; // just like before
bit_string = 0x72f588;
index = (bit_string >> (h * 3)) & 0x7;

Or in short:

index = (0x72f588 >> ((((ch * 29) >> 5) & 0x7) * 3)) & 0x7;

There are no divisions/modulos/conditions in the code, so it should perform fast on any CPU.

The prove of concept code:

unsigned char ch;
for (ch = 1; ch; ch <<= 1) {
        int index = (0x72f588 >> ((((ch * 29) >> 5) & 7) * 3)) & 7;
        printf("ch = 0x%02x index = %d\n", ch, index);
}
return 0;


问:
How to extract the month, day of month and IP address from the line using sed or awk?
I have extracted the day/month and IP that are continuously bruteforcing my IMAP server:

```<code>Nov1 unknown[186.216.99.239]:
Nov1 unknown[62.249.196.214]:
Nov1 unknown[110.145.123.120]:
Nov1 fixed-187-190-251-149.totalplay.net[187.190.251.149]:
Nov1 pd9568164.dip0.t-ipconnect.de[217.86.129.100]:
Nov1 unknown[103.227.88.130]:
</code>```

I want the output to be like below:

```<code>Nov1 186.216.99.239
Nov1 62.249.196.214
Nov1 110.145.123.120
Nov1 187.190.251.149
Nov1 217.86.129.100
Nov1 103.227.88.130
</code>```

I achieved this result using combination of sed, awk and cut with below code, but I would like to learn if there are better ways?

```<code>while read -r line
    do
        monthday=$(echo $line | awk '{ print $1 }')
        # ip=$(echo $line | awk -F'[\\\[\\\]]' { print $2 } )
        ip=$(echo $line| cut -d[ -f2| cut -d] -f1 )
        echo "${monthday} ${ip}"
    done < badIpList.txt
</code>```

答:
try this

```<code>sed -E 's/\s.*\[(.*)\]:/ \1/' file
</code>```

no loops needed.

Body:
I have extracted the day/month and IP that are continuously bruteforcing my IMAP server:

Nov1 unknown[186.216.99.239]:
Nov1 unknown[62.249.196.214]:
Nov1 unknown[110.145.123.120]:
Nov1 fixed-187-190-251-149.totalplay.net[187.190.251.149]:
Nov1 pd9568164.dip0.t-ipconnect.de[217.86.129.100]:
Nov1 unknown[103.227.88.130]:

I want the output to be like below:

Nov1 186.216.99.239
Nov1 62.249.196.214
Nov1 110.145.123.120
Nov1 187.190.251.149
Nov1 217.86.129.100
Nov1 103.227.88.130

I achieved this result using combination of sed, awk and cut with below code, but I would like to learn if there are better ways?

while read -r line
    do
        monthday=$(echo $line | awk '{ print $1 }')
        # ip=$(echo $line | awk -F'[\\\[\\\]]' { print $2 } )
        ip=$(echo $line| cut -d[ -f2| cut -d] -f1 )
        echo "${monthday} ${ip}"
    done < badIpList.txt

Body:
try this

sed -E 's/\s.*\[(.*)\]:/ \1/' file

no loops needed.


问:
Count distinct id with case
So say I have a list IDs with values, like so:

```<code>ID  VALUE
1   A
1   NULL
1   B
2   NULL
3   A
</code>```

And I want to count distinct ID for values that equal A OR B (at least one)

The answer should be 2, since there are 2 IDs that have either A or B value.

If I do a COUNT(DISTINCT(CASE WHEN ... I'm unable to get the unique IDs.

Is there another solution?

答:
You should be able to filter for values A or B, and then count the distinct Ids listed, as below:</p>

```<code>declare @t table (id int not null,
                  value char(1) null);

insert into @t
values
(1,'A'),
(1,NULL),
(1,'B'),
(2,NULL),
(3,'A');

select
   count(distinct id)
from @t
where value in ('A','B');
</code>```

Title: Count distinct id with case

Body:
So say I have a list IDs with values, like so:

ID  VALUE
1   A
1   NULL
1   B
2   NULL
3   A

And I want to count distinct ID for values that equal A OR B (at least one)

The answer should be 2, since there are 2 IDs that have either A or B value.

If I do a COUNT(DISTINCT(CASE WHEN ... I'm unable to get the unique IDs.

Is there another solution?

Body:
You should be able to filter for values A or B, and then count the distinct Ids listed, as below:

declare @t table (id int not null,
                  value char(1) null);

insert into @t
values
(1,'A'),
(1,NULL),
(1,'B'),
(2,NULL),
(3,'A');

select
   count(distinct id)
from @t
where value in ('A','B');


问:
Using initializer list for a struct with inheritance
I have a struct that I'd like to initialize using an initializer list

```<code>struct Parent{};

struct Child : private Parent {
    int b;
};

int main() {
    Child c{ 1 };
    return 0;
}
</code>```

Looking at other questions I found this answer that states that it should be possible in c++17.

However when I try the above snippet in VS2017 I get

```<code>Error   C2440   'initializing': cannot convert from 'initializer list' to 'child'
</code>```

Is there any way to utilize this new feature?

答:
With inheritance, each base class subobject of the aggregate is initialized like a member. So to aggregate initialization, Child has two subobjects: Parent, and i. So you need two initializers in your braced-init-list:

```<code>Child c{ {}, 1 };
</code>```

Also, in order for Child to be an aggregate, all subobjects must be public. So you can't have private base classes.

Of course, this assumes that Visual Studio implements the feature correctly. VS2017 15.5 is not C++17 compliant, but 15.7 supports this.

Body:
I have a struct that I'd like to initialize using an initializer list

struct Parent{};

struct Child : private Parent {
    int b;
};

int main() {
    Child c{ 1 };
    return 0;
}

Looking at other questions I found this answer that states that it should be possible in c++17.

However when I try the above snippet in VS2017 I get

Error   C2440   'initializing': cannot convert from 'initializer list' to 'child'

Is there any way to utilize this new feature?

Body:
With inheritance, each base class subobject of the aggregate is initialized like a member. So to aggregate initialization, Child has two subobjects: Parent, and i. So you need two initializers in your braced-init-list:

Child c{ {}, 1 };

Also, in order for Child to be an aggregate, all subobjects must be public. So you can't have private base classes.

Of course, this assumes that Visual Studio implements the feature correctly. VS2017 15.5 is not C++17 compliant, but 15.7 supports this.

ContentLicense: CC BY-SA 4.0


问:
How to add all the values of a map without using recurrsion or var
I want to add all the values in a map without using var or any mutable structures. I have tried to do something like this but it doens't work:

```<code>val mymap = ("a" -> 1, "b" -> 2)
    val sum_of_alcohol_consumption =
    for ((k,v) <- mymap ) yield (sum_of_alcohol_consumption += v)
</code>```

I have been told that I can use .sum on a list
Please help

Thanks

答:
You can use the .values function of a Map to return an Iterable List of its values (all of the Integers) and then call the .sum function on that:

```<code>val myMap = Map("a" -> 1, "b" -> 2)
val sum = myMap.values.sum
println(sum) // Outputs: 3
</code>```

Body:
I want to add all the values in a map without using var or any mutable structures. I have tried to do something like this but it doens't work:

val mymap = ("a" -> 1, "b" -> 2)
    val sum_of_alcohol_consumption =
    for ((k,v) <- mymap ) yield (sum_of_alcohol_consumption += v)

I have been told that I can use .sum on a list
Please help

Thanks

Body:
You can use the .values function of a Map to return an Iterable List of its values (all of the Integers) and then call the .sum function on that:

val myMap = Map("a" -> 1, "b" -> 2)
val sum = myMap.values.sum
println(sum) // Outputs: 3


问:
Distribution function in ERC20 token which can be executed on a later stage?
I need to implement Distribute function in ERC20 token code which will send equal amount of the tokens on an array of addresses when executed. Below is the source code that I will use for that. Of course I will change the variables for my token:

https://pastebin.com/wAe9a1EV

Is the Distribute function that I add at the end of the contract suitable and does not interfere with the rest of the source code? Can I execute distributions on a later stage through Myetherwallet or Mist with that function if I deploy the contract with that function on the blockchain?

```<code> function distributeToken(address[] addresses, uint256 _value) onlyOwner{
 for (uint i = 0; i < addresses.length; i++) {
 balances[owner] -= _value;
 balances[addresses[i]] += _value;
 Transfer(owner, addresses[i], _value);
 }
}
</code>```

答:
It is best to have a claim function and have users call the function to get their tokens as opposed to having an owner try to distribute them. The amount of gas the owner has to pay to distribute the tokens would be breathtaking.

Possibly giving out tokens as soon as a hser has sent ether to the contract is better solution.

Body:
I need to implement Distribute function in ERC20 token code which will send equal amount of the tokens on an array of addresses when executed. Below is the source code that I will use for that. Of course I will change the variables for my token:

https://pastebin.com/wAe9a1EV

Is the Distribute function that I add at the end of the contract suitable and does not interfere with the rest of the source code? Can I execute distributions on a later stage through Myetherwallet or Mist with that function if I deploy the contract with that function on the blockchain?

 function distributeToken(address[] addresses, uint256 _value) onlyOwner{
 for (uint i = 0; i < addresses.length; i++) {
 balances[owner] -= _value;
 balances[addresses[i]] += _value;
 Transfer(owner, addresses[i], _value);
 }
}


问:
Capturing the text of the closest span element with a specific class
I'm trying to fetch the text of a span that has a given class -> closest to the click via Google Tag Manager. Is it possible via plain JS or JQuery?

The code looks like this:

```<code><a class="contenttile" href="/mypage" style="height: 193px;">
  <div class="imageContainer" style="height: 97px;">
    <img src="http://http:someadress.com/foto.jpg" class="blurr" alt="">
  </div>
  <div class="textContainer">
    <span class="text3">My text</span>
    <br>
  </div>
</a>
</code>```

What I want to return via a function is My text.

I was trying different snippets found here, but since im a JS lame I couldn't adjust it to work properly.

For example this one:

```<code>function(){
  var ec = {{Click Element}};
  var x = $(ec).closest('span');
  return x.innerText;
}
</code>```

答:
In GTM, your click may register two events: gtm.click and gtm.linkClick. Depending on which one your tag is set to fire on (ie. you can set it to fire on all clicks or just links), then you could use either of the following:

If using just links, then $(ce).find('.textContainer').find('span').text()

If using all clicks, then $(ce).closest('span').text()

Body:
I'm trying to fetch the text of a span that has a given class -> closest to the click via Google Tag Manager. Is it possible via plain JS or JQuery?

The code looks like this:

    My text

What I want to return via a function is My text.

I was trying different snippets found here, but since im a JS lame I couldn't adjust it to work properly.

For example this one:

function(){
  var ec = {{Click Element}};
  var x = $(ec).closest('span');
  return x.innerText;
}


问:
How to add an object to file every time i run my program in java
I Have 3 objects of Person type and i write them to my file Person.person and than i read them one by one but when i run my program again i get the same 3 objets written as when i run it for the firts time.How to add those 3 objects to  my file again and again every time i run my program.I want from it to be the same 3 objects or some other objects but they need to be added to the end of my file.

And how to get that data when i want to read that file?

```<code> package pisanjeUFajl;

 import java.io.BufferedInputStream;
 import java.io.BufferedOutputStream;
 import java.io.EOFException;
 import java.io.File;
 import java.io.FileInputStream;
 import java.io.FileOutputStream;
 import java.io.IOException;
 import java.io.ObjectInputStream;
 import java.io.ObjectOutputStream;
 import java.util.List;

 public class Serilizacija {
 public static void main(String[] args) throws IOException,
 ClassNotFoundException {

    Person person = new Person("Jovan", "Dukic");
    Person person2 = new Person("Stanko", "Maca");
    Person person3 = new Person("Tole", "Lopove");

    File file = new File("C:\\Users\\Jovan\\Desktop\\Person.person");
    if (!(file.exists())) {
        file.createNewFile();
    }

    ObjectOutputStream outputStream = null;

    outputStream = new ObjectOutputStream(new BufferedOutputStream(new
    FileOutputStream(file)));

    outputStream.writeObject(person);
    outputStream.reset();
    outputStream.writeObject(person2);
    outputStream.reset();
    outputStream.writeObject(person3);
    outputStream.reset();

    outputStream.close();

    ObjectInputStream inputStream = null;

    inputStream = new ObjectInputStream(new BufferedInputStream(new
    FileInputStream(file)));
    int count = 0;
    Person object = null;
</code>```

I added more objects to my file but when i wanted to read them i got and error:
Exception in thread "main" java.io.StreamCorruptedException:
 invalid typecode:AC

```<code>at java.io.ObjectInputStream.readObject0(Unknown Source)
at java.io.ObjectInputStream.readObject(Unknown Source)
at pisanjeUFajl.Serilizacija.main(Serilizacija.java:46)
</code>```

It read just the first 3 objects which were added the first to my file.

```<code>    try {
        while (true) {
            object = (Person) inputStream.readObject();
            count++;
            System.out.println(object);

        }
    } catch (EOFException error) {
        System.out.println("\nEnd of file reacher - objects read = " +
    count);
    }

    inputStream.close();
}
</code>```

}

答:
```<code>Use for writing object
ObjectOutputStream  outputStream = new ObjectOutputStream(new
                        FileOutputStream(new File("test")));

Use it for appending object at end of file
ObjectOutputStream outputStream2 = new ObjectOutputStream(new FileOutputStream("test", true)) {
                    protected void writeStreamHeader() throws IOException {
                        reset();
                    }
                };
</code>```

for reading
ObjectInputStream inputStream = new ObjectInputStream(new FileInputStream("test"));

Body:
I Have 3 objects of Person type and i write them to my file Person.person and than i read them one by one but when i run my program again i get the same 3 objets written as when i run it for the firts time.How to add those 3 objects to  my file again and again every time i run my program.I want from it to be the same 3 objects or some other objects but they need to be added to the end of my file.

And how to get that data when i want to read that file?

 package pisanjeUFajl;

 import java.io.BufferedInputStream;
 import java.io.BufferedOutputStream;
 import java.io.EOFException;
 import java.io.File;
 import java.io.FileInputStream;
 import java.io.FileOutputStream;
 import java.io.IOException;
 import java.io.ObjectInputStream;
 import java.io.ObjectOutputStream;
 import java.util.List;

 public class Serilizacija {
 public static void main(String[] args) throws IOException,
 ClassNotFoundException {

    Person person = new Person("Jovan", "Dukic");
    Person person2 = new Person("Stanko", "Maca");
    Person person3 = new Person("Tole", "Lopove");

    File file = new File("C:\\Users\\Jovan\\Desktop\\Person.person");
    if (!(file.exists())) {
        file.createNewFile();
    }

    ObjectOutputStream outputStream = null;

    outputStream = new ObjectOutputStream(new BufferedOutputStream(new
    FileOutputStream(file)));

    outputStream.writeObject(person);
    outputStream.reset();
    outputStream.writeObject(person2);
    outputStream.reset();
    outputStream.writeObject(person3);
    outputStream.reset();

    outputStream.close();

    ObjectInputStream inputStream = null;

    inputStream = new ObjectInputStream(new BufferedInputStream(new
    FileInputStream(file)));
    int count = 0;
    Person object = null;

I added more objects to my file but when i wanted to read them i got and error:
Exception in thread "main" java.io.StreamCorruptedException:
 invalid typecode:AC

at java.io.ObjectInputStream.readObject0(Unknown Source)
at java.io.ObjectInputStream.readObject(Unknown Source)
at pisanjeUFajl.Serilizacija.main(Serilizacija.java:46)

It read just the first 3 objects which were added the first to my file.

    try {
        while (true) {
            object = (Person) inputStream.readObject();
            count++;
            System.out.println(object);

        }
    } catch (EOFException error) {
        System.out.println("\nEnd of file reacher - objects read = " +
    count);
    }

    inputStream.close();
}

}

Body:
Use for writing object
ObjectOutputStream  outputStream = new ObjectOutputStream(new
                        FileOutputStream(new File("test")));

Use it for appending object at end of file
ObjectOutputStream outputStream2 = new ObjectOutputStream(new FileOutputStream("test", true)) {
                    protected void writeStreamHeader() throws IOException {
                        reset();
                    }
                };

for reading
ObjectInputStream inputStream = new ObjectInputStream(new FileInputStream("test"));


问:
Oracle Analytical Functions in XMLElement
I am trying to generate XML from a oracle table using the analytical functions like sum and count over partition. Using following query:

```<code>SELECT XMLElement("DEPARTMENT",
            XMLAttributes((sum(amount) OVER (PARTITION BY deptid)) AS dept_sum,
                            (count(*) OVER (PARTITION BY deptid)) AS dept_count),
                XMLAgg(
                    XMLElement("EMPLOYEE",
                        XMLConcat(XMLElement("EMP_SALARY", a.emp_salary),
                                     XMLElement("EMP_ADDRESS", a.emp_address))
                    )
                )
         )
   AS "EMP_XML"
FROM EMPLOYEES
</code>```

Expecting following Output

```<code>EMP_XML
-------------------------------------------
<DEPARTMENT dept_sum=150, dept_count=2>
    <EMPLOYEE>
        <EMP_SALARY>100</EMP_SALARY>
        <EMP_ADDRESS>Mumbai</EMP_ADDRESS>
    </EMPLOYEE>
    <EMPLOYEE>
        <EMP_SALARY>50</EMP_SALARY>
        <EMP_ADDRESS>Hyderabad</EMP_ADDRESS>
    </EMPLOYEE>
</DEPARTMENT>
</code>```

Got below error over the sum and count functions:

```<code>ORA-00937: not a single-group group function
</code>```

How do I use analytical functions in XMLElement function ?

答:
Try This :</p>

```<code>SELECT XMLElement("DEPARTMENT",
            XMLAttributes(sum(emp_salary) AS dept_sum,
                            count(1) AS dept_count),
                XMLAgg(
                    XMLElement("EMPLOYEE",
                        XMLConcat(XMLElement("EMP_SALARY", emp_salary),
                                     XMLElement("EMP_ADDRESS", emp_address))
                    )
                )
         )
   AS "EMP_XML"
FROM EMPLOYEES
Group by deptid;
</code>```

Body:
I am trying to generate XML from a oracle table using the analytical functions like sum and count over partition. Using following query:

SELECT XMLElement("DEPARTMENT",
            XMLAttributes((sum(amount) OVER (PARTITION BY deptid)) AS dept_sum,
                            (count(*) OVER (PARTITION BY deptid)) AS dept_count),
                XMLAgg(
                    XMLElement("EMPLOYEE",
                        XMLConcat(XMLElement("EMP_SALARY", a.emp_salary),
                                     XMLElement("EMP_ADDRESS", a.emp_address))
                    )
                )
         )
   AS "EMP_XML"
FROM EMPLOYEES

Expecting following Output

EMP_XML
-------------------------------------------
<DEPARTMENT dept_sum=150, dept_count=2>
    <EMPLOYEE>
        <EMP_SALARY>100</EMP_SALARY>
        <EMP_ADDRESS>Mumbai</EMP_ADDRESS>
    </EMPLOYEE>
    <EMPLOYEE>
        <EMP_SALARY>50</EMP_SALARY>
        <EMP_ADDRESS>Hyderabad</EMP_ADDRESS>
    </EMPLOYEE>
</DEPARTMENT>

Got below error over the sum and count functions:

ORA-00937: not a single-group group function

How do I use analytical functions in XMLElement function ?

Body:
Try This :

SELECT XMLElement("DEPARTMENT",
            XMLAttributes(sum(emp_salary) AS dept_sum,
                            count(1) AS dept_count),
                XMLAgg(
                    XMLElement("EMPLOYEE",
                        XMLConcat(XMLElement("EMP_SALARY", emp_salary),
                                     XMLElement("EMP_ADDRESS", emp_address))
                    )
                )
         )
   AS "EMP_XML"
FROM EMPLOYEES
Group by deptid;


问:
Unity objects not in layermask getting hit by raycast
I am raycasting to detect collision with objects that are on the controllable layer. For some reason objects that are not on the controllable layer are also getting hit. Here is the code where I call the raycast.

```<code>if (Input.touches.Length > 0)
    {
        RaycastHit hit;
        if (Physics.Raycast(firstPersonCamera.ScreenPointToRay(Input.GetTouch(0).position), out hit, controllableLayer))
        {
            Debug.Log("Object hit");
            Debug.Log(hit.transform.gameObject.name);

            Touch touch = Input.GetTouch(0);

            GameObject objectHit = hit.transform.gameObject;

            if (dragging)
            {
                Vector3 cursorScreenPoint = new Vector3(touch.position.x, touch.position.y, screenPoint.z);
                Vector3 cursorPosition = firstPersonCamera.ScreenToWorldPoint(cursorScreenPoint) + offset;
                objectHit.transform.position = cursorPosition;
            }
            // Handle finger movements based on touch phase.
            switch (touch.phase)
            {
                // Record initial touch position.
                case TouchPhase.Began:
                    screenPoint = firstPersonCamera.WorldToScreenPoint(objectHit.transform.position);
                    offset = objectHit.transform.position - firstPersonCamera.ScreenToWorldPoint(new Vector3(touch.position.x, touch.position.y, screenPoint.z));
                    dragging = true;
                    break;

                // Determine direction by comparing the current touch position with the initial one.
                case TouchPhase.Moved:
                    break;

                // Report that a direction has been chosen when the finger is lifted.
                case TouchPhase.Ended:
                    dragging = false;
                    break;
            }
        }
        else
        {
            Debug.Log("Nothing hit");
        }
    }
</code>```

Also here is where I declare the layermask

```<code>void Awake()
{
    firstPersonCamera = GameObject.Find("First Person Camera").GetComponent<Camera>();
    controllableLayer = LayerMask.NameToLayer("Controllable");
    Debug.Log(LayerMask.LayerToName(controllableLayer));
}
</code>```

答:
Because Layers use bit shifting, you have to do as follow when raycasting :

```<code>int layerMask = 1 << controllableLayer;
Physics.Raycast(firstPersonCamera.ScreenPointToRay(Input.GetTouch(0).position), out hit, layerMask)
</code>```

Otherwise, declare controllableLayer as an integer and do as follow :

```<code>int controllableLayer ;

void Awake()
{
    controllableLayer = 1 << LayerMask.NameToLayer("Controllable");
}

void Update()
{
    // ...
    if( Physics.Raycast(firstPersonCamera.ScreenPointToRay(Input.GetTouch(0).position), out hit, controllableLayer) )
    {
        // ...
    }
}
</code>```

Check these links :

https://answers.unity.com/questions/472886/use-layer-name-for-layermask-instead-of-layer-numb.html

https://gamedev.stackexchange.com/questions/132132/why-do-unity-layer-masks-need-to-use-bit-shifting

Body:
I am raycasting to detect collision with objects that are on the controllable layer. For some reason objects that are not on the controllable layer are also getting hit. Here is the code where I call the raycast.

if (Input.touches.Length > 0)
    {
        RaycastHit hit;
        if (Physics.Raycast(firstPersonCamera.ScreenPointToRay(Input.GetTouch(0).position), out hit, controllableLayer))
        {
            Debug.Log("Object hit");
            Debug.Log(hit.transform.gameObject.name);

            Touch touch = Input.GetTouch(0);

            GameObject objectHit = hit.transform.gameObject;

            if (dragging)
            {
                Vector3 cursorScreenPoint = new Vector3(touch.position.x, touch.position.y, screenPoint.z);
                Vector3 cursorPosition = firstPersonCamera.ScreenToWorldPoint(cursorScreenPoint) + offset;
                objectHit.transform.position = cursorPosition;
            }
            // Handle finger movements based on touch phase.
            switch (touch.phase)
            {
                // Record initial touch position.
                case TouchPhase.Began:
                    screenPoint = firstPersonCamera.WorldToScreenPoint(objectHit.transform.position);
                    offset = objectHit.transform.position - firstPersonCamera.ScreenToWorldPoint(new Vector3(touch.position.x, touch.position.y, screenPoint.z));
                    dragging = true;
                    break;

                // Determine direction by comparing the current touch position with the initial one.
                case TouchPhase.Moved:
                    break;

                // Report that a direction has been chosen when the finger is lifted.
                case TouchPhase.Ended:
                    dragging = false;
                    break;
            }
        }
        else
        {
            Debug.Log("Nothing hit");
        }
    }

Also here is where I declare the layermask

void Awake()
{
    firstPersonCamera = GameObject.Find("First Person Camera").GetComponent<Camera>();
    controllableLayer = LayerMask.NameToLayer("Controllable");
    Debug.Log(LayerMask.LayerToName(controllableLayer));
}

Body:
Because Layers use bit shifting, you have to do as follow when raycasting :

int layerMask = 1 << controllableLayer;
Physics.Raycast(firstPersonCamera.ScreenPointToRay(Input.GetTouch(0).position), out hit, layerMask)

Otherwise, declare controllableLayer as an integer and do as follow :

int controllableLayer ;

void Awake()
{
    controllableLayer = 1 << LayerMask.NameToLayer("Controllable");
}

void Update()
{
    // ...
    if( Physics.Raycast(firstPersonCamera.ScreenPointToRay(Input.GetTouch(0).position), out hit, controllableLayer) )
    {
        // ...
    }
}

Check these links :

https://answers.unity.com/questions/472886/use-layer-name-for-layermask-instead-of-layer-numb.html

https://gamedev.stackexchange.com/questions/132132/why-do-unity-layer-masks-need-to-use-bit-shifting


问:
auto hide a div / flash message after few seconds using css3 react
I comparatively new to React environment .I have wrote a very basic component for bookmarking feature.

Basically clicking upon favourite icon,

it sends an ajax call > create a record in the db > on ajax success show a flash message "Page added to favourites."

Its a toggle button, so upon clicking on it again ,

it sends an ajax call > delete the record in the db > on ajax success i show a flash message "Page removed from favourites."

Here is the component i wrote which works perfectly. But what i do not like is, using the setTimeOut function to hide the flash message. I fell like there must be other way (may be css) to achieve the same in React way.

import React, {
  PropTypes
} from 'react';
import {
  Component
} from 'aplus-base';
import axios from 'axios';

const API = "http://localhost:3000/favourites/toggle"
const API2 = "http://localhost:3000/favourites/current_bookmark_status"

@Component
export default class Bookmark extends React.Component {
  static styles = require('./bookmark.sass')

  state = {
    bookmarked: '',
    message: "",
    alert: false
  }

  componentDidMount() {
    this.fetchData();
  }

  toggle() {
    const querystring = require('querystring')
    axios.post(API, querystring.stringify({
        current_page_key: '/marketing'
      }), {
        headers: {
          "Content-Type": "application/x-www-form-urlencoded"
        }
      })
      .then(response => {
        this.setState({
          bookmarked: response.data.bookmarked,
          alert: true
        });
        const message = response.data.bookmarked ? "Added to Favourites" : "Removed from Favourites"
        this.setState({
          message
        })
        setTimeout(() => {
          this.setState({
            alert: false
          });
        }, 2000);
      })

  }
  fetchData = () => {
    const querystring = require('querystring')
    axios.post(API2, querystring.stringify({
        current_page_key: '/marketing'
      }), {
        headers: {
          "Content-Type": "application/x-www-form-urlencoded"
        }
      })
      .then(response => {
        this.setState({
          bookmarked: response.data.bookmarked
        });
      })
  }

  render() {
    return ( <
      div >
      <
      i className = {
        this.state.bookmarked ? "icon icon-bookmarked" : "icon icon-bookmark"
      }
      onClick = {
        this.toggle.bind(this)
      }
      /> <
      div styleName = {
        `result ${this.state.alert ? "alert-shown": "alert-hidden"}`
      } > {
        this.state.message
      } <
      /div>     <
      /div>
    )
  }
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.icon display: inline-block width: 30px height: 30px background: no-repeat center background-size: contain vertical-align: middle &.icon-bookmark background-image: url(../assets/bookmark.png) transition: all 1s linear &.icon-bookmarked background-image: url(../assets/bookmarked.png) transition: all 1s linear .result position: fixed top: 0 left: 40% width: 20% box-sizing: border-box padding: 4px text-align: center font-weight: bold .alert-shown opacity: 1;
transition: all 250ms linear;
.alert-hidden opacity: 0;
transition: all 250ms linear;</code>```

```

答:
I wanted to show an overlay with React and hide it with css after a few seconds and I bumped into your question, so I thought I show you how I made it. The answer of @jefree-sujit was of great help to me.

The end result is that actually we are showing a hidden overlay, then showing it via an animation in css, and then hiding it again.

So, in my render method I show my component like that:

{isPostFulfilled && <SuccessDisplay />}

(this part can be different depending on how you make your API calls, I use react-redux-fetch so I'm getting pending/fulfilled/rejected properties for my calls).

My SuccessDisplay component uses styled-components and is practically the overlay:

```<code>// @flow
import React from 'react';
import styled from 'styled-components';
import { BootstrapIcon } from 'skin';

export const Styling = styled.div`
  .success {
    animation: hide-animation 0.6s ease-in 0s;
    visibility: hidden;
    position: fixed;
    top: 0;
    bottom: 0;
    left: 0;
    right: 0;
    height: 100vh;
    width: 100vw;
    background-color: rgba(0, 0, 0, 0.3);
    z-index: 100000;

    .ok-icon {
      font-size: 50px;
      cursor: default;
      opacity: 0.9;
      position: absolute;
      top: 48%;
      left: 48%;
      color: green;
      margin: 0 auto;
    }

    @keyframes hide-animation {
      0% {
        opacity: 1;
        visibility: visible;
      }

      100% {
        opacity: 0;
        visibility: hidden;
      }
    }
  }
`;

const SuccessDisplay = () => (
  <Styling>
    <div className="success">
      <BootstrapIcon icon="ok" className="ok-icon" />
    </div>
  </Styling>
);

export default SuccessDisplay;
</code>```

The BootstrapIcon is rendering react-bootstrap's glyphicons.

The deal with the animation in this css snippet is that:
it will run the hide-animation for 0.6 seconds, using the ease-in style (within those 0.6 seconds) and all this kicks in 0 seconds after the styles are loaded (instantly).

The important part is to set the visibility: hidden in our initial styles as well, since this is where we start from and where we're going to. After the animation ends (after 0.6 seconds) then we're falling back to our initial styles.

Hope this helps somebody in the future!

Body:
I comparatively new to React environment .I have wrote a very basic component for bookmarking feature.

Basically clicking upon favourite icon,

it sends an ajax call > create a record in the db > on ajax success show a flash message "Page added to favourites."

Its a toggle button, so upon clicking on it again ,

it sends an ajax call > delete the record in the db > on ajax success i show a flash message "Page removed from favourites."

Here is the component i wrote which works perfectly. But what i do not like is, using the setTimeOut function to hide the flash message. I fell like there must be other way (may be css) to achieve the same in React way.

import React, {
  PropTypes
} from 'react';
import {
  Component
} from 'aplus-base';
import axios from 'axios';

const API = "http://localhost:3000/favourites/toggle"
const API2 = "http://localhost:3000/favourites/current_bookmark_status"

@Component
export default class Bookmark extends React.Component {
  static styles = require('./bookmark.sass')

  state = {
    bookmarked: '',
    message: "",
    alert: false
  }

  componentDidMount() {
    this.fetchData();
  }

  toggle() {
    const querystring = require('querystring')
    axios.post(API, querystring.stringify({
        current_page_key: '/marketing'
      }), {
        headers: {
          "Content-Type": "application/x-www-form-urlencoded"
        }
      })
      .then(response => {
        this.setState({
          bookmarked: response.data.bookmarked,
          alert: true
        });
        const message = response.data.bookmarked ? "Added to Favourites" : "Removed from Favourites"
        this.setState({
          message
        })
        setTimeout(() => {
          this.setState({
            alert: false
          });
        }, 2000);
      })

  }
  fetchData = () => {
    const querystring = require('querystring')
    axios.post(API2, querystring.stringify({
        current_page_key: '/marketing'
      }), {
        headers: {
          "Content-Type": "application/x-www-form-urlencoded"
        }
      })
      .then(response => {
        this.setState({
          bookmarked: response.data.bookmarked
        });
      })
  }

  render() {
    return ( <
      div >
      <
      i className = {
        this.state.bookmarked ? "icon icon-bookmarked" : "icon icon-bookmark"
      }
      onClick = {
        this.toggle.bind(this)
      }
      /> <
      div styleName = {
        `result ${this.state.alert ? "alert-shown": "alert-hidden"}`
      } > {
        this.state.message
      } <
      /div>     <
      /div>
    )
  }
}

.icon display: inline-block width: 30px height: 30px background: no-repeat center background-size: contain vertical-align: middle &.icon-bookmark background-image: url(../assets/bookmark.png) transition: all 1s linear &.icon-bookmarked background-image: url(../assets/bookmarked.png) transition: all 1s linear .result position: fixed top: 0 left: 40% width: 20% box-sizing: border-box padding: 4px text-align: center font-weight: bold .alert-shown opacity: 1;
transition: all 250ms linear;
.alert-hidden opacity: 0;
transition: all 250ms linear;

Body:
I wanted to show an overlay with React and hide it with css after a few seconds and I bumped into your question, so I thought I show you how I made it. The answer of @jefree-sujit was of great help to me.

The end result is that actually we are showing a hidden overlay, then showing it via an animation in css, and then hiding it again.

So, in my render method I show my component like that:

{isPostFulfilled && <SuccessDisplay />}

(this part can be different depending on how you make your API calls, I use react-redux-fetch so I'm getting pending/fulfilled/rejected properties for my calls).

My SuccessDisplay component uses styled-components and is practically the overlay:

// @flow
import React from 'react';
import styled from 'styled-components';
import { BootstrapIcon } from 'skin';

export const Styling = styled.div`
  .success {
    animation: hide-animation 0.6s ease-in 0s;
    visibility: hidden;
    position: fixed;
    top: 0;
    bottom: 0;
    left: 0;
    right: 0;
    height: 100vh;
    width: 100vw;
    background-color: rgba(0, 0, 0, 0.3);
    z-index: 100000;

    .ok-icon {
      font-size: 50px;
      cursor: default;
      opacity: 0.9;
      position: absolute;
      top: 48%;
      left: 48%;
      color: green;
      margin: 0 auto;
    }

    @keyframes hide-animation {
      0% {
        opacity: 1;
        visibility: visible;
      }

      100% {
        opacity: 0;
        visibility: hidden;
      }
    }
  }
`;

const SuccessDisplay = () => (
  <Styling>
    <div className="success">
      <BootstrapIcon icon="ok" className="ok-icon" />
    </div>
  </Styling>
);

export default SuccessDisplay;

The BootstrapIcon is rendering react-bootstrap's glyphicons.

The deal with the animation in this css snippet is that:
it will run the hide-animation for 0.6 seconds, using the ease-in style (within those 0.6 seconds) and all this kicks in 0 seconds after the styles are loaded (instantly).

The important part is to set the visibility: hidden in our initial styles as well, since this is where we start from and where we're going to. After the animation ends (after 0.6 seconds) then we're falling back to our initial styles.

Hope this helps somebody in the future!


问:
Insert Form Input values into array AND retain custom Key indexes
I am working with a form with elements like this:

```<code><form id="post">
   <div id="related_posts">
        <input type="hidden" class='related' name="reladded[72]" value="12" />
        <input type="hidden" class='related' name="reladded[34]" value="21" />
        <input type="hidden" class='related' name="reladded[46]" value="33" />
   <div>
</form>
</code>```

When I submit this using the standard form process, I get an array, which looks like:

```<code>array('72'=> '12,'34'=> '21,'46'=> '33')
</code>```

which I then serialize and save to a database.

How can I use JQuery to collect the same elements from those fields and convert them to a serialized array, so I can submit via AJAX POST?

I have all the AJAX code covered, but I can't yet iterate the elements to collect the correct array values. There are other elements in the form, but these ones are the only ones I want to submit.

I have tried methods like the following, to no avail:

```<code>var serialrel = $('#post input:hidden[name="reladded"]').serialize();
</code>```

Please help!

答:
You can use .serialize() on the form element

```<code>$("#post").serialize();
</code>```

Body:
I am working with a form with elements like this:

<form id="post">

        <input type="hidden" class='related' name="reladded[72]" value="12" />
        <input type="hidden" class='related' name="reladded[34]" value="21" />
        <input type="hidden" class='related' name="reladded[46]" value="33" />

</form>

When I submit this using the standard form process, I get an array, which looks like:

array('72'=> '12,'34'=> '21,'46'=> '33')

which I then serialize and save to a database.

How can I use JQuery to collect the same elements from those fields and convert them to a serialized array, so I can submit via AJAX POST?

I have all the AJAX code covered, but I can't yet iterate the elements to collect the correct array values. There are other elements in the form, but these ones are the only ones I want to submit.

I have tried methods like the following, to no avail:

var serialrel = $('#post input:hidden[name="reladded"]').serialize();

Please help!

Body:
You can use .serialize() on the form element

$("#post").serialize();


问:
Is there a way to pull an instagram feed with PHP without logging in?
It seems that this solution no longer works -

How to get a user's Instagram feed

The new API requires an access token which is dynamically assigned after passing through a login page.  Is there a way to still pull a feed programmatically through PHP without jumping through the new oauth hoops?  This is useful for setting a crontab to automatically save new posts to a database.

答:
Try this php library: https://github.com/postaddictme/instagram-php-scraper

And here is example (https://github.com/postaddictme/instagram-php-scraper/blob/master/examples/getAccountMediasByUsername.php):

```<code><?php
require __DIR__ . '/../vendor/autoload.php';
// If account is public you can query Instagram without auth
$instagram = new \InstagramScraper\Instagram();
$medias = $instagram->getMedias('kevin', 25);
// Let's look at $media
$media = $medias[0];
echo "Media info:\n";
echo "Id: {$media->getId()}\n";
echo "Shotrcode: {$media->getShortCode()}\n";
echo "Created at: {$media->getCreatedTime()}\n";
echo "Caption: {$media->getCaption()}\n";
echo "Number of comments: {$media->getCommentsCount()}";
echo "Number of likes: {$media->getLikesCount()}";
echo "Get link: {$media->getLink()}";
echo "High resolution image: {$media->getImageHighResolutionUrl()}";
echo "Media type (video or image): {$media->getType()}";
$account = $media->getOwner();
echo "Account info:\n";
echo "Id: {$account->getId()}\n";
echo "Username: {$account->getUsername()}\n";
echo "Full name: {$account->getFullName()}\n";
echo "Profile pic url: {$account->getProfilePicUrl()}\n";
// If account private you should be subscribed and after auth it will be available
$instagram = \InstagramScraper\Instagram::withCredentials('username', 'password', 'path/to/cache/folder');
$instagram->login();
$medias = $instagram->getMedias('private_account', 100);
</code>```

Body:
Try this php library: https://github.com/postaddictme/instagram-php-scraper

And here is example (https://github.com/postaddictme/instagram-php-scraper/blob/master/examples/getAccountMediasByUsername.php):

<?php
require __DIR__ . '/../vendor/autoload.php';
// If account is public you can query Instagram without auth
$instagram = new \InstagramScraper\Instagram();
$medias = $instagram->getMedias('kevin', 25);
// Let's look at $media
$media = $medias[0];
echo "Media info:\n";
echo "Id: {$media->getId()}\n";
echo "Shotrcode: {$media->getShortCode()}\n";
echo "Created at: {$media->getCreatedTime()}\n";
echo "Caption: {$media->getCaption()}\n";
echo "Number of comments: {$media->getCommentsCount()}";
echo "Number of likes: {$media->getLikesCount()}";
echo "Get link: {$media->getLink()}";
echo "High resolution image: {$media->getImageHighResolutionUrl()}";
echo "Media type (video or image): {$media->getType()}";
$account = $media->getOwner();
echo "Account info:\n";
echo "Id: {$account->getId()}\n";
echo "Username: {$account->getUsername()}\n";
echo "Full name: {$account->getFullName()}\n";
echo "Profile pic url: {$account->getProfilePicUrl()}\n";
// If account private you should be subscribed and after auth it will be available
$instagram = \InstagramScraper\Instagram::withCredentials('username', 'password', 'path/to/cache/folder');
$instagram->login();
$medias = $instagram->getMedias('private_account', 100);


问:
Entity Framework generic Where for entities that inherit from a specific class
Here I have a generic Repository class I copied from a tutorial page, but specifically my problem is on the two last functions. On my project I have several catalog entities that inherit from CRUDProperties class and there is a property "Activo" in all of them, what I currently want to do is that if the entity inherits from CRUDProperties class I get all the entities with Activo property on true, and if they do not inherit from that class it just gets all entities. But the compiler throws an error stating T is already defined. What should I do?</p>

```<code>public class Repository<T> where T : class
{
    private readonly projectEntities context;
    private IDbSet<T> entities;
    string errorMessage = string.Empty;

    public Repository(projectEntities context)
    {
        this.context = context;
    }

    public T GetById(object id)
    {
        return context.Set<T>().Find(id);
    }

    // This is the function that throws me a compilation error
    public virtual IList<T> GetAll<T>() where T : CRUDProperties
    {
        return context.Set<T>().Where(c => c.Activo).ToList();
    }

    public virtual IList<T> GetAll()
    {
        return context.Set<T>().ToList();
    }
}
</code>```

答:
The compiler complains about the ambiguous naming of the type parameters. The class already has a type parameter named T, so in the context of the class that type parameter name is already "taken".

But you should be able to accomplish what you want to do simply by renaming the type parameter for the method to something else than T, so your changed method could look like this:

```<code>public virtual IList<TCrud> GetAll<TCrud>() where TCrud : CRUDProperties
{
    return context.Set<TCrud>().Where(c => c.Activo).ToList();
}
</code>```

Note: I assume here that CRUDProperties is a class... If it is an interface then you'll also need to copy the class constraint to the method (i.e. change it to where TCrud : class, CRUDProperties)

Body:
Here I have a generic Repository class I copied from a tutorial page, but specifically my problem is on the two last functions. On my project I have several catalog entities that inherit from CRUDProperties class and there is a property "Activo" in all of them, what I currently want to do is that if the entity inherits from CRUDProperties class I get all the entities with Activo property on true, and if they do not inherit from that class it just gets all entities. But the compiler throws an error stating T is already defined. What should I do?

public class Repository<T> where T : class
{
    private readonly projectEntities context;
    private IDbSet<T> entities;
    string errorMessage = string.Empty;

    public Repository(projectEntities context)
    {
        this.context = context;
    }

    public T GetById(object id)
    {
        return context.Set<T>().Find(id);
    }

    // This is the function that throws me a compilation error
    public virtual IList<T> GetAll<T>() where T : CRUDProperties
    {
        return context.Set<T>().Where(c => c.Activo).ToList();
    }

    public virtual IList<T> GetAll()
    {
        return context.Set<T>().ToList();
    }
}

Body:
The compiler complains about the ambiguous naming of the type parameters. The class already has a type parameter named T, so in the context of the class that type parameter name is already "taken".

But you should be able to accomplish what you want to do simply by renaming the type parameter for the method to something else than T, so your changed method could look like this:

public virtual IList<TCrud> GetAll<TCrud>() where TCrud : CRUDProperties
{
    return context.Set<TCrud>().Where(c => c.Activo).ToList();
}

Note: I assume here that CRUDProperties is a class... If it is an interface then you'll also need to copy the class constraint to the method (i.e. change it to where TCrud : class, CRUDProperties)


问:
How can I change the UIButton "glow" color used when "Shows Touch On Highlight" is enabled?
I have a UIButton with "Shows Touch On Highlight" enabled in the storyboard. It applies a "white" glow to the button when clicked.

However, I have a light grey button and would like to change the glow color so that it's more visible.

I've tried setting the background image for the highlighted control state to black, but it doesn't seem to make a different to the glow. I can change the background color of the button---that all works.

What controls the glow color, if anything? Or do I have to do it manually if I need a different color?

答: "Shows Touch On Highlight" is a pure convenience, so you do have to do things manually if you want a different effect. Just supply a different image for the highlighted state, one that includes the desired "glow" drawing.</p>


问:
How to make a dictionary from this data?
So the part of my data.dat looks like this:

carine        mite, tick
accipitrine   bird: hawk, falcon, or bird of prey
acipenserine  sturgeon
aedine        mosquito (genus Aedes)
alaudine      bird: skylark
alcelaphine   antelopes
alcidine      bird: auk, puffin, or murre
alectorine    crane
anatine       duck, mallard
anguilline    snake
```

<p>How could I create a dictionary that would map multiple values (e.g bird: hawk, falcon, or bird of prey maps to accipitrine) to single keys?</p>

<p>This is my code so far:</p>

```with open ('collateralAdjectives.dat', 'r') as a:
    adjectives = a.read().splitlines()

d = dict()
for item in collateralAdjectives:
    (s, c) = item.split(' ')
    d[s] = c
```

<p>This is the error that I get:</p>

```(s, c) = item.split(' ')

ValueError: too many values to unpack (expected 2)
```

答:
To map a single key to multiple values, instead map that key to a list containing those values.</p>

```<code>dictionary = {}
dictionary['carine'] = ['mite','tick']
...
dictionary['anguilline'] = ['snake']
</code>```

Body:
So the part of my data.dat looks like this:

carine        mite, tick
accipitrine   bird: hawk, falcon, or bird of prey
acipenserine  sturgeon
aedine        mosquito (genus Aedes)
alaudine      bird: skylark
alcelaphine   antelopes
alcidine      bird: auk, puffin, or murre
alectorine    crane
anatine       duck, mallard
anguilline    snake

How could I create a dictionary that would map multiple values (e.g bird: hawk, falcon, or bird of prey maps to accipitrine) to single keys?

This is my code so far:

with open ('collateralAdjectives.dat', 'r') as a:
    adjectives = a.read().splitlines()

d = dict()
for item in collateralAdjectives:
    (s, c) = item.split(' ')
    d[s] = c

This is the error that I get:

(s, c) = item.split(' ')

ValueError: too many values to unpack (expected 2)

Body:
To map a single key to multiple values, instead map that key to a list containing those values.

dictionary = {}
dictionary['carine'] = ['mite','tick']
...
dictionary['anguilline'] = ['snake']


答:
First let's address a few other things in your query:

You are using the alias a but you never defined it. Since you select only from one table, you don't need a table alias. Just write emp_salary instead of a.emp_salary. However, if for some reason you insist on using an alias anyway, then you must use it for ALL column names, not just for some of them.

You sum over column amount - should that, instead, be emp_salary?

In the XMLATTRIBUTES clause, don't you need to also show the department number?

Then, to your question (and the error you get). You are using XMLAGG, which is correct - to get the proper document structure. But that is an aggregate function - you need a GROUP BY clause. (Obviously, group by deptid).

Then, what goes into XMLATTRIBUTES are aggregate functions. In that place you need sum(emp_salary) and count(*). You would need analytic functions if you wanted to store the sum(salary) and count(rows) IN EACH ROW in the XML document (just like regular analytic functions!) That's not what you are doing; you should be using aggregate, not analytic, functions in XMLATTRIBUTES.

Title: Oracle Analytical Functions in XMLElement


问:
How does $(this) know what my target is?
How does $(this).keyup know I want the keyup listener associated with the #searchString input, and not the parent div?  Doesn't $(this) represent the parent div?  I dumped out $(this) to the console, and it looks like an object for the parent div.

Long story short:

How is this working?  $(this).keyup

Instead of explicitly saying:  $('#searchString').keyup ??

```<code>$('<div id="msg">' + <input id="searchString" name="searchString" type="text" value="" /> + '</div>').dialog({

    open: function () {

        $(this).keyup(function (e) {
            if (e.keyCode == $.ui.keyCode.ENTER)
                $('#btnFind').click();
            return false;
        })

    },

    buttons: [
        {
            text: "Find",
            id: "btnFind",
            icon: "ui-icon-search",
            click: function () {
                //do stuff
            }
        }
    ]
});
</code>```

答:
Did some testing; here are my observations:

$(this) is representative of the parent

$(this).keyup is targeting any (and all) extra inputs I add to

I don't think this this is event bubbling/capturing (the listeners are not nested):

$('#btnFind').click(); is an action nested inside the keyup listener

the jQuery UI dialog button id: "btnFind" has a separate event listener, outside of the the parent

I went ahead and explicitly indicated the target for the listener:  $('#searchString').keyup

Who cares?

Well, I didn't think you could establish event listeners on inputs via the dialog open event.  I'm creating my dialog on-the-fly, and my assumption was that the input may not exist while the open event was trying to establish the event listener.

Body:
How does $(this).keyup know I want the keyup listener associated with the #searchString input, and not the parent div?  Doesn't $(this) represent the parent div?  I dumped out $(this) to the console, and it looks like an object for the parent div.

Long story short:

How is this working?  $(this).keyup

Instead of explicitly saying:  $('#searchString').keyup ??

$('
' + <input id="searchString" name="searchString" type="text" value="" /> + '
').dialog({

    open: function () {

        $(this).keyup(function (e) {
            if (e.keyCode == $.ui.keyCode.ENTER)
                $('#btnFind').click();
            return false;
        })

    },

    buttons: [
        {
            text: "Find",
            id: "btnFind",
            icon: "ui-icon-search",
            click: function () {
                //do stuff
            }
        }
    ]
});

Body:
Did some testing; here are my observations:

$(this) is representative of the parent <div id="msg">

$(this).keyup is targeting any (and all) extra inputs I add to <div id="msg">

I don't think this this is event bubbling/capturing (the listeners are not nested):

$('#btnFind').click(); is an action nested inside the keyup listener

the jQuery UI dialog button id: "btnFind" has a separate event listener, outside of the the parent <div id="msg">

I went ahead and explicitly indicated the target for the listener:  $('#searchString').keyup

Who cares?

Well, I didn't think you could establish event listeners on inputs via the dialog open event.  I'm creating my dialog on-the-fly, and my assumption was that the input may not exist while the open event was trying to establish the event listener.


问:
Cast DataRowView as a typed row?
-update start

Unable to cast object of type 'namespace.Student' to type 'System.Data.DataRowView'

```<code> <%# FixNull(((System.Data.DataRowView)Container.DataItem).Row, "Name")%>

 protected string FixNull(DataRow dr, string fieldName)
        {
            if (dr != null)
            {
                if (!dr.IsNull(fieldName))
                    return (dr[fieldName]).ToString();            }
            return " ";
        }
</code>```

-update end

in the below method expecting an object, so how would i cast it to that type? i always get null no matter what column.

calling from .aspx:

```<code><%# FixNull((mynamespace.Student)(Container.DataItem), "CreatedBy")%>
</code>```

.CS

```<code> protected string FixNull(object dataItem, string fieldName)
        {
            if (dataItem != null)
            {
                DataRowView drv = (DataRowView)dataItem;
                if (drv != null) //always getting null
                {
                    if (!drv.Row.IsNull(fieldName))
                        return (drv[fieldName]).ToString();
                }
            }
            return " ";
        }
</code>```

答:
Get the help from this article:

http://www.codeproject.com/Articles/38669/Using-Formatting-Functions-with-GridView-Template-.aspx

Updated...

Try the given code:

ASPX:

```<code>    <asp:GridView ID="gvSample" runat="server" AutoGenerateColumns="false">
        <Columns>
            <asp:TemplateField HeaderText="ID" HeaderStyle-Width="100px">
                <ItemTemplate>
                    <%# FixNull(Container.DataItem ,"ID") %>
                </ItemTemplate>
            </asp:TemplateField>
            <asp:TemplateField HeaderText="Code" HeaderStyle-Width="100px">
                <ItemTemplate>
                    <%# FixNull(((System.Data.DataRowView)Container.DataItem).Row, "Code") %>  <!--updated here-->
                </ItemTemplate>
            </asp:TemplateField>
        </Columns>
    </asp:GridView>
</code>```

Code behind

```<code>    protected void Page_Load(object sender, EventArgs e)
    {
        gvSample.DataSource = GetData();
        gvSample.DataBind();
    }

    private DataTable GetData()
    {
        DataTable dt = new DataTable();
        dt.Columns.Add(new DataColumn("ID", typeof(string)));
        dt.Columns.Add(new DataColumn("Code", typeof(string)));
        DataRow dr;
        dr = dt.NewRow();
        dr["ID"] = 1;
        dr["Code"] = null;
        dt.Rows.Add(dr);
        dr = dt.NewRow();
        dr["ID"] = 2;
        dr["Code"] = "Karan";
        dt.Rows.Add(dr);
        return dt;
    }

protected string FixNull(object dataItem,string fieldname)
{
    if (dataItem != null)
    {
       //updated here
        //DataRowView drv = (DataRowView)dataItem;
        //if (drv != null)
        //{
        //    if (!drv.Row.IsNull(fieldname))
        //        return (drv[fieldname]).ToString();
        //}
        DataRowView drv;
        DataRow dr;
        if (dataItem is DataRowView)
        {
            drv = (DataRowView)dataItem;
            if (drv != null)
            {
                if (!drv.Row.IsNull(fieldname))
                    return (drv[fieldname]).ToString();
            }
        }
        if (dataItem is DataRow)
        {
            dr = (DataRow)dataItem;
            if (dr != null)
            {
                if (!dr.IsNull(fieldname))
                    return dr[fieldname].ToString();
            }
        }
    }
    return " ";
}
</code>```

Title: Cast DataRowView as a typed row?

Body:
-update start

Unable to cast object of type 'namespace.Student' to type 'System.Data.DataRowView'

 <%# FixNull(((System.Data.DataRowView)Container.DataItem).Row, "Name")%>

 protected string FixNull(DataRow dr, string fieldName)
        {
            if (dr != null)
            {
                if (!dr.IsNull(fieldName))
                    return (dr[fieldName]).ToString();            }
            return " ";
        }

-update end

in the below method expecting an object, so how would i cast it to that type? i always get null no matter what column.

calling from .aspx:

<%# FixNull((mynamespace.Student)(Container.DataItem), "CreatedBy")%>

.CS

 protected string FixNull(object dataItem, string fieldName)
        {
            if (dataItem != null)
            {
                DataRowView drv = (DataRowView)dataItem;
                if (drv != null) //always getting null
                {
                    if (!drv.Row.IsNull(fieldName))
                        return (drv[fieldName]).ToString();
                }
            }
            return " ";
        }

Body:
Get the help from this article:

http://www.codeproject.com/Articles/38669/Using-Formatting-Functions-with-GridView-Template-.aspx

Updated...

Try the given code:

ASPX:

    <asp:GridView ID="gvSample" runat="server" AutoGenerateColumns="false">
        <Columns>
            <asp:TemplateField HeaderText="ID" HeaderStyle-Width="100px">
                <ItemTemplate>
                    <%# FixNull(Container.DataItem ,"ID") %>
                </ItemTemplate>
            </asp:TemplateField>
            <asp:TemplateField HeaderText="Code" HeaderStyle-Width="100px">
                <ItemTemplate>
                    <%# FixNull(((System.Data.DataRowView)Container.DataItem).Row, "Code") %>  <!--updated here-->
                </ItemTemplate>
            </asp:TemplateField>
        </Columns>
    </asp:GridView>

Code behind

    protected void Page_Load(object sender, EventArgs e)
    {
        gvSample.DataSource = GetData();
        gvSample.DataBind();
    }

    private DataTable GetData()
    {
        DataTable dt = new DataTable();
        dt.Columns.Add(new DataColumn("ID", typeof(string)));
        dt.Columns.Add(new DataColumn("Code", typeof(string)));
        DataRow dr;
        dr = dt.NewRow();
        dr["ID"] = 1;
        dr["Code"] = null;
        dt.Rows.Add(dr);
        dr = dt.NewRow();
        dr["ID"] = 2;
        dr["Code"] = "Karan";
        dt.Rows.Add(dr);
        return dt;
    }

protected string FixNull(object dataItem,string fieldname)
{
    if (dataItem != null)
    {
       //updated here
        //DataRowView drv = (DataRowView)dataItem;
        //if (drv != null)
        //{
        //    if (!drv.Row.IsNull(fieldname))
        //        return (drv[fieldname]).ToString();
        //}
        DataRowView drv;
        DataRow dr;
        if (dataItem is DataRowView)
        {
            drv = (DataRowView)dataItem;
            if (drv != null)
            {
                if (!drv.Row.IsNull(fieldname))
                    return (drv[fieldname]).ToString();
            }
        }
        if (dataItem is DataRow)
        {
            dr = (DataRow)dataItem;
            if (dr != null)
            {
                if (!dr.IsNull(fieldname))
                    return dr[fieldname].ToString();
            }
        }
    }
    return "&nbsp;";
}


问:
Can I share data between different class instances in Python?
I have a class option, for which I create an instance z.

How can I use the optionbook from instance z in another instance of option, say y?

```<code>class option(object):
    nextIdNum = 0
    def __init__(self):
          self.optionbook = {}
          self.options = []
          self.optioncomb = {}
    def addopttobook(self,optiondescription):
        self.idNum = option.nextIdNum
        if optiondescription in self.optionbook.values() :
            raise ValueError('Duplicate Option')
        self.optionbook["Opt.ID." + str(self.idNum)] = optiondescription
        option.nextIdNum += 1
    def addoptocomb (self,option):
         combID = 0
         if option in self.optionbook.values():
               if option in self.options:
                    raise ValueError('Duplicate Option')
               self.combID = combID
               self.options.append(str(list(self.optionbook.keys())[list(self.optionbook.values()).index(option)]) +":"+ option)
               self.optioncomb["Optcomb.ID." + str(self.combID)] = self.options
               self.combID +=1
         else:
              raise ValueError('Add options to optionbook first')
    def __str__(self):
        return  str(self.optionbook)

    def getOptionbook(self):
        return self.optionbook.copy()

    def getOptioncomb(self):

        return self.optioncomb.copy()

z = option()
z.addopttobook('open the well')

y = option()
y.addoptocomb('open the well')
</code>```

This gives me a ValueError "Add options to optionbook first" , I understand the error, y and z are different instances. I just want to know how to share data between different instances of same class.

答:
You need a static variable in the option class, and extend your methods to be able to pass in a variable for which optionbook to use:

```<code>class option(object):
    nextIdNum = 0
    optionbook = {} # this variable is "static", i.e. not bound to an instance, but the class itself

    def __init__(self):
          self.optionbook = {}
          self.options = []
          self.optioncomb = {}

    def addopttobook(self,optiondescription, book): # add book-param
        self.idNum = option.nextIdNum
        if optiondescription in self.optionbook.values() :
            raise ValueError('Duplicate Option')
        book["Opt.ID." + str(self.idNum)] = optiondescription
        option.nextIdNum += 1

    def addoptocomb (self,option, book): # add book-param
         combID = 0
         if option in book.values():
               if option in self.options:
                    raise ValueError('Duplicate Option')
               self.combID = combID
               self.options.append(str(list(book.keys())[list(book.values()).index(option)]) +":"+ option)
               self.optioncomb["Optcomb.ID." + str(self.combID)] = self.options
               self.combID +=1
         else:
              raise ValueError('Add options to optionbook first')

    def __str__(self):
        return  str(self.optionbook)

    def getOptionbook(self):
        return self.optionbook.copy()

    def getOptioncomb(self):
        return self.optioncomb.copy()
</code>```

That way, you can access the static member optionbook via option.optionbook:

```<code>z = option()
# you can always access the static member by referencing it via the class-name
# it is not bound to any concrete instances
z.addopttobook('open the well', option.optionbook)
y = option()
y.addoptocomb('open the well', option.optionbook)
print(option.optionbook)
</code>```

Body:
I have a class option, for which I create an instance z.

How can I use the optionbook from instance z in another instance of option, say y?

class option(object):
    nextIdNum = 0
    def __init__(self):
          self.optionbook = {}
          self.options = []
          self.optioncomb = {}
    def addopttobook(self,optiondescription):
        self.idNum = option.nextIdNum
        if optiondescription in self.optionbook.values() :
            raise ValueError('Duplicate Option')
        self.optionbook["Opt.ID." + str(self.idNum)] = optiondescription
        option.nextIdNum += 1
    def addoptocomb (self,option):
         combID = 0
         if option in self.optionbook.values():
               if option in self.options:
                    raise ValueError('Duplicate Option')
               self.combID = combID
               self.options.append(str(list(self.optionbook.keys())[list(self.optionbook.values()).index(option)]) +":"+ option)
               self.optioncomb["Optcomb.ID." + str(self.combID)] = self.options
               self.combID +=1
         else:
              raise ValueError('Add options to optionbook first')
    def __str__(self):
        return  str(self.optionbook)

    def getOptionbook(self):
        return self.optionbook.copy()

    def getOptioncomb(self):

        return self.optioncomb.copy()

z = option()
z.addopttobook('open the well')

y = option()
y.addoptocomb('open the well')

This gives me a ValueError "Add options to optionbook first" , I understand the error, y and z are different instances. I just want to know how to share data between different instances of same class.

Body:
You need a static variable in the option class, and extend your methods to be able to pass in a variable for which optionbook to use:

class option(object):
    nextIdNum = 0
    optionbook = {} # this variable is "static", i.e. not bound to an instance, but the class itself

    def __init__(self):
          self.optionbook = {}
          self.options = []
          self.optioncomb = {}

    def addopttobook(self,optiondescription, book): # add book-param
        self.idNum = option.nextIdNum
        if optiondescription in self.optionbook.values() :
            raise ValueError('Duplicate Option')
        book["Opt.ID." + str(self.idNum)] = optiondescription
        option.nextIdNum += 1

    def addoptocomb (self,option, book): # add book-param
         combID = 0
         if option in book.values():
               if option in self.options:
                    raise ValueError('Duplicate Option')
               self.combID = combID
               self.options.append(str(list(book.keys())[list(book.values()).index(option)]) +":"+ option)
               self.optioncomb["Optcomb.ID." + str(self.combID)] = self.options
               self.combID +=1
         else:
              raise ValueError('Add options to optionbook first')

    def __str__(self):
        return  str(self.optionbook)

    def getOptionbook(self):
        return self.optionbook.copy()

    def getOptioncomb(self):
        return self.optioncomb.copy()

That way, you can access the static member optionbook via option.optionbook:

z = option()
# you can always access the static member by referencing it via the class-name
# it is not bound to any concrete instances
z.addopttobook('open the well', option.optionbook)
y = option()
y.addoptocomb('open the well', option.optionbook)
print(option.optionbook)