问:
java.lang.NullPointerException: Attempt to invoke interface method 'java.util.Iterator java.util.List.iterator()' on a null object reference Retrofit
I'm trying to use blog id to get JSON object from server. At the moment I'm getting this error

java.lang.NullPointerException: Attempt to invoke interface method 'java.util.Iterator java.util.List.iterator()

on a null object reference`.How do I use the post Id to get the full content what am I doing wrong. Please help!!!

MyBlog Adapter:

```<code>public class MyBlogAdapter extends RecyclerView.Adapter<BlogViewHolder> {
    List<BlogResponse> postsList;
    Context context;
    public static String blog_Id, blogID;
    private LayoutInflater inflater;

    public MyBlogAdapter(Context context, List<BlogResponse> postsList){
        this.context = context;
        this.inflater = LayoutInflater.from(context);
        this.postsList = postsList;
    }

    @Override
    public BlogViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = inflater.inflate(R.layout.custom_view,parent, false);
        return new BlogViewHolder(view);
    }

    @Override
    public void onBindViewHolder(BlogViewHolder holder, int position) {
        final BlogResponse posts= postsList.get(position);
        holder.summary.setText(posts.getBlogExcerpt().trim().toString());
        holder.title.setText(posts.getBlogTitle().trim().toString());
        //  Glide.with(context).load(posts.getBlogThumbnail()).into(holder.cover);

        holder.blogHolder.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(context, AnotherSingleView.class);
                blog_Id = posts.getBlogId();
                intent.putExtra(blogID,blog_Id);
                Log.d("MyblogAdapter","Please check blog Id: "+blog_Id);

                context.startActivity(intent);
            }
        });
    }

    @Override
    public int getItemCount() {
        Log.d("MyBlogAdapter,","getItemCount"+postsList.size());

        return postsList == null ? (0) : postsList.size();
    }
}
</code>```

SecondActivity:

```<code>public class AnotherSingleView extends AppCompatActivity {
    String postID;
    int position;
    public TextView blogTitle,blogSub,blogContent;
    public ImageView blogPic;
    List<SingleBlogPost> singleBlogPosts;
    SingleBlogPost singleBlogPost;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_another_single_view);

        Intent intent  = getIntent();
        Bundle showBlogId = intent.getExtras();
        postID = showBlogId.getString(blogID);
        Log.d("AnotherSingleView","Please check blog Id: "+postID);

        singleBlogPosts = new ArrayList<>();

        blogContent = (TextView)findViewById(R.id.blog_content);
        blogSub = (TextView) findViewById(R.id.blog_subtitle);
        blogTitle =(TextView) findViewById(R.id.blog_title);
        blogPic =(ImageView) findViewById(R.id.blog_pix);
        singlePostDisplay();

    }

private void singlePostDisplay() {
    BlogaPI api = ApiClient.getBlogInterface();
    Call<List<SingleBlogPost>> call = api.postResponse(postID);
    call.enqueue(new Callback<List<SingleBlogPost>>() {
        @Override
        public void onResponse(Call<List<SingleBlogPost>> call, Response<List<SingleBlogPost>> response) {
            singleBlogPosts = response.body();
            if (singleBlogPosts != null && !singleBlogPosts.isEmpty() ){
                for (SingleBlogPost posts : singleBlogPosts){
                    Log.d("AnotherSingleView","Please check RESPONSE: "+response.body().toString());
                    blogTitle.setText(posts.getBlogTitle());
                    blogSub.setText(posts.getBlogSubtitle());
                    blogContent.setText(posts.getBlogContent());
                    // Glide.with(AnotherSingleView.this).load(singlepost.getBlogMedimg()).into(blogPic);
                }
            }
            else{
                Toast.makeText(AnotherSingleView.this, "Something is empty", Toast.LENGTH_SHORT).show();
            }            }

            @Override
            public void onFailure(Call<List<SingleBlogPost>> call, Throwable t) {
                Toast.makeText(AnotherSingleView.this, "check again: "+t.toString(), Toast.LENGTH_SHORT).show();
            }
        });
    }
}
</code>```

Interface:

```<code>public interface BlogaPI {
    @GET("blog")
    Call<BlogList> response();

    @GET("post/{blog_id}")
    Call<List<SingleBlogPost>> postResponse(@Path("blog_id") String blog_id);
    //Call<List<SingleBlogPost>> postResponse();
}
</code>```

SingleBlogPost:

```<code>public class SingleBlogPost {

@SerializedName("blog_id")
@Expose
private String blogId;
@SerializedName("blog_title")
@Expose
private String blogTitle;
@SerializedName("blog_subtitle")
@Expose
private String blogSubtitle;
@SerializedName("blog_excerpt")
@Expose
private String blogExcerpt;
@SerializedName("blog_content")
@Expose
private String blogContent;
@SerializedName("blog_thumbnail")
@Expose
private String blogThumbnail;
@SerializedName("blog_medimg")
@Expose
private String blogMedimg;
@SerializedName("category_title")
@Expose
private String categoryTitle;
public SingleBlogPost(String blogId,String blogTitle, String blogSubtitle, String blogExcerpt,
                      String blogContent, String blogThumbnail, String blogMedimg, String categoryTitle){
    this.blogId = blogId;
    this.blogTitle = blogTitle;
    this.blogSubtitle = blogSubtitle;
    this.blogExcerpt = blogExcerpt;
    this.blogContent = blogContent;
    this.blogThumbnail = blogThumbnail;
    this.blogMedimg = blogMedimg;
    this.categoryTitle = categoryTitle;
}

public String getBlogId() {
    return blogId;
}

public void setBlogId(String blogId) {
    this.blogId = blogId;
}

public String getBlogTitle() {
    return blogTitle;
}

public void setBlogTitle(String blogTitle) {
    this.blogTitle = blogTitle;
}

public String getBlogSubtitle() {
    return blogSubtitle;
}

public void setBlogSubtitle(String blogSubtitle) {
    this.blogSubtitle = blogSubtitle;
}

public String getBlogExcerpt() {
    return blogExcerpt;
}

public void setBlogExcerpt(String blogExcerpt) {
    this.blogExcerpt = blogExcerpt;
}

public String getBlogContent() {
    return blogContent;
}

public void setBlogContent(String blogContent) {
    this.blogContent = blogContent;
}

public String getBlogThumbnail() {
    return blogThumbnail;
}

public void setBlogThumbnail(String blogThumbnail) {
    this.blogThumbnail = blogThumbnail;
}

public String getBlogMedimg() {
    return blogMedimg;
}

public void setBlogMedimg(String blogMedimg) {
    this.blogMedimg = blogMedimg;
}

public String getCategoryTitle() {
    return categoryTitle;
}

public void setCategoryTitle(String categoryTitle) {
    this.categoryTitle = categoryTitle;
}

}
</code>```

答:
Check if the server response is different then null before you do a enhanced for like this:

```<code>if(singleBlogPosts!= null) {
    for (SingleBlogPosts posts : singleBlogPosts){
        Log.d("AnotherSingleView","Please check RESPONSE: "+response.body().toString());
        blogTitle.setText(posts.getBlogTitle());
        blogSub.setText(posts.getBlogSubtitle());
        blogContent.setText(posts.getBlogContent());
        // Glide.with(AnotherSingleView.this).load(singlepost.getBlogMedimg()).into(blogPic);
    }
}
</code>```

Body:
I'm trying to use blog id to get JSON object from server. At the moment I'm getting this error

java.lang.NullPointerException: Attempt to invoke interface method 'java.util.Iterator java.util.List.iterator()

on a null object reference`.How do I use the post Id to get the full content what am I doing wrong. Please help!!!

MyBlog Adapter:

public class MyBlogAdapter extends RecyclerView.Adapter<BlogViewHolder> {
    List<BlogResponse> postsList;
    Context context;
    public static String blog_Id, blogID;
    private LayoutInflater inflater;

    public MyBlogAdapter(Context context, List<BlogResponse> postsList){
        this.context = context;
        this.inflater = LayoutInflater.from(context);
        this.postsList = postsList;
    }

    @Override
    public BlogViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = inflater.inflate(R.layout.custom_view,parent, false);
        return new BlogViewHolder(view);
    }

    @Override
    public void onBindViewHolder(BlogViewHolder holder, int position) {
        final BlogResponse posts= postsList.get(position);
        holder.summary.setText(posts.getBlogExcerpt().trim().toString());
        holder.title.setText(posts.getBlogTitle().trim().toString());
        //  Glide.with(context).load(posts.getBlogThumbnail()).into(holder.cover);

        holder.blogHolder.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(context, AnotherSingleView.class);
                blog_Id = posts.getBlogId();
                intent.putExtra(blogID,blog_Id);
                Log.d("MyblogAdapter","Please check blog Id: "+blog_Id);

                context.startActivity(intent);
            }
        });
    }

    @Override
    public int getItemCount() {
        Log.d("MyBlogAdapter,","getItemCount"+postsList.size());

        return postsList == null ? (0) : postsList.size();
    }
}

SecondActivity:

public class AnotherSingleView extends AppCompatActivity {
    String postID;
    int position;
    public TextView blogTitle,blogSub,blogContent;
    public ImageView blogPic;
    List<SingleBlogPost> singleBlogPosts;
    SingleBlogPost singleBlogPost;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_another_single_view);

        Intent intent  = getIntent();
        Bundle showBlogId = intent.getExtras();
        postID = showBlogId.getString(blogID);
        Log.d("AnotherSingleView","Please check blog Id: "+postID);

        singleBlogPosts = new ArrayList<>();

        blogContent = (TextView)findViewById(R.id.blog_content);
        blogSub = (TextView) findViewById(R.id.blog_subtitle);
        blogTitle =(TextView) findViewById(R.id.blog_title);
        blogPic =(ImageView) findViewById(R.id.blog_pix);
        singlePostDisplay();

    }

private void singlePostDisplay() {
    BlogaPI api = ApiClient.getBlogInterface();
    Call<List<SingleBlogPost>> call = api.postResponse(postID);
    call.enqueue(new Callback<List<SingleBlogPost>>() {
        @Override
        public void onResponse(Call<List<SingleBlogPost>> call, Response<List<SingleBlogPost>> response) {
            singleBlogPosts = response.body();
            if (singleBlogPosts != null && !singleBlogPosts.isEmpty() ){
                for (SingleBlogPost posts : singleBlogPosts){
                    Log.d("AnotherSingleView","Please check RESPONSE: "+response.body().toString());
                    blogTitle.setText(posts.getBlogTitle());
                    blogSub.setText(posts.getBlogSubtitle());
                    blogContent.setText(posts.getBlogContent());
                    // Glide.with(AnotherSingleView.this).load(singlepost.getBlogMedimg()).into(blogPic);
                }
            }
            else{
                Toast.makeText(AnotherSingleView.this, "Something is empty", Toast.LENGTH_SHORT).show();
            }            }

            @Override
            public void onFailure(Call<List<SingleBlogPost>> call, Throwable t) {
                Toast.makeText(AnotherSingleView.this, "check again: "+t.toString(), Toast.LENGTH_SHORT).show();
            }
        });
    }
}

Interface:

public interface BlogaPI {
    @GET("blog")
    Call<BlogList> response();

    @GET("post/{blog_id}")
    Call<List<SingleBlogPost>> postResponse(@Path("blog_id") String blog_id);
    //Call<List<SingleBlogPost>> postResponse();
}

SingleBlogPost:

public class SingleBlogPost {

@SerializedName("blog_id")
@Expose
private String blogId;
@SerializedName("blog_title")
@Expose
private String blogTitle;
@SerializedName("blog_subtitle")
@Expose
private String blogSubtitle;
@SerializedName("blog_excerpt")
@Expose
private String blogExcerpt;
@SerializedName("blog_content")
@Expose
private String blogContent;
@SerializedName("blog_thumbnail")
@Expose
private String blogThumbnail;
@SerializedName("blog_medimg")
@Expose
private String blogMedimg;
@SerializedName("category_title")
@Expose
private String categoryTitle;
public SingleBlogPost(String blogId,String blogTitle, String blogSubtitle, String blogExcerpt,
                      String blogContent, String blogThumbnail, String blogMedimg, String categoryTitle){
    this.blogId = blogId;
    this.blogTitle = blogTitle;
    this.blogSubtitle = blogSubtitle;
    this.blogExcerpt = blogExcerpt;
    this.blogContent = blogContent;
    this.blogThumbnail = blogThumbnail;
    this.blogMedimg = blogMedimg;
    this.categoryTitle = categoryTitle;
}

public String getBlogId() {
    return blogId;
}

public void setBlogId(String blogId) {
    this.blogId = blogId;
}

public String getBlogTitle() {
    return blogTitle;
}

public void setBlogTitle(String blogTitle) {
    this.blogTitle = blogTitle;
}

public String getBlogSubtitle() {
    return blogSubtitle;
}

public void setBlogSubtitle(String blogSubtitle) {
    this.blogSubtitle = blogSubtitle;
}

public String getBlogExcerpt() {
    return blogExcerpt;
}

public void setBlogExcerpt(String blogExcerpt) {
    this.blogExcerpt = blogExcerpt;
}

public String getBlogContent() {
    return blogContent;
}

public void setBlogContent(String blogContent) {
    this.blogContent = blogContent;
}

public String getBlogThumbnail() {
    return blogThumbnail;
}

public void setBlogThumbnail(String blogThumbnail) {
    this.blogThumbnail = blogThumbnail;
}

public String getBlogMedimg() {
    return blogMedimg;
}

public void setBlogMedimg(String blogMedimg) {
    this.blogMedimg = blogMedimg;
}

public String getCategoryTitle() {
    return categoryTitle;
}

public void setCategoryTitle(String categoryTitle) {
    this.categoryTitle = categoryTitle;
}

}

Body:
Check if the server response is different then null before you do a enhanced for like this:

if(singleBlogPosts!= null) {
    for (SingleBlogPosts posts : singleBlogPosts){
        Log.d("AnotherSingleView","Please check RESPONSE: "+response.body().toString());
        blogTitle.setText(posts.getBlogTitle());
        blogSub.setText(posts.getBlogSubtitle());
        blogContent.setText(posts.getBlogContent());
        // Glide.with(AnotherSingleView.this).load(singlepost.getBlogMedimg()).into(blogPic);
    }
}


来源: stackexchange

问:
get index of boolean values in pandas - python
```<code>a=pd.DataFrame({'a1':[1,2,3,4],'a2':[5,6,7,8]})
c=pd.DataFrame({'c1':[True,False,True,True],'c2':[True,False,False,True]})
</code>```

How can I get the index of the elements in columns a1 and a2 which are True in columns c1 and c2 respectively?

The index of a1 should be [0,2,3] and the index of a2 [0,3]. The result could be a list of indexes like [[0,2,3],[0,3]].

答:
I think you need where:

```<code>c.columns = a.columns
df1 = a.where(c)
idx = [df1[x].dropna().index.tolist() for x in df1]
print (idx)
[[0, 2, 3], [0, 3]]
</code>```

Another solution:

```<code>c.columns = a.columns
idx = list(a.where(c).stack().reset_index()
            .groupby('level_1')['level_0'].apply(list))
print (idx)
[[0, 2, 3], [0, 3]]
</code>```

ContentLicense: CC BY-SA 3.0

Body:
a=pd.DataFrame({'a1':[1,2,3,4],'a2':[5,6,7,8]})
c=pd.DataFrame({'c1':[True,False,True,True],'c2':[True,False,False,True]})

How can I get the index of the elements in columns a1 and a2 which are True in columns c1 and c2 respectively?

The index of a1 should be [0,2,3] and the index of a2 [0,3]. The result could be a list of indexes like [[0,2,3],[0,3]].

Body:
I think you need where:

c.columns = a.columns
df1 = a.where(c)
idx = [df1[x].dropna().index.tolist() for x in df1]
print (idx)
[[0, 2, 3], [0, 3]]

Another solution:

c.columns = a.columns
idx = list(a.where(c).stack().reset_index()
            .groupby('level_1')['level_0'].apply(list))
print (idx)
[[0, 2, 3], [0, 3]]


问:
Php get dates inside a string
I have a string like this:

Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean 2017-03-31 ligula eget dolor. Aenean massa. 2016-03-04 sociis natoque penatibus...

I would like to get all the dates inside the text... the format dates are always yyyy-mm-dd.

Any suggestions?

Title: Php get dates inside a string

Body: preg_match("/[0-9]{4}-[0-9]{1,2}-[0-9]{1,2}/", $input_line, $output_array);


问:
Send parameters to a URL and get output from that page
I have 2 pages say abc.php and def.php. When abc.php sends 2 values [id and name] to def.php, it shows a message "Value received". Now how can I send those 2 values to def.php without using form in abc.php and get the "Value received" message from def.php? I can't use form because when user frequently visits the abc.php file, the script should automatically work and get the message "Value received" from def.php. Please see my example code:

abc.php:

```<code> <?php
  $id="123";
  $name="blahblah";
   //need to send the value to def.php & get value from that page
  // echo $value=Print the "Value received" msg from def.php;
 ?>
</code>```

def.php:

```<code> <?php
  $id=$_GET['id'];
  $name=$_GET['name'];
  if(!is_null($id)&&!is_null($name))
  {  echo "Value received";}
  else{echo "Not ok";}
 ?>
</code>```

Is there any kind heart who can help me solve the issue?

答: use CURL or Zend_Http_Client.</p>

Body:
I have 2 pages say abc.php and def.php. When abc.php sends 2 values [id and name] to def.php, it shows a message "Value received". Now how can I send those 2 values to def.php without using form in abc.php and get the "Value received" message from def.php? I can't use form because when user frequently visits the abc.php file, the script should automatically work and get the message "Value received" from def.php. Please see my example code:

abc.php:

 <?php
  $id="123";
  $name="blahblah";
   //need to send the value to def.php & get value from that page
  // echo $value=Print the "Value received" msg from def.php;
 ?>

def.php:

 <?php
  $id=$_GET['id'];
  $name=$_GET['name'];
  if(!is_null($id)&&!is_null($name))
  {  echo "Value received";}
  else{echo "Not ok";}
 ?>

Is there any kind heart who can help me solve the issue?

Body: use CURL or Zend_Http_Client.

ContentLicense: CC BY-SA 2.5


问:
ConnectException: connect error: No such file or directory when trying to connect to '50010' using importtsv on hbase
I configured short-circuit settings on both hdfs-site.xml and hbase-site.xml. And I run importtsv on hbase to import data from HDFS to HBase on Hbase cluster. I look over the log on each datanode and all datanode have ConnectException i said to the title.

```<code>2017-03-31 21:59:01,273 WARN [main] org.apache.hadoop.hdfs.shortcircuit.DomainSocketFactory: error creating DomainSocket
java.net.ConnectException: connect(2) error: No such file or directory when trying to connect to '50010'
    at org.apache.hadoop.net.unix.DomainSocket.connect0(Native Method)
    at org.apache.hadoop.net.unix.DomainSocket.connect(DomainSocket.java:250)
    at org.apache.hadoop.hdfs.shortcircuit.DomainSocketFactory.createSocket(DomainSocketFactory.java:164)
    at org.apache.hadoop.hdfs.BlockReaderFactory.nextDomainPeer(BlockReaderFactory.java:753)
    at org.apache.hadoop.hdfs.BlockReaderFactory.createShortCircuitReplicaInfo(BlockReaderFactory.java:469)
    at org.apache.hadoop.hdfs.shortcircuit.ShortCircuitCache.create(ShortCircuitCache.java:783)
    at org.apache.hadoop.hdfs.shortcircuit.ShortCircuitCache.fetchOrCreate(ShortCircuitCache.java:717)
    at org.apache.hadoop.hdfs.BlockReaderFactory.getBlockReaderLocal(BlockReaderFactory.java:421)
    at org.apache.hadoop.hdfs.BlockReaderFactory.build(BlockReaderFactory.java:332)
    at org.apache.hadoop.hdfs.DFSInputStream.blockSeekTo(DFSInputStream.java:617)
    at org.apache.hadoop.hdfs.DFSInputStream.readWithStrategy(DFSInputStream.java:841)
    at org.apache.hadoop.hdfs.DFSInputStream.read(DFSInputStream.java:889)
    at org.apache.hadoop.hdfs.DFSInputStream.read(DFSInputStream.java:696)
    at java.io.DataInputStream.readByte(DataInputStream.java:265)
    at org.apache.hadoop.io.WritableUtils.readVLong(WritableUtils.java:308)
    at org.apache.hadoop.io.WritableUtils.readVIntInRange(WritableUtils.java:348)
    at org.apache.hadoop.io.Text.readString(Text.java:471)
    at org.apache.hadoop.io.Text.readString(Text.java:464)
    at org.apache.hadoop.mapred.MapTask.getSplitDetails(MapTask.java:358)
    at org.apache.hadoop.mapred.MapTask.runNewMapper(MapTask.java:751)
    at org.apache.hadoop.mapred.MapTask.run(MapTask.java:341)
    at org.apache.hadoop.mapred.YarnChild$2.run(YarnChild.java:163)
    at java.security.AccessController.doPrivileged(Native Method)
    at javax.security.auth.Subject.doAs(Subject.java:422)
    at org.apache.hadoop.security.UserGroupInformation.doAs(UserGroupInformation.java:1656)
    at org.apache.hadoop.mapred.YarnChild.main(YarnChild.java:158)
2017-03-31 21:59:01,277 WARN [main] org.apache.hadoop.hdfs.shortcircuit.ShortCircuitCache: ShortCircuitCache(0x34f7234e): failed to load 1073750370_BP-642933002-"IP_ADDRESS"-1490774107737
</code>```

EDIT

hadoop 2.6.4
hbase 1.2.3

hdfs-site.xml

```<code><property>
    <name>dfs.namenode.dir</name>
    <value>/home/hadoop/hdfs/nn</value>
</property>
<property>
    <name>dfs.namenode.checkpoint.dir</name>
    <value>/home/hadoop/hdfs/snn</value>
</property>
<property>
    <name>dfs.datanode.data.dir</name>
    <value>file:///home/hadoop/hdfs/dn</value>
</property>
<property>
    <name>dfs.namenode.http-address</name>
    <value>hadoop1:50070</value>
</property>
<property>
    <name>dfs.namenode.secondary.http-address</name>
    <value>hadoop1:50090</value>
</property>
<property>
    <name>dfs.namenode.rpc-address</name>
    <value>hadoop1:8020</value>
</property>
<property>
    <name>dfs.namenode.handler.count</name>
    <value>50</value>
</property>
<property>
    <name>dfs.datanode.handler.count</name>
    <value>50</value>
</property>
<property>
    <name>dfs.client.read.shortcircuit</name>
    <value>true</value>
</property>
<property>
    <name>dfs.block.local-path-access.user</name>
    <value>hbase</value>
</property>
<property>
    <name>dfs.datanode.data.dir.perm</name>
    <value>775</value>
</property>
<property>
    <name>dfs.domain.socket.path</name>
    <value>_PORT</value>
</property>
<property>
    <name>dfs.client.domain.socket.traffic</name>
    <value>true</value>
</property>
</code>```

hbase-site.xml

```<code><property>
    <name>hbase.rootdir</name>
    <value>hdfs://hadoop1/hbase</value>
</property>
<property>
    <name>hbase.zookeeper.quorum</name>
        <value>hadoop1,hadoop2,hadoop3,hadoop4,hadoop5,hadoop6,hadoop7,hadoop8</value>
</property>
<property>
    <name>hbase.cluster.distributed</name>
    <value>true</value>
</property>
<property>
    <name>dfs.client.read.shortcircuit</name>
    <value>true</value>
</property>
<property>
    <name>hbase.regionserver.handler.count</name>
    <value>50</value>
</property>
<property>
    <name>hfile.block.cache.size</name>
    <value>0.5</value>
</property>
<property>
    <name>hbase.regionserver.global.memstore.size</name>
    <value>0.3</value>
</property>
<property>
    <name>hbase.regionserver.global.memstore.size.lower.limit</name>
    <value>0.65</value>
</property>
<property>
    <name>dfs.domain.socket.path</name>
    <value>_PORT</value>
</property>
</code>```

答:
Short-circuit reads make use of a UNIX domain socket. This is a special path in the filesystem that allows the Client and the DataNodes to communicate. You will need to set a path (not port) to this socket. The DataNode should be able to create this path.

The parent directory of the path value (for ex: /var/lib/hadoop-hdfs/) must exist and should be owned by the hadoop superuser. Also make sure any user except the HDFS user or root has no access to this path.

```<code>mkdir /var/lib/hadoop-hdfs/
chown hdfs_user:hdfs_user /var/lib/hadoop-hdfs/
chmod 750 /var/lib/hadoop-hdfs/
</code>```

Add this property to hdfs-site.xml on all datanodes and clients.

```<code><property>
  <name>dfs.domain.socket.path</name>
  <value>/var/lib/hadoop-hdfs/dn_socket</value>
</property>
</code>```

Restart the services after making the changes.

Note: Paths under /var/run or /var/lib are commonly used.

Body:
I configured short-circuit settings on both hdfs-site.xml and hbase-site.xml. And I run importtsv on hbase to import data from HDFS to HBase on Hbase cluster. I look over the log on each datanode and all datanode have ConnectException i said to the title.

2017-03-31 21:59:01,273 WARN [main] org.apache.hadoop.hdfs.shortcircuit.DomainSocketFactory: error creating DomainSocket
java.net.ConnectException: connect(2) error: No such file or directory when trying to connect to '50010'
    at org.apache.hadoop.net.unix.DomainSocket.connect0(Native Method)
    at org.apache.hadoop.net.unix.DomainSocket.connect(DomainSocket.java:250)
    at org.apache.hadoop.hdfs.shortcircuit.DomainSocketFactory.createSocket(DomainSocketFactory.java:164)
    at org.apache.hadoop.hdfs.BlockReaderFactory.nextDomainPeer(BlockReaderFactory.java:753)
    at org.apache.hadoop.hdfs.BlockReaderFactory.createShortCircuitReplicaInfo(BlockReaderFactory.java:469)
    at org.apache.hadoop.hdfs.shortcircuit.ShortCircuitCache.create(ShortCircuitCache.java:783)
    at org.apache.hadoop.hdfs.shortcircuit.ShortCircuitCache.fetchOrCreate(ShortCircuitCache.java:717)
    at org.apache.hadoop.hdfs.BlockReaderFactory.getBlockReaderLocal(BlockReaderFactory.java:421)
    at org.apache.hadoop.hdfs.BlockReaderFactory.build(BlockReaderFactory.java:332)
    at org.apache.hadoop.hdfs.DFSInputStream.blockSeekTo(DFSInputStream.java:617)
    at org.apache.hadoop.hdfs.DFSInputStream.readWithStrategy(DFSInputStream.java:841)
    at org.apache.hadoop.hdfs.DFSInputStream.read(DFSInputStream.java:889)
    at org.apache.hadoop.hdfs.DFSInputStream.read(DFSInputStream.java:696)
    at java.io.DataInputStream.readByte(DataInputStream.java:265)
    at org.apache.hadoop.io.WritableUtils.readVLong(WritableUtils.java:308)
    at org.apache.hadoop.io.WritableUtils.readVIntInRange(WritableUtils.java:348)
    at org.apache.hadoop.io.Text.readString(Text.java:471)
    at org.apache.hadoop.io.Text.readString(Text.java:464)
    at org.apache.hadoop.mapred.MapTask.getSplitDetails(MapTask.java:358)
    at org.apache.hadoop.mapred.MapTask.runNewMapper(MapTask.java:751)
    at org.apache.hadoop.mapred.MapTask.run(MapTask.java:341)
    at org.apache.hadoop.mapred.YarnChild$2.run(YarnChild.java:163)
    at java.security.AccessController.doPrivileged(Native Method)
    at javax.security.auth.Subject.doAs(Subject.java:422)
    at org.apache.hadoop.security.UserGroupInformation.doAs(UserGroupInformation.java:1656)
    at org.apache.hadoop.mapred.YarnChild.main(YarnChild.java:158)
2017-03-31 21:59:01,277 WARN [main] org.apache.hadoop.hdfs.shortcircuit.ShortCircuitCache: ShortCircuitCache(0x34f7234e): failed to load 1073750370_BP-642933002-"IP_ADDRESS"-1490774107737

EDIT

hadoop 2.6.4
hbase 1.2.3

hdfs-site.xml

<property>
    <name>dfs.namenode.dir</name>
    <value>/home/hadoop/hdfs/nn</value>
</property>
<property>
    <name>dfs.namenode.checkpoint.dir</name>
    <value>/home/hadoop/hdfs/snn</value>
</property>
<property>
    <name>dfs.datanode.data.dir</name>
    <value>file:///home/hadoop/hdfs/dn</value>
</property>
<property>
    <name>dfs.namenode.http-address</name>
    <value>hadoop1:50070</value>
</property>
<property>
    <name>dfs.namenode.secondary.http-address</name>
    <value>hadoop1:50090</value>
</property>
<property>
    <name>dfs.namenode.rpc-address</name>
    <value>hadoop1:8020</value>
</property>
<property>
    <name>dfs.namenode.handler.count</name>
    <value>50</value>
</property>
<property>
    <name>dfs.datanode.handler.count</name>
    <value>50</value>
</property>
<property>
    <name>dfs.client.read.shortcircuit</name>
    <value>true</value>
</property>
<property>
    <name>dfs.block.local-path-access.user</name>
    <value>hbase</value>
</property>
<property>
    <name>dfs.datanode.data.dir.perm</name>
    <value>775</value>
</property>
<property>
    <name>dfs.domain.socket.path</name>
    <value>_PORT</value>
</property>
<property>
    <name>dfs.client.domain.socket.traffic</name>
    <value>true</value>
</property>

hbase-site.xml

<property>
    <name>hbase.rootdir</name>
    <value>hdfs://hadoop1/hbase</value>
</property>
<property>
    <name>hbase.zookeeper.quorum</name>
        <value>hadoop1,hadoop2,hadoop3,hadoop4,hadoop5,hadoop6,hadoop7,hadoop8</value>
</property>
<property>
    <name>hbase.cluster.distributed</name>
    <value>true</value>
</property>
<property>
    <name>dfs.client.read.shortcircuit</name>
    <value>true</value>
</property>
<property>
    <name>hbase.regionserver.handler.count</name>
    <value>50</value>
</property>
<property>
    <name>hfile.block.cache.size</name>
    <value>0.5</value>
</property>
<property>
    <name>hbase.regionserver.global.memstore.size</name>
    <value>0.3</value>
</property>
<property>
    <name>hbase.regionserver.global.memstore.size.lower.limit</name>
    <value>0.65</value>
</property>
<property>
    <name>dfs.domain.socket.path</name>
    <value>_PORT</value>
</property>

Body:
Short-circuit reads make use of a UNIX domain socket. This is a special path in the filesystem that allows the Client and the DataNodes to communicate. You will need to set a path (not port) to this socket. The DataNode should be able to create this path.

The parent directory of the path value (for ex: /var/lib/hadoop-hdfs/) must exist and should be owned by the hadoop superuser. Also make sure any user except the HDFS user or root has no access to this path.

mkdir /var/lib/hadoop-hdfs/
chown hdfs_user:hdfs_user /var/lib/hadoop-hdfs/
chmod 750 /var/lib/hadoop-hdfs/

Add this property to hdfs-site.xml on all datanodes and clients.

<property>
  <name>dfs.domain.socket.path</name>
  <value>/var/lib/hadoop-hdfs/dn_socket</value>
</property>

Restart the services after making the changes.

Note: Paths under /var/run or /var/lib are commonly used.


问:
Varnish won't start as a daemon
Varnish fails to start using:

```<code>service varnish start
</code>```

without any errors, but runs fine when I do:

```<code>varnishd -f /etc/varnish/user.vcl -s malloc,1G -T localhost:6082  -a 0.0.0.0:6081 -d
</code>```

This is /etc/default/varnish:

```<code>START=yes
NFILES=131072
MEMLOCK=82000

DAEMON_OPTS="-a 0.0.0.0:6081 \
         -T localhost:6082 \
         -f /etc/varnish/user.vcl \
         -S /etc/varnish/secret \
         -s malloc,1024m"
</code>```

I'm on Ubuntu 16.04. Any thoughts?

Update (version, syslog and systemd):

Version:

```<code># varnishd -V
varnishd (varnish-4.1.1 revision 66bb824)
Copyright (c) 2006 Verdens Gang AS
Copyright (c) 2006-2015 Varnish Software AS
</code>```

This is syslog:

```<code>Nov 30 14:16:46 **** systemd[1]: Started Varnish HTTP accelerator.
Nov 30 14:16:46 **** varnishd[28089]: Error: Cannot open socket: :6081: Address family not supported by protocol
Nov 30 14:16:46 **** systemd[1]: varnish.service: Main process exited, code=exited, status=2/INVALIDARGUMENT
Nov 30 14:16:46 **** systemd[1]: varnish.service: Unit entered failed state.
Nov 30 14:16:46 **** systemd[1]: varnish.service: Failed with result 'exit-code'.
</code>```

/etc/init.d/varnish:

```<code>#! /bin/sh

### BEGIN INIT INFO
# Provides:          varnish
# Required-Start:    $local_fs $remote_fs $network
# Required-Stop:     $local_fs $remote_fs $network
# Default-Start:     2 3 4 5
# Default-Stop:      0 1 6
# Short-Description: Start HTTP accelerator
# Description:       This script provides a server-side cache
#                    to be run in front of a httpd and should
#                    listen on port 80 on a properly configured
#                    system
### END INIT INFO

# Source function library
. /lib/lsb/init-functions

NAME=varnishd
DESC="HTTP accelerator"
PATH=/sbin:/bin:/usr/sbin:/usr/bin
DAEMON=/usr/sbin/varnishd
PIDFILE=/run/$NAME.pid

test -x $DAEMON || exit 0

# Include varnish defaults if available
if [ -f /etc/default/varnish ] ; then
        . /etc/default/varnish
fi

# Open files (usually 1024, which is way too small for varnish)
ulimit -n ${NFILES:-131072}

# Maxiumum locked memory size for shared memory log
ulimit -l ${MEMLOCK:-82000}

# If $DAEMON_OPTS is not set at all in /etc/default/varnish, use minimal useful
# defaults (Backend at localhost:8080, a common place to put a locally
# installed application server.)
DAEMON_OPTS=${DAEMON_OPTS:--b localhost}

# Ensure we have a PATH
export PATH="${PATH:+$PATH:}/usr/sbin:/usr/bin:/sbin:/bin"

start_varnishd() {
    log_daemon_msg "Starting $DESC" "$NAME"
    output=$(/bin/tempfile -s.varnish)
    if start-stop-daemon \
        --start --quiet --pidfile ${PIDFILE} --exec ${DAEMON} -- \
        -P ${PIDFILE} ${DAEMON_OPTS} > ${output} 2>&1; then
        log_end_msg 0
    else
        log_end_msg 1
        cat $output
        exit 1
    fi
    rm $output
}

disabled_varnishd() {
    log_daemon_msg "Not starting $DESC" "$NAME"
    log_progress_msg "disabled in /etc/default/varnish"
    log_end_msg 0
}

stop_varnishd() {
    log_daemon_msg "Stopping $DESC" "$NAME"
    if start-stop-daemon \
        --stop --quiet --pidfile $PIDFILE --retry 10 \
        --exec $DAEMON; then
        log_end_msg 0
    else
        log_end_msg 1
    fi

    if test -r $PIDFILE; then
        read -r PID < $PIDFILE
        if test ! -d /proc/$PID ; then
            # stale pidfile
            unset PID
            rm -f $PIDFILE
        fi
    fi
}

reload_varnishd() {
    log_daemon_msg "Reloading $DESC" "$NAME"
    if /usr/share/varnish/reload-vcl -q; then
        log_end_msg 0
    else
        log_end_msg 1
    fi
}

status_varnishd() {
    start-stop-daemon \
        --status --quiet --pidfile $PIDFILE \
        --exec $DAEMON
    exit $?
}

configtest() {
    $DAEMON ${DAEMON_OPTS} -C -n /tmp > /dev/null
}

case "$1" in
    start)
        case "${START:-}" in
            [Yy]es|[Yy]|1|[Tt]|[Tt]rue)
                start_varnishd
                ;;
            *)
                disabled_varnishd
                ;;
        esac
        ;;
    stop)
        stop_varnishd
        ;;
    reload)
        reload_varnishd
        ;;
    status)
        status_varnishd
        ;;
    restart|force-reload)
        if status_of_proc -p "${PIDFILE}" "${DAEMON}" "${NAME}" 1>/dev/null; then
            if ! configtest; then
            log_failure_msg "Syntax check failed, not restarting"
            exit 1
            fi
        fi
        $0 stop
        $0 start
        ;;
    configtest)
        configtest && log_success_msg "Syntax ok"
        ;;
    *)
        log_success_msg "Usage: $0 {start|stop|restart|reload|force-reload|configtest}"
        exit 1
        ;;
esac
</code>```

答:
I ran into the exact same issue moving my production environment to a less... ancient Opsworks/Chef stack with Ubuntu.

It turned out that the docs on the Varnish site were not quite complete for Ubuntu 16+, you need a few other command line switches. This is what works for me:

```<code>[Service]
ExecStart=
ExecStart=/usr/sbin/varnishd -j unix,user=vcache -F -a :80 -T localhost:6082 -f /etc/varnish/default.vcl -S /etc/varnish/secret -s malloc,256m
</code>```

The -F switch moves it into the foreground, which I've found helps with systemctl services.

The -j switch enables the Varnish privilege jail (more on that here: https://www.varnish-cache.org/docs/4.1/reference/varnishd.html?highlight=jail#jail).

Title: Varnish won't start as a daemon

Body:
Varnish fails to start using:

service varnish start

without any errors, but runs fine when I do:

varnishd -f /etc/varnish/user.vcl -s malloc,1G -T localhost:6082  -a 0.0.0.0:6081 -d

This is /etc/default/varnish:

START=yes
NFILES=131072
MEMLOCK=82000

DAEMON_OPTS="-a 0.0.0.0:6081 \
         -T localhost:6082 \
         -f /etc/varnish/user.vcl \
         -S /etc/varnish/secret \
         -s malloc,1024m"

I'm on Ubuntu 16.04. Any thoughts?

Update (version, syslog and systemd):

Version:

# varnishd -V
varnishd (varnish-4.1.1 revision 66bb824)
Copyright (c) 2006 Verdens Gang AS
Copyright (c) 2006-2015 Varnish Software AS

This is syslog:

Nov 30 14:16:46 **** systemd[1]: Started Varnish HTTP accelerator.
Nov 30 14:16:46 **** varnishd[28089]: Error: Cannot open socket: :6081: Address family not supported by protocol
Nov 30 14:16:46 **** systemd[1]: varnish.service: Main process exited, code=exited, status=2/INVALIDARGUMENT
Nov 30 14:16:46 **** systemd[1]: varnish.service: Unit entered failed state.
Nov 30 14:16:46 **** systemd[1]: varnish.service: Failed with result 'exit-code'.

/etc/init.d/varnish:

#! /bin/sh

### BEGIN INIT INFO
# Provides:          varnish
# Required-Start:    $local_fs $remote_fs $network
# Required-Stop:     $local_fs $remote_fs $network
# Default-Start:     2 3 4 5
# Default-Stop:      0 1 6
# Short-Description: Start HTTP accelerator
# Description:       This script provides a server-side cache
#                    to be run in front of a httpd and should
#                    listen on port 80 on a properly configured
#                    system
### END INIT INFO

# Source function library
. /lib/lsb/init-functions

NAME=varnishd
DESC="HTTP accelerator"
PATH=/sbin:/bin:/usr/sbin:/usr/bin
DAEMON=/usr/sbin/varnishd
PIDFILE=/run/$NAME.pid

test -x $DAEMON || exit 0

# Include varnish defaults if available
if [ -f /etc/default/varnish ] ; then
        . /etc/default/varnish
fi

# Open files (usually 1024, which is way too small for varnish)
ulimit -n ${NFILES:-131072}

# Maxiumum locked memory size for shared memory log
ulimit -l ${MEMLOCK:-82000}

# If $DAEMON_OPTS is not set at all in /etc/default/varnish, use minimal useful
# defaults (Backend at localhost:8080, a common place to put a locally
# installed application server.)
DAEMON_OPTS=${DAEMON_OPTS:--b localhost}

# Ensure we have a PATH
export PATH="${PATH:+$PATH:}/usr/sbin:/usr/bin:/sbin:/bin"

start_varnishd() {
    log_daemon_msg "Starting $DESC" "$NAME"
    output=$(/bin/tempfile -s.varnish)
    if start-stop-daemon \
        --start --quiet --pidfile ${PIDFILE} --exec ${DAEMON} -- \
        -P ${PIDFILE} ${DAEMON_OPTS} > ${output} 2>&1; then
        log_end_msg 0
    else
        log_end_msg 1
        cat $output
        exit 1
    fi
    rm $output
}

disabled_varnishd() {
    log_daemon_msg "Not starting $DESC" "$NAME"
    log_progress_msg "disabled in /etc/default/varnish"
    log_end_msg 0
}

stop_varnishd() {
    log_daemon_msg "Stopping $DESC" "$NAME"
    if start-stop-daemon \
        --stop --quiet --pidfile $PIDFILE --retry 10 \
        --exec $DAEMON; then
        log_end_msg 0
    else
        log_end_msg 1
    fi

    if test -r $PIDFILE; then
        read -r PID < $PIDFILE
        if test ! -d /proc/$PID ; then
            # stale pidfile
            unset PID
            rm -f $PIDFILE
        fi
    fi
}

reload_varnishd() {
    log_daemon_msg "Reloading $DESC" "$NAME"
    if /usr/share/varnish/reload-vcl -q; then
        log_end_msg 0
    else
        log_end_msg 1
    fi
}

status_varnishd() {
    start-stop-daemon \
        --status --quiet --pidfile $PIDFILE \
        --exec $DAEMON
    exit $?
}

configtest() {
    $DAEMON ${DAEMON_OPTS} -C -n /tmp > /dev/null
}

case "$1" in
    start)
        case "${START:-}" in
            [Yy]es|[Yy]|1|[Tt]|[Tt]rue)
                start_varnishd
                ;;
            *)
                disabled_varnishd
                ;;
        esac
        ;;
    stop)
        stop_varnishd
        ;;
    reload)
        reload_varnishd
        ;;
    status)
        status_varnishd
        ;;
    restart|force-reload)
        if status_of_proc -p "${PIDFILE}" "${DAEMON}" "${NAME}" 1>/dev/null; then
            if ! configtest; then
            log_failure_msg "Syntax check failed, not restarting"
            exit 1
            fi
        fi
        $0 stop
        $0 start
        ;;
    configtest)
        configtest && log_success_msg "Syntax ok"
        ;;
    *)
        log_success_msg "Usage: $0 {start|stop|restart|reload|force-reload|configtest}"
        exit 1
        ;;
esac

Body:
I ran into the exact same issue moving my production environment to a less... ancient Opsworks/Chef stack with Ubuntu.

It turned out that the docs on the Varnish site were not quite complete for Ubuntu 16+, you need a few other command line switches. This is what works for me:

[Service]
ExecStart=
ExecStart=/usr/sbin/varnishd -j unix,user=vcache -F -a :80 -T localhost:6082 -f /etc/varnish/default.vcl -S /etc/varnish/secret -s malloc,256m

The -F switch moves it into the foreground, which I've found helps with systemctl services.

The -j switch enables the Varnish privilege jail (more on that here: https://www.varnish-cache.org/docs/4.1/reference/varnishd.html?highlight=jail#jail).


问:
How to append value to an array keeping old value intact in Javascript?
Google visualization API requires arrays like this:

```<code>var data = google.visualization.arrayToDataTable([
         ['Element', 'Density', { role: 'style' }],
         ['Copper', 8.94, '#b87333'],            // RGB value
         ['Copper', 10.49, 'silver'],            // English color name
         ['Gold', 19.30, 'gold'],
         ['Gold', 21.45, 'color: #e5e4e2' ], // CSS-style declaration
      ]);
</code>```

I have separately array of columns

```<code>var columns = ['Copper', 'Copper', 'Gold', 'Gold'];
</code>```

for values

```<code>var values = [8.94, 10.49, 19.30, 21.45];
</code>```

and for colors

```<code>var styles = ['#b87333', 'silver', 'gold', 'color: #e5e4e2'];
</code>```

Am I really in need to write multilevel loop with multiple conditions to build this array? Or there are simpler ways?

I can't push because arrays should be intact.

答:
You can map them together, here is a working fiddle</p>

```<code>var columns = ['Copper', 'Copper', 'Gold', 'Gold'];
var values = [8.94, 10.49, 19.30, 21.45];
var styles = ['#b87333', 'silver', 'gold', 'color: #e5e4e2'];

var newArr = columns.map((item, index) => {return [columns[index], values[index], styles[index]]})

console.log(newArr) //=> ['Copper', 8.94, '#b87333'],
                    //['Copper', 10.49, 'silver'],
                    //['Gold', 19.30, 'gold'],
                    //['Gold', 21.45, 'color: #e5e4e2' ],
</code>```

Body:
Google visualization API requires arrays like this:

var data = google.visualization.arrayToDataTable([
         ['Element', 'Density', { role: 'style' }],
         ['Copper', 8.94, '#b87333'],            // RGB value
         ['Copper', 10.49, 'silver'],            // English color name
         ['Gold', 19.30, 'gold'],
         ['Gold', 21.45, 'color: #e5e4e2' ], // CSS-style declaration
      ]);

I have separately array of columns

var columns = ['Copper', 'Copper', 'Gold', 'Gold'];

for values

var values = [8.94, 10.49, 19.30, 21.45];

and for colors

var styles = ['#b87333', 'silver', 'gold', 'color: #e5e4e2'];

Am I really in need to write multilevel loop with multiple conditions to build this array? Or there are simpler ways?

I can't push because arrays should be intact.

Body:
You can map them together, here is a working fiddle

var columns = ['Copper', 'Copper', 'Gold', 'Gold'];
var values = [8.94, 10.49, 19.30, 21.45];
var styles = ['#b87333', 'silver', 'gold', 'color: #e5e4e2'];

var newArr = columns.map((item, index) => {return [columns[index], values[index], styles[index]]})

console.log(newArr) //=> ['Copper', 8.94, '#b87333'],
                    //['Copper', 10.49, 'silver'],
                    //['Gold', 19.30, 'gold'],
                    //['Gold', 21.45, 'color: #e5e4e2' ],


问:
Assist with simple count out of a list
I'm trying to count the number of people marked as Break in a column in a list.

currently when I run my foreach loop (the one at the bottom) to count the number of breaks listed it throws the error message cannot convert type char to string. I understand that my class of NewAgent does not contain all string values but I'm only trying to reference one string.  I need a way to count the number of times break appears in my list. Break would appear under newAgent.auxreason

```<code>public List newAgentList;
List<NewAgent> newAgentList = new List<NewAgent>();

NewAgent newAgents = new ScoreBoardClientTest.NewAgent();

foreach (var item in e.CmsData.Agents)
{

    newAgents.AgentName = item.AgName;

    newAgents.AgentExtension = item.Extension;

    newAgents.AgentDateTimeChange = ConvertedDateTimeUpdated;

    newAgents.AuxReasons = item.AuxReasonDescription;

    newAgents.LoginIdentifier = item.LoginId;

    newAgents.AgentState = item.WorkModeDirectionDescription;

    var timeSpanSince = DateTime.Now - item.DateTimeUpdated;
    newAgents.AgentDateTimeStateChange = timeSpanSince;

    newAgentList.Add(newAgents);
}

int breakCount = 0;
foreach(string s in newAgents.AuxReasons)
{
    if (s != null && s.StartsWith("Break")) breakCount++;
}
</code>```

答:
First, you need to put NewAgent newAgents = new ScoreBoardClientTest.NewAgent(); inside your first foreach loop because right now you are working with reference to the same object and if you update any property of this object in one place it will be updated for the entire list.

Second, you need to work with newAgentList in the second loop and not with newAgents (this is why you are seeing the exception since you are going trough chars inside the string instead of going trough elements of a list).

This should work:

```<code>public List newAgentList;
List<NewAgent> newAgentList = new List<NewAgent>();

foreach (var item in e.CmsData.Agents)
{
    NewAgent newAgents = new ScoreBoardClientTest.NewAgent();

    newAgents.AgentName = item.AgName;
    newAgents.AgentExtension = item.Extension;
    newAgents.AgentDateTimeChange = ConvertedDateTimeUpdated;
    newAgents.AuxReasons = item.AuxReasonDescription;
    newAgents.LoginIdentifier = item.LoginId;
    newAgents.AgentState = item.WorkModeDirectionDescription;

    var timeSpanSince = DateTime.Now - item.DateTimeUpdated;
    newAgents.AgentDateTimeStateChange = timeSpanSince;

    newAgentList.Add(newAgents);
}

int breakCount = 0;
foreach(string s in newAgentList.AuxReasons)
{
    if (!string.IsNullOrWhiteSpace(s.AuxReasons) && s.AuxReasons.StartsWith("Break")) breakCount++;
}
</code>```

Title: Assist with simple count out of a list

Body:
I'm trying to count the number of people marked as Break in a column in a list.

currently when I run my foreach loop (the one at the bottom) to count the number of breaks listed it throws the error message cannot convert type char to string. I understand that my class of NewAgent does not contain all string values but I'm only trying to reference one string.  I need a way to count the number of times break appears in my list. Break would appear under newAgent.auxreason

public List newAgentList;
List<NewAgent> newAgentList = new List<NewAgent>();

NewAgent newAgents = new ScoreBoardClientTest.NewAgent();

foreach (var item in e.CmsData.Agents)
{

    newAgents.AgentName = item.AgName;

    newAgents.AgentExtension = item.Extension;

    newAgents.AgentDateTimeChange = ConvertedDateTimeUpdated;

    newAgents.AuxReasons = item.AuxReasonDescription;

    newAgents.LoginIdentifier = item.LoginId;

    newAgents.AgentState = item.WorkModeDirectionDescription;

    var timeSpanSince = DateTime.Now - item.DateTimeUpdated;
    newAgents.AgentDateTimeStateChange = timeSpanSince;

    newAgentList.Add(newAgents);
}

int breakCount = 0;
foreach(string s in newAgents.AuxReasons)
{
    if (s != null && s.StartsWith("Break")) breakCount++;
}

Body:
First, you need to put NewAgent newAgents = new ScoreBoardClientTest.NewAgent(); inside your first foreach loop because right now you are working with reference to the same object and if you update any property of this object in one place it will be updated for the entire list.

Second, you need to work with newAgentList in the second loop and not with newAgents (this is why you are seeing the exception since you are going trough chars inside the string instead of going trough elements of a list).

This should work:

public List newAgentList;
List<NewAgent> newAgentList = new List<NewAgent>();

foreach (var item in e.CmsData.Agents)
{
    NewAgent newAgents = new ScoreBoardClientTest.NewAgent();

    newAgents.AgentName = item.AgName;
    newAgents.AgentExtension = item.Extension;
    newAgents.AgentDateTimeChange = ConvertedDateTimeUpdated;
    newAgents.AuxReasons = item.AuxReasonDescription;
    newAgents.LoginIdentifier = item.LoginId;
    newAgents.AgentState = item.WorkModeDirectionDescription;

    var timeSpanSince = DateTime.Now - item.DateTimeUpdated;
    newAgents.AgentDateTimeStateChange = timeSpanSince;

    newAgentList.Add(newAgents);
}

int breakCount = 0;
foreach(string s in newAgentList.AuxReasons)
{
    if (!string.IsNullOrWhiteSpace(s.AuxReasons) && s.AuxReasons.StartsWith("Break")) breakCount++;
}


问:
Error in sending data (post) from AJAX to NODEJS app
I need to get data sent from ajax to nodejs.
Here is AJAX side:

```<code> $.ajax({
  type:"POST",
  url: "http://127.0.0.1:3000/a",
  data: { id: "2" },
  dataType: 'jsonp',
  contentType: "application/json",
  success: function fun(json) {
    console.log(JSON.stringify(json));
  }
})
</code>```

And In Node:

```<code>var express = require('express')
var bodyParser = require('body-parser')
var app = express()
app.use(bodyParser.json())
var quizzController = require('./quizzController')

app.post('/a', function (req,rep) {
  rep.send('ok')
  console.log(req.body.id)
})
app.listen(3000)
</code>```

When I send, I get this error in AJAX side:

```<code>GET http://127.0.0.1:3000/a?                              callback=jQuery111105826120341114538_1490969686792&id=2&_=1490969686793
</code>```

答:
You cannot do a POST using JSONP as datatype. You can only do a HTTP/GET. If you have CORS issue, you have to enable cross-origin request sharing in the server side. Something like :</p>

```<code>app.use(function(req, res, next) {
  res.header("Access-Control-Allow-Origin", "*");
  res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
  next();
});
</code>```

Body:
I need to get data sent from ajax to nodejs.
Here is AJAX side:

 $.ajax({
  type:"POST",
  url: "http://127.0.0.1:3000/a",
  data: { id: "2" },
  dataType: 'jsonp',
  contentType: "application/json",
  success: function fun(json) {
    console.log(JSON.stringify(json));
  }
})

And In Node:

var express = require('express')
var bodyParser = require('body-parser')
var app = express()
app.use(bodyParser.json())
var quizzController = require('./quizzController')

app.post('/a', function (req,rep) {
  rep.send('ok')
  console.log(req.body.id)
})
app.listen(3000)

When I send, I get this error in AJAX side:

GET http://127.0.0.1:3000/a?                              callback=jQuery111105826120341114538_1490969686792&id=2&_=1490969686793

Body:
You cannot do a POST using JSONP as datatype. You can only do a HTTP/GET. If you have CORS issue, you have to enable cross-origin request sharing in the server side. Something like :

app.use(function(req, res, next) {
  res.header("Access-Control-Allow-Origin", "*");
  res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
  next();
});


问:
JPA Inheritance. Setting value Exeption in EclipseLink
I'm getting the following exception when attempting to persist an entity during a JUnit test.  I'm using Eclipselink 2.5.2.  I cant find what might be causing this exception.

```<code>Exception in thread "Thread-3" javax.persistence.RollbackException: Exception [EclipseLink-32] (Eclipse Persistence Services - 2.5.2.v20140319-9ad6abd): org.eclipse.persistence.exceptions.DescriptorException
Exception Description: Trying to set value [165.0] for instance variable [doubleValue] of type [java.lang.Double] in the object.  The specified object is not an instance of the class or interface declaring the underlying field, or an unwrapping conversion has failed.
Internal Exception: java.lang.IllegalArgumentException: Can not set java.lang.Double field ar.asimov.acumar.ema.model.DoubleListValue.doubleValue to ar.asimov.acumar.ema.model.ExtraHumidity
Mapping: org.eclipse.persistence.mappings.DirectToFieldMapping[doubleValue-->ta_ams_weather_list_parameters.double_value]
Descriptor: RelationalDescriptor(ar.asimov.acumar.ema.model.ExtraTemperature --> [DatabaseTable(ta_ams_weather_list_parameters)])
    at org.eclipse.persistence.internal.jpa.transaction.EntityTransactionImpl.commit(EntityTransactionImpl.java:157)
    at ar.asimov.acumar.ema.model.helper.EntityManagerHelper.commitTransaction(EntityManagerHelper.java:41)
    at ar.asimov.acumar.ema.services.WeatherDataConsumer.run(WeatherDataConsumer.java:51)
    at java.lang.Thread.run(Thread.java:745)
Caused by: Exception [EclipseLink-32] (Eclipse Persistence Services - 2.5.2.v20140319-9ad6abd): org.eclipse.persistence.exceptions.DescriptorException
Exception Description: Trying to set value [165.0] for instance variable [doubleValue] of type [java.lang.Double] in the object.  The specified object is not an instance of the class or interface declaring the underlying field, or an unwrapping conversion has failed.
Internal Exception: java.lang.IllegalArgumentException: Can not set java.lang.Double field ar.asimov.acumar.ema.model.DoubleListValue.doubleValue to ar.asimov.acumar.ema.model.ExtraHumidity
Mapping: org.eclipse.persistence.mappings.DirectToFieldMapping[doubleValue-->ta_ams_weather_list_parameters.double_value]
Descriptor: RelationalDescriptor(ar.asimov.acumar.ema.model.ExtraTemperature --> [DatabaseTable(ta_ams_weather_list_parameters)])
    at org.eclipse.persistence.exceptions.DescriptorException.illegalArgumentWhileSettingValueThruInstanceVariableAccessor(DescriptorException.java:703)
    at org.eclipse.persistence.internal.descriptors.InstanceVariableAttributeAccessor.setAttributeValueInObject(InstanceVariableAttributeAccessor.java:188)
    at org.eclipse.persistence.mappings.DatabaseMapping.setAttributeValueInObject(DatabaseMapping.java:1625)
    at org.eclipse.persistence.mappings.foundation.AbstractDirectMapping.mergeIntoObject(AbstractDirectMapping.java:1040)
    at org.eclipse.persistence.internal.descriptors.ObjectBuilder.mergeIntoObject(ObjectBuilder.java:4132)
    at org.eclipse.persistence.internal.descriptors.ObjectBuilder.mergeChangesIntoObject(ObjectBuilder.java:4065)
    at org.eclipse.persistence.internal.sessions.MergeManager.mergeChangesOfWorkingCopyIntoOriginal(MergeManager.java:884)
    at org.eclipse.persistence.internal.sessions.MergeManager.mergeChangesOfWorkingCopyIntoOriginal(MergeManager.java:698)
    at org.eclipse.persistence.internal.sessions.MergeManager.mergeChanges(MergeManager.java:309)
    at org.eclipse.persistence.mappings.CollectionMapping.mergeIntoObject(CollectionMapping.java:1638)
    at org.eclipse.persistence.internal.descriptors.ObjectBuilder.mergeIntoObject(ObjectBuilder.java:4132)
    at org.eclipse.persistence.internal.descriptors.ObjectBuilder.mergeChangesIntoObject(ObjectBuilder.java:4065)
    at org.eclipse.persistence.internal.sessions.MergeManager.mergeChangesOfWorkingCopyIntoOriginal(MergeManager.java:839)
    at org.eclipse.persistence.internal.sessions.MergeManager.mergeChangesOfWorkingCopyIntoOriginal(MergeManager.java:698)
    at org.eclipse.persistence.internal.sessions.MergeManager.mergeChanges(MergeManager.java:309)
    at org.eclipse.persistence.internal.sessions.UnitOfWorkImpl.mergeChangesIntoParent(UnitOfWorkImpl.java:3280)
    at org.eclipse.persistence.internal.sessions.RepeatableWriteUnitOfWork.mergeChangesIntoParent(RepeatableWriteUnitOfWork.java:376)
    at org.eclipse.persistence.internal.sessions.RepeatableWriteUnitOfWork.commitRootUnitOfWork(RepeatableWriteUnitOfWork.java:290)
    at org.eclipse.persistence.internal.sessions.UnitOfWorkImpl.commitAndResume(UnitOfWorkImpl.java:1169)
    at org.eclipse.persistence.internal.jpa.transaction.EntityTransactionImpl.commit(EntityTransactionImpl.java:132)
    ... 3 more
Caused by: java.lang.IllegalArgumentException: Can not set java.lang.Double field ar.asimov.acumar.ema.model.DoubleListValue.doubleValue to ar.asimov.acumar.ema.model.ExtraHumidity
    at sun.reflect.UnsafeFieldAccessorImpl.throwSetIllegalArgumentException(UnsafeFieldAccessorImpl.java:167)
    at sun.reflect.UnsafeFieldAccessorImpl.throwSetIllegalArgumentException(UnsafeFieldAccessorImpl.java:171)
    at sun.reflect.UnsafeFieldAccessorImpl.ensureObj(UnsafeFieldAccessorImpl.java:58)
    at sun.reflect.UnsafeObjectFieldAccessorImpl.set(UnsafeObjectFieldAccessorImpl.java:75)
    at java.lang.reflect.Field.set(Field.java:764)
    at org.eclipse.persistence.internal.descriptors.InstanceVariableAttributeAccessor.setAttributeValueInObject(InstanceVariableAttributeAccessor.java:141)
    ... 21 more
</code>```

I have the following classes in my model (i'm omitting the getters and setters
for simplicity)

```<code>@IdClass(ListParameterValue.PrimaryKey.class)
@Entity
@Inheritance(strategy=InheritanceType.SINGLE_TABLE)
@DiscriminatorColumn(discriminatorType=DiscriminatorType.STRING, name="parameter_type",length=20)
@Table(name="ta_ams_weather_list_parameters")
@Access(AccessType.FIELD)
public abstract class ListParameterValue implements Serializable {

    private static final long serialVersionUID = 1L;

    public static class PrimaryKey implements Serializable{...}

    @Id
    @ManyToOne
    @JoinColumn(name="station_id",referencedColumnName="station_id")
    protected Station station;
    @Id
    @Column(name="date")
    protected LocalDate date;
    @Id
    @Column(name="start_time")
    protected LocalTime startTime;
    @Id
    @Column(name="order_index")
    protected Integer order;
    @Id
    @Column(name="parameter_type")
    protected String type;

}

@MappedSuperclass
@Access(AccessType.FIELD)
public abstract class DoubleListValue extends ListParameterValue implements Serializable {

    private static final long serialVersionUID = 1L;

    @Column(name="double_value", nullable = true, columnDefinition="default null")
    protected Double doubleValue;

}

@MappedSuperclass
@Access(AccessType.FIELD)
public abstract class ShortListValue extends ListParameterValue implements Serializable {

    private static final long serialVersionUID = 1L;

    @Column(name="short_value")
    protected Short shortValue;

}

@Entity
@DiscriminatorValue("extra_humidity")
public class ExtraHumidity extends ShortListValue implements Serializable{

    /**
     *
     */
    private static final long serialVersionUID = 1L;

    public ExtraHumidity() {
     super();
    }

}
</code>```

I would really appreciate the help.
Thanks in advance

答:
I'm guessing your test has a bug in that it is trying to create an instance of something that extends DoubleListValue and merge it in, but giving it and ID that already is used by an instance of ExtraHumidity.  This is illegal, as you cannot change the type of an entity without first removing and then re-inserting the entity.

We can't say how this occurs without seeing your test.

Body:
I'm getting the following exception when attempting to persist an entity during a JUnit test.  I'm using Eclipselink 2.5.2.  I cant find what might be causing this exception.

Exception in thread "Thread-3" javax.persistence.RollbackException: Exception [EclipseLink-32] (Eclipse Persistence Services - 2.5.2.v20140319-9ad6abd): org.eclipse.persistence.exceptions.DescriptorException
Exception Description: Trying to set value [165.0] for instance variable [doubleValue] of type [java.lang.Double] in the object.  The specified object is not an instance of the class or interface declaring the underlying field, or an unwrapping conversion has failed.
Internal Exception: java.lang.IllegalArgumentException: Can not set java.lang.Double field ar.asimov.acumar.ema.model.DoubleListValue.doubleValue to ar.asimov.acumar.ema.model.ExtraHumidity
Mapping: org.eclipse.persistence.mappings.DirectToFieldMapping[doubleValue-->ta_ams_weather_list_parameters.double_value]
Descriptor: RelationalDescriptor(ar.asimov.acumar.ema.model.ExtraTemperature --> [DatabaseTable(ta_ams_weather_list_parameters)])
    at org.eclipse.persistence.internal.jpa.transaction.EntityTransactionImpl.commit(EntityTransactionImpl.java:157)
    at ar.asimov.acumar.ema.model.helper.EntityManagerHelper.commitTransaction(EntityManagerHelper.java:41)
    at ar.asimov.acumar.ema.services.WeatherDataConsumer.run(WeatherDataConsumer.java:51)
    at java.lang.Thread.run(Thread.java:745)
Caused by: Exception [EclipseLink-32] (Eclipse Persistence Services - 2.5.2.v20140319-9ad6abd): org.eclipse.persistence.exceptions.DescriptorException
Exception Description: Trying to set value [165.0] for instance variable [doubleValue] of type [java.lang.Double] in the object.  The specified object is not an instance of the class or interface declaring the underlying field, or an unwrapping conversion has failed.
Internal Exception: java.lang.IllegalArgumentException: Can not set java.lang.Double field ar.asimov.acumar.ema.model.DoubleListValue.doubleValue to ar.asimov.acumar.ema.model.ExtraHumidity
Mapping: org.eclipse.persistence.mappings.DirectToFieldMapping[doubleValue-->ta_ams_weather_list_parameters.double_value]
Descriptor: RelationalDescriptor(ar.asimov.acumar.ema.model.ExtraTemperature --> [DatabaseTable(ta_ams_weather_list_parameters)])
    at org.eclipse.persistence.exceptions.DescriptorException.illegalArgumentWhileSettingValueThruInstanceVariableAccessor(DescriptorException.java:703)
    at org.eclipse.persistence.internal.descriptors.InstanceVariableAttributeAccessor.setAttributeValueInObject(InstanceVariableAttributeAccessor.java:188)
    at org.eclipse.persistence.mappings.DatabaseMapping.setAttributeValueInObject(DatabaseMapping.java:1625)
    at org.eclipse.persistence.mappings.foundation.AbstractDirectMapping.mergeIntoObject(AbstractDirectMapping.java:1040)
    at org.eclipse.persistence.internal.descriptors.ObjectBuilder.mergeIntoObject(ObjectBuilder.java:4132)
    at org.eclipse.persistence.internal.descriptors.ObjectBuilder.mergeChangesIntoObject(ObjectBuilder.java:4065)
    at org.eclipse.persistence.internal.sessions.MergeManager.mergeChangesOfWorkingCopyIntoOriginal(MergeManager.java:884)
    at org.eclipse.persistence.internal.sessions.MergeManager.mergeChangesOfWorkingCopyIntoOriginal(MergeManager.java:698)
    at org.eclipse.persistence.internal.sessions.MergeManager.mergeChanges(MergeManager.java:309)
    at org.eclipse.persistence.mappings.CollectionMapping.mergeIntoObject(CollectionMapping.java:1638)
    at org.eclipse.persistence.internal.descriptors.ObjectBuilder.mergeIntoObject(ObjectBuilder.java:4132)
    at org.eclipse.persistence.internal.descriptors.ObjectBuilder.mergeChangesIntoObject(ObjectBuilder.java:4065)
    at org.eclipse.persistence.internal.sessions.MergeManager.mergeChangesOfWorkingCopyIntoOriginal(MergeManager.java:839)
    at org.eclipse.persistence.internal.sessions.MergeManager.mergeChangesOfWorkingCopyIntoOriginal(MergeManager.java:698)
    at org.eclipse.persistence.internal.sessions.MergeManager.mergeChanges(MergeManager.java:309)
    at org.eclipse.persistence.internal.sessions.UnitOfWorkImpl.mergeChangesIntoParent(UnitOfWorkImpl.java:3280)
    at org.eclipse.persistence.internal.sessions.RepeatableWriteUnitOfWork.mergeChangesIntoParent(RepeatableWriteUnitOfWork.java:376)
    at org.eclipse.persistence.internal.sessions.RepeatableWriteUnitOfWork.commitRootUnitOfWork(RepeatableWriteUnitOfWork.java:290)
    at org.eclipse.persistence.internal.sessions.UnitOfWorkImpl.commitAndResume(UnitOfWorkImpl.java:1169)
    at org.eclipse.persistence.internal.jpa.transaction.EntityTransactionImpl.commit(EntityTransactionImpl.java:132)
    ... 3 more
Caused by: java.lang.IllegalArgumentException: Can not set java.lang.Double field ar.asimov.acumar.ema.model.DoubleListValue.doubleValue to ar.asimov.acumar.ema.model.ExtraHumidity
    at sun.reflect.UnsafeFieldAccessorImpl.throwSetIllegalArgumentException(UnsafeFieldAccessorImpl.java:167)
    at sun.reflect.UnsafeFieldAccessorImpl.throwSetIllegalArgumentException(UnsafeFieldAccessorImpl.java:171)
    at sun.reflect.UnsafeFieldAccessorImpl.ensureObj(UnsafeFieldAccessorImpl.java:58)
    at sun.reflect.UnsafeObjectFieldAccessorImpl.set(UnsafeObjectFieldAccessorImpl.java:75)
    at java.lang.reflect.Field.set(Field.java:764)
    at org.eclipse.persistence.internal.descriptors.InstanceVariableAttributeAccessor.setAttributeValueInObject(InstanceVariableAttributeAccessor.java:141)
    ... 21 more

I have the following classes in my model (i'm omitting the getters and setters
for simplicity)

@IdClass(ListParameterValue.PrimaryKey.class)
@Entity
@Inheritance(strategy=InheritanceType.SINGLE_TABLE)
@DiscriminatorColumn(discriminatorType=DiscriminatorType.STRING, name="parameter_type",length=20)
@Table(name="ta_ams_weather_list_parameters")
@Access(AccessType.FIELD)
public abstract class ListParameterValue implements Serializable {

    private static final long serialVersionUID = 1L;

    public static class PrimaryKey implements Serializable{...}

    @Id
    @ManyToOne
    @JoinColumn(name="station_id",referencedColumnName="station_id")
    protected Station station;
    @Id
    @Column(name="date")
    protected LocalDate date;
    @Id
    @Column(name="start_time")
    protected LocalTime startTime;
    @Id
    @Column(name="order_index")
    protected Integer order;
    @Id
    @Column(name="parameter_type")
    protected String type;

}

@MappedSuperclass
@Access(AccessType.FIELD)
public abstract class DoubleListValue extends ListParameterValue implements Serializable {

    private static final long serialVersionUID = 1L;

    @Column(name="double_value", nullable = true, columnDefinition="default null")
    protected Double doubleValue;

}

@MappedSuperclass
@Access(AccessType.FIELD)
public abstract class ShortListValue extends ListParameterValue implements Serializable {

    private static final long serialVersionUID = 1L;

    @Column(name="short_value")
    protected Short shortValue;

}

@Entity
@DiscriminatorValue("extra_humidity")
public class ExtraHumidity extends ShortListValue implements Serializable{

    /**
     *
     */
    private static final long serialVersionUID = 1L;

    public ExtraHumidity() {
     super();
    }

}

I would really appreciate the help.
Thanks in advance


问:
Unit testing of thread synchronization (lock)
I'm working on multithread app and there is part of code which sholud be run only by one thread same time. Nothing complicated. I use lock to synchronize it. It's working in life system but I would like to write unit test to check if only one thread is in the critical section. I wrote one, it was working but it stops :)
I can't figure out how to write a test it in proper way. I use NSubstitute to create mocks.

Class to test:

```<code>public interface IMultiThreadClass
{
    void Go();
}
public class Lock02 : IMultiThreadClass
{
    private readonly IProcessor _processor;
    private readonly string _threadName;

    private static readonly object Locker = new Object();

    public Lock02(IProcessor processor, string threadName)
    {
        _processor = processor;
        _threadName = threadName;
    }

    public void Go()
    {
        //critical section
        lock (Locker)
        {
            _processor.Process(_threadName);
        }
    }
}
</code>```

Test:

```<code>[TestMethod()]
public void Run_Test()
{
    //Only one thread should run Processor.Process, but we allow max 2 threads to catch locking erorrs
    SemaphoreSlim semaphore = new SemaphoreSlim(1, 2);

    //Semaphore to synchronize asserts
    SemaphoreSlim synchroSemaphore = new SemaphoreSlim(0, 1);

    IProcessor procesor = Substitute.For<IProcessor>();
    procesor.When(x => x.Process(Arg.Any<string>())).Do(y =>
    {
        //increment counter to check if method was called
        Interlocked.Increment(ref _counter);

        //release synchro semaphore
        synchroSemaphore.Release();

        //stop thread and wait for release
        semaphore.Wait();
    });

    Lock02 locker1 = new Lock02(procesor, "1");
    Lock02 locker2 = new Lock02(procesor, "2");
    Lock02 locker3 = new Lock02(procesor, "3");

    Task.Run(() => locker1.Go());
    Task.Run(() => locker2.Go());
    Task.Run(() => locker3.Go());

    //ASSERT
    //Thread.Sleep(1000);
    synchroSemaphore.Wait();
    Assert.AreEqual(1, _counter);

    semaphore.Release(1);
    synchroSemaphore.Wait();
    Assert.AreEqual(2, _counter);

    semaphore.Release(1);
    synchroSemaphore.Wait();
    Assert.AreEqual(3, _counter);

    semaphore.Release(1);
}
</code>```

答:
A possible (simple but not bulletproof) way is to spawn some threads/tasks in the unit test, each fetching and temporarily storing an int variable (possibly static), waiting for a bit (delay), incrementing the value and writing it back to the variable. Without thread synchronization (lock), many if not all threads will grab the same number and it will not be equal (as it should) to the number of threads/tasks.

This is not bulletproof since there is still a race condition making it not reproducible (the smelly code is the 50 ms delay), although it seems (to me) very unlikely for all treads to wait for each other in the perfect way and produce the right result.

I consider this being a smelly workaround, but it is simple and works.

```<code>    [TestMethod]
    public async Task APossibleTest()
    {
        int importantNumber = 0;

        var proc = Substitute.For<IProcessor>();
        proc.WhenForAnyArgs(processor => processor.Process(Arg.Any<string>()))
            .Do(callInfo =>
            {
                int cached = importantNumber;
                // Wait for other threads to fetch the number too (if they were not synchronized).
                Thread.Sleep(TimeSpan.FromMilliseconds(50));
                // This kind of incrementation will check the thread synchronization.
                // Using a thread-safe Interlocked or other here does not make sense.
                importantNumber = cached + 1;
            });

        var locker = new Locker(proc, "da horror");

        // Create 10 tasks all attempting to increment the important number.
        Task[] tasks =
            Enumerable
                .Range(0, 10)
                // You could create multiple lockers here (with their own processors).
                .Select(i => Task.Run(() => locker.Go()))
                .ToArray();
        await Task.WhenAll(tasks);

        Assert.AreEqual(10, importantNumber, "Exactly 10 increments were expected since we have 10 tasks.");
    }
</code>```

Body:
I'm working on multithread app and there is part of code which sholud be run only by one thread same time. Nothing complicated. I use lock to synchronize it. It's working in life system but I would like to write unit test to check if only one thread is in the critical section. I wrote one, it was working but it stops :)
I can't figure out how to write a test it in proper way. I use NSubstitute to create mocks.

Class to test:

public interface IMultiThreadClass
{
    void Go();
}
public class Lock02 : IMultiThreadClass
{
    private readonly IProcessor _processor;
    private readonly string _threadName;

    private static readonly object Locker = new Object();

    public Lock02(IProcessor processor, string threadName)
    {
        _processor = processor;
        _threadName = threadName;
    }

    public void Go()
    {
        //critical section
        lock (Locker)
        {
            _processor.Process(_threadName);
        }
    }
}

Test:

[TestMethod()]
public void Run_Test()
{
    //Only one thread should run Processor.Process, but we allow max 2 threads to catch locking erorrs
    SemaphoreSlim semaphore = new SemaphoreSlim(1, 2);

    //Semaphore to synchronize asserts
    SemaphoreSlim synchroSemaphore = new SemaphoreSlim(0, 1);

    IProcessor procesor = Substitute.For<IProcessor>();
    procesor.When(x => x.Process(Arg.Any<string>())).Do(y =>
    {
        //increment counter to check if method was called
        Interlocked.Increment(ref _counter);

        //release synchro semaphore
        synchroSemaphore.Release();

        //stop thread and wait for release
        semaphore.Wait();
    });

    Lock02 locker1 = new Lock02(procesor, "1");
    Lock02 locker2 = new Lock02(procesor, "2");
    Lock02 locker3 = new Lock02(procesor, "3");

    Task.Run(() => locker1.Go());
    Task.Run(() => locker2.Go());
    Task.Run(() => locker3.Go());

    //ASSERT
    //Thread.Sleep(1000);
    synchroSemaphore.Wait();
    Assert.AreEqual(1, _counter);

    semaphore.Release(1);
    synchroSemaphore.Wait();
    Assert.AreEqual(2, _counter);

    semaphore.Release(1);
    synchroSemaphore.Wait();
    Assert.AreEqual(3, _counter);

    semaphore.Release(1);
}

Body:
A possible (simple but not bulletproof) way is to spawn some threads/tasks in the unit test, each fetching and temporarily storing an int variable (possibly static), waiting for a bit (delay), incrementing the value and writing it back to the variable. Without thread synchronization (lock), many if not all threads will grab the same number and it will not be equal (as it should) to the number of threads/tasks.

This is not bulletproof since there is still a race condition making it not reproducible (the smelly code is the 50 ms delay), although it seems (to me) very unlikely for all treads to wait for each other in the perfect way and produce the right result.

I consider this being a smelly workaround, but it is simple and works.

    [TestMethod]
    public async Task APossibleTest()
    {
        int importantNumber = 0;

        var proc = Substitute.For<IProcessor>();
        proc.WhenForAnyArgs(processor => processor.Process(Arg.Any<string>()))
            .Do(callInfo =>
            {
                int cached = importantNumber;
                // Wait for other threads to fetch the number too (if they were not synchronized).
                Thread.Sleep(TimeSpan.FromMilliseconds(50));
                // This kind of incrementation will check the thread synchronization.
                // Using a thread-safe Interlocked or other here does not make sense.
                importantNumber = cached + 1;
            });

        var locker = new Locker(proc, "da horror");

        // Create 10 tasks all attempting to increment the important number.
        Task[] tasks =
            Enumerable
                .Range(0, 10)
                // You could create multiple lockers here (with their own processors).
                .Select(i => Task.Run(() => locker.Go()))
                .ToArray();
        await Task.WhenAll(tasks);

        Assert.AreEqual(10, importantNumber, "Exactly 10 increments were expected since we have 10 tasks.");
    }


问:
Sitecore cannot save in Experience Editor special characters
The website is component bases website. In a component I have rich-text and inside of that I have something like 70%. After I add the component to the page the save on the page does not work anymore.

Does someone had an issue like this before?

答:
This post fixed for me. Note I'm using Sitecore 8.2 Update 2

My error:

After parsing a value an unexpected character was encountered: {. Path 'scLayout', line 1, position 2246.

http://jockstothecore.com/experience-editor-error/

```<code>postServerRequest: function (requestType, commandContext, handler, async) {

    function normalizeDeviceProp(d) {
        if (typeof(d) !== "object")
            throw new Error("Unexpected presentation details XML: cannot find device property");

        if (d instanceof Array)
            return d;

        var normalized = [];
        normalized.push(d);
        return normalized;
    }

    var token = $('input[name="__RequestVerificationToken"]').val();

    // Custom Brainjocks code to fix Experience Editor error.
    var ajaxData = unescape(JSON.stringify(commandContext));
    if (commandContext && commandContext.scLayout) {
        var obj = JSON.parse(commandContext.scLayout);
      if (obj && obj.r) {
          normalizeDeviceProp(obj.r.d).forEach(function (d) {
              if (d.r instanceof Array) {
                  d.r.forEach(function (r) {
                      var val = r["@par"];
                        if (val && val.length > 0) {
                            ajaxData = ajaxData.replace(unescape(val), val);
                        }
                  });
              }

            });
        }
    }

    jQuery.ajax({
        url: "/-/speak/request/v1/expeditor/" + requestType,
        data: {
            __RequestVerificationToken: token,
            data: ajaxData
        },
        success: handler,
        type: "POST",
        async: async != undefined ? async : false
    });
}
</code>```

Body:
This post fixed for me. Note I'm using Sitecore 8.2 Update 2

My error:

After parsing a value an unexpected character was encountered: {. Path 'scLayout', line 1, position 2246.

http://jockstothecore.com/experience-editor-error/

postServerRequest: function (requestType, commandContext, handler, async) {

    function normalizeDeviceProp(d) {
        if (typeof(d) !== "object")
            throw new Error("Unexpected presentation details XML: cannot find device property");

        if (d instanceof Array)
            return d;

        var normalized = [];
        normalized.push(d);
        return normalized;
    }

    var token = $('input[name="__RequestVerificationToken"]').val();

    // Custom Brainjocks code to fix Experience Editor error.
    var ajaxData = unescape(JSON.stringify(commandContext));
    if (commandContext && commandContext.scLayout) {
        var obj = JSON.parse(commandContext.scLayout);
      if (obj && obj.r) {
          normalizeDeviceProp(obj.r.d).forEach(function (d) {
              if (d.r instanceof Array) {
                  d.r.forEach(function (r) {
                      var val = r["@par"];
                        if (val && val.length > 0) {
                            ajaxData = ajaxData.replace(unescape(val), val);
                        }
                  });
              }

            });
        }
    }

    jQuery.ajax({
        url: "/-/speak/request/v1/expeditor/" + requestType,
        data: {
            __RequestVerificationToken: token,
            data: ajaxData
        },
        success: handler,
        type: "POST",
        async: async != undefined ? async : false
    });
}