问:
Centralizing RecyclerView with LinearLayoutManager
I am trying to centralize a RecyclerView list in the screen. Its going to be a single list, so I will use the LinearLayoutManager (LLM).
However using the LLM its not centralizing the items, and it looks like this on the landscape mode:

The XML code looks like this:

```<code><FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:orientation="vertical" android:layout_width="match_parent"

    android:layout_height="match_parent">

    <android.support.v7.widget.CardView
        android:id="@+id/recipe_card"
        android:layout_gravity="center"
        android:layout_width="400dp"
        android:layout_height="186dp"
        style="@style/CardViewStyle">

        <android.support.constraint.ConstraintLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent">

            <ImageView
                android:id="@+id/recipe_image"
                android:layout_width="120dp"
                android:layout_height="163dp"
                app:srcCompat="@mipmap/ic_pan"
                app:layout_constraintTop_toTopOf="parent"
                android:layout_marginTop="8dp"
                app:layout_constraintBottom_toBottomOf="parent"
                android:layout_marginBottom="8dp"
                android:layout_marginLeft="8dp"
                app:layout_constraintLeft_toLeftOf="parent"
                tools:layout_editor_absoluteY="3dp" />

            <TextView
                android:id="@+id/recipe_name"
                android:layout_width="250dp"
                android:layout_height="119dp"
                android:text="TextView"
                app:layout_constraintLeft_toRightOf="@+id/recipe_image"
                android:layout_marginLeft="8dp"
                app:layout_constraintTop_toTopOf="parent"
                android:layout_marginTop="16dp" />

            <TextView
                android:id="@+id/recipe_servings"
                android:layout_width="164dp"
                android:layout_height="32dp"
                android:text="TextView"
                android:layout_marginTop="8dp"
                app:layout_constraintTop_toBottomOf="@+id/recipe_name"
                app:layout_constraintBottom_toBottomOf="parent"
                android:layout_marginBottom="8dp"
                app:layout_constraintLeft_toRightOf="@+id/recipe_image"
                android:layout_marginLeft="94dp"
                app:layout_constraintVertical_bias="0.0" />
        </android.support.constraint.ConstraintLayout>

    </android.support.v7.widget.CardView>

</FrameLayout>
</code>```

On the Android Studio's Preview, it looks fine, but on the app, it does not.
I manage to fix it by changing the LLM for a GridLayoutManager with only one column. But it looks ugly.

Does anyone knows what is going on?
Thanks.

答:
write this code in your FrameLayout</p>

```<code>    android:layout_gravity="center"
</code>```

Body:
I am trying to centralize a RecyclerView list in the screen. Its going to be a single list, so I will use the LinearLayoutManager (LLM).
However using the LLM its not centralizing the items, and it looks like this on the landscape mode:

The XML code looks like this:

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:orientation="vertical" android:layout_width="match_parent"

    android:layout_height="match_parent">

    <android.support.v7.widget.CardView
        android:id="@+id/recipe_card"
        android:layout_gravity="center"
        android:layout_width="400dp"
        android:layout_height="186dp"
        style="@style/CardViewStyle">

        <android.support.constraint.ConstraintLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent">

            <ImageView
                android:id="@+id/recipe_image"
                android:layout_width="120dp"
                android:layout_height="163dp"
                app:srcCompat="@mipmap/ic_pan"
                app:layout_constraintTop_toTopOf="parent"
                android:layout_marginTop="8dp"
                app:layout_constraintBottom_toBottomOf="parent"
                android:layout_marginBottom="8dp"
                android:layout_marginLeft="8dp"
                app:layout_constraintLeft_toLeftOf="parent"
                tools:layout_editor_absoluteY="3dp" />

            <TextView
                android:id="@+id/recipe_name"
                android:layout_width="250dp"
                android:layout_height="119dp"
                android:text="TextView"
                app:layout_constraintLeft_toRightOf="@+id/recipe_image"
                android:layout_marginLeft="8dp"
                app:layout_constraintTop_toTopOf="parent"
                android:layout_marginTop="16dp" />

            <TextView
                android:id="@+id/recipe_servings"
                android:layout_width="164dp"
                android:layout_height="32dp"
                android:text="TextView"
                android:layout_marginTop="8dp"
                app:layout_constraintTop_toBottomOf="@+id/recipe_name"
                app:layout_constraintBottom_toBottomOf="parent"
                android:layout_marginBottom="8dp"
                app:layout_constraintLeft_toRightOf="@+id/recipe_image"
                android:layout_marginLeft="94dp"
                app:layout_constraintVertical_bias="0.0" />
        </android.support.constraint.ConstraintLayout>

    </android.support.v7.widget.CardView>

</FrameLayout>

On the Android Studio's Preview, it looks fine, but on the app, it does not.
I manage to fix it by changing the LLM for a GridLayoutManager with only one column. But it looks ugly.

Does anyone knows what is going on?
Thanks.

Body:
write this code in your FrameLayout

    android:layout_gravity="center"


来源: stackexchange

问:
Elegant way to validate scala map
My program receives a scala map, the requirements is to validate this map (key-value pairs). Ex: validate a key value, change its value to an acceptable format etc. In a rare case, we update the key as well before passing the map to the down layer. Its not always required to update this map , but only when we detect that there are any unsupported keys or values. However, we have to check all key/value pairs. I'm doing some thing like this:

```<code>private def updateMap ( parameters: Map[String, String]): Map[String, String] = {

parameters.map{

  case(k,v) => k match { case "checkPool" =>

    (k, (if (k.contains("checkPool"))
      v match {
        case "1" => "true"
        case _ => "false"
      }
    else v))

  case "Newheader" => (k.replace("Newheader","header"),v)
  case _ =>(k,v)
  }

  case _ => ("","")
}

}
</code>```

Like this the code increases for doing the validation and converting the keys/values to supported ones. Is there a cleaner way of doing this validation in Scala for a map?

Thanks

答:
simple if else condition matching seems to be the best choice.

```<code>def updateMap(parameters: Map[String, String]): Map[String, String] = {
  parameters.map(kv => {
    var key = kv._1
    var value = kv._2
    if(key.contains("checkPool")){
      value = if(value.equals("1")) "true" else "false"
    }
    else if(key.contains("Newheader")){
      key = key.replace("Newheader", "header")
    }
    (key, value)
  })
}
</code>```

You can add more else if conditions

ContentLicense: CC BY-SA 3.0

Title: Elegant way to validate scala map

Body:
My program receives a scala map, the requirements is to validate this map (key-value pairs). Ex: validate a key value, change its value to an acceptable format etc. In a rare case, we update the key as well before passing the map to the down layer. Its not always required to update this map , but only when we detect that there are any unsupported keys or values. However, we have to check all key/value pairs. I'm doing some thing like this:

private def updateMap ( parameters: Map[String, String]): Map[String, String] = {

parameters.map{

  case(k,v) => k match { case "checkPool" =>

    (k, (if (k.contains("checkPool"))
      v match {
        case "1" => "true"
        case _ => "false"
      }
    else v))

  case "Newheader" => (k.replace("Newheader","header"),v)
  case _ =>(k,v)
  }

  case _ => ("","")
}

}

Like this the code increases for doing the validation and converting the keys/values to supported ones. Is there a cleaner way of doing this validation in Scala for a map?

Thanks

Body:
simple if else condition matching seems to be the best choice.

def updateMap(parameters: Map[String, String]): Map[String, String] = {
  parameters.map(kv => {
    var key = kv._1
    var value = kv._2
    if(key.contains("checkPool")){
      value = if(value.equals("1")) "true" else "false"
    }
    else if(key.contains("Newheader")){
      key = key.replace("Newheader", "header")
    }
    (key, value)
  })
}

You can add more else if conditions


问:
What is a clabject?
I am trying to find a clear definition of clabject.

Has anyone a good one ?

答:
Paper on The Rationale of Powertype-based Metamodelling to Underpin Software Development Methodologies gives a definition of clabjets, two faceted constructs that have properties of classes and objects:

This idea of a two-faceted construct
  or clabject is perfect for our needs,
  since it nicely models a single
  concept being modelled simultaneously
  as a class and as an object. Rather
  than seeing the WriteMethodCode class
  and the “WriteMethodCode” object as
  separate entities in the method layer,
  we can look at them as a single
  entity, a clabject, named
  #WriteMethodCode. As such, #WriteMethodCode will exhibit a class facet (with a name and possibly some
  attributes and relationships) plus an
  object facet (with values and links).
  The class facet of a method-level
  clabject, as we have explained before,
  is a subtype of a metamodel class
  (Task in our example), while the
  object facet in the same clabject is
  an instance of a different metamodel
  class.

Title: What is a clabject?

ContentLicense: CC BY-SA 2.5


问:
How to get value from JSON php
This is my JSON.

```<code>{
  "OUT_STAT": "200",
  "OUT_MESS": "SUKSES",
  "OUT_DATA": [{
      "id_doc_proj": "4"
    }]
}
</code>```

My Questions are:

1. How to get OUT_STAT value?

2. How to get id_doc_proj value?

I am sorry if my questions are silly because i am new at get value from JSON.

Thanks in advance.

UPDATE

I am sorry if you are saying i duplicated Parsing JSON file with PHP. I have tried code from there but i don't get any JSON from my response. I don't know where is the mistake. If you want to help, this is my php script.

```<code><?php
    $file_path = "";
    $id_project = "16";
    $p_id_doc_proj = "50";
    $id_doc_type = "1";
    $id_user = "4";

    $url = $file_path.basename($_FILES['uploaded_file']['name']);

    if(move_uploaded_file($_FILES['uploaded_file']['tmp_name'], $url)){
        $ws = "http://172.xx.x.xx:xxxx/rest/com/acc/uw/in/httprest/apponline/uploadtrough/UploadImage/$id_project/$p_id_doc_proj/$id_doc_type/$id_user/$url";

        $opts = array('http'=>array('header'=>'Content-type: application/x-www-form-urlencoded'));

        $context = stream_context_create($opts);

        $arrayLog=array();
        $data1 = file_get_contents($ws, false, $context);
        $result = json_decode($data1, true);;

        //$result = array("result" => "success");
    }else{
        $result = array("result" => "error");
    }

    echo json_encode($result);
?>
</code>```

The result should show my JSON above but it was null. Any answers will help me. Thanks in advance.

答:
you can use json_decode to convert json to array or object:

```<code>$json = '{
  "OUT_STAT": "200",
  "OUT_MESS": "SUKSES",
  "OUT_DATA": [{
      "id_doc_proj": "4"
    }]
}';

$object = json_decode($json);
$out_stat = $object->OUT_STAT;
$id_doc_proj = $object->OUT_DATA[0]->id_doc_proj;
</code>```

Title: How to get value from JSON php

Body:
This is my JSON.

{
  "OUT_STAT": "200",
  "OUT_MESS": "SUKSES",
  "OUT_DATA": [{
      "id_doc_proj": "4"
    }]
}

My Questions are:

1. How to get OUT_STAT value?

2. How to get id_doc_proj value?

I am sorry if my questions are silly because i am new at get value from JSON.

Thanks in advance.

UPDATE

I am sorry if you are saying i duplicated Parsing JSON file with PHP. I have tried code from there but i don't get any JSON from my response. I don't know where is the mistake. If you want to help, this is my php script.

<?php
    $file_path = "";
    $id_project = "16";
    $p_id_doc_proj = "50";
    $id_doc_type = "1";
    $id_user = "4";

    $url = $file_path.basename($_FILES['uploaded_file']['name']);

    if(move_uploaded_file($_FILES['uploaded_file']['tmp_name'], $url)){
        $ws = "http://172.xx.x.xx:xxxx/rest/com/acc/uw/in/httprest/apponline/uploadtrough/UploadImage/$id_project/$p_id_doc_proj/$id_doc_type/$id_user/$url";

        $opts = array('http'=>array('header'=>'Content-type: application/x-www-form-urlencoded'));

        $context = stream_context_create($opts);

        $arrayLog=array();
        $data1 = file_get_contents($ws, false, $context);
        $result = json_decode($data1, true);;

        //$result = array("result" => "success");
    }else{
        $result = array("result" => "error");
    }

    echo json_encode($result);
?>

The result should show my JSON above but it was null. Any answers will help me. Thanks in advance.

Body:
you can use json_decode to convert json to array or object:

$json = '{
  "OUT_STAT": "200",
  "OUT_MESS": "SUKSES",
  "OUT_DATA": [{
      "id_doc_proj": "4"
    }]
}';

$object = json_decode($json);
$out_stat = $object->OUT_STAT;
$id_doc_proj = $object->OUT_DATA[0]->id_doc_proj;


问:
Fetch into Map for a one to many relationship in JOOQ
We have a Feature table and a Tier table, 1 tier can have multiple features. So wanted to query and get output as

```<code>Map<Byte,List<String>>
</code>```

byte corresponds to a tierID and list of feature names

Managed to get an answer from an older post here
Question

Further we wanted to get a map of

```<code>Map<id, List<List<FeaturePojo>>
</code>```

答:
got it working, using the following </p>

```<code>.intoGroups(FreemiumFeature.FREEMIUM_FEATURE.ID,
            c->c.into(FreemiumTierFeature.FREEMIUM_TIER_FEATURE)
           .into(FeaturePojo.class));
</code>```

Body:
We have a Feature table and a Tier table, 1 tier can have multiple features. So wanted to query and get output as

Map<Byte,List<String>>

byte corresponds to a tierID and list of feature names

Managed to get an answer from an older post here
Question

Further we wanted to get a map of

Map<id, List<List<FeaturePojo>>

Body:
got it working, using the following

.intoGroups(FreemiumFeature.FREEMIUM_FEATURE.ID,
            c->c.into(FreemiumTierFeature.FREEMIUM_TIER_FEATURE)
           .into(FeaturePojo.class));


问:
i need to allow the data which is in between the start and end date
Here i given my database table. i need to create a code to allow the data to show after the start date and remove the data after the end date:

答:
here i found a technique to solve the deletion process but i need to hide the data which is not satisfied the condition .... plese go through this link to see the code which i was used.

Screenshot:

ContentLicense: CC BY-SA 4.0


问:
Netezza stored procedure error
I am my trying to convert an oracle procedure of something like below to Netezza and facing some issues when executed, no compilation errors. The procedure was executed successfully in Oracle. About the task, it is batch process without expecting to return or take input parameters and loop through the a table to prepare an SQL statement dynamically. Logic is built well as there is no issue in Oracle.

```<code>CREATE OR REPLACE PROCEDURE proc1 ()
   RETURNS CHARACTER VARYING (ANY) EXECUTE AS OWNER  LANGUAGE NZPLSQL AS
BEGIN_PROC

DECLARE

lv_sql varchar(4000);
lv1 varchar(4000);
lv2 varchar(4000);
lv3 varchar(4000);
lv4 varchar(4000);
lv5 varchar(4000);
lv_value varchar(1000);
lv_str_cnt integer;
lv_ret_string VARCHAR(1000);

BEGIN
    FOR c1 IN (SELECT * from test)
    LOOP
            IF lv_str_cnt = 0 THEN
              lv_ret_string := '''' || c1.col1 || '''';
            ELSE IF  lv_str_cnt IS NULL THEN
              lv_ret_string := NULL;
            ELSE
                lv_ret_string := '''' || c1.col2 || '''';
            END IF;
            .............
            .............

        lv_sql := lv_sql || lv1 || lv2 || lv3 || lv4;

        EXECUTE IMMEDIATE lv_sql;

     END LOOP;

END;
END_PROC;
</code>```

I get the following error when the procedure is executed
"Syntax error, unexpected WORD at or near Varchar2"

Varchar2 is an Oracle datatype and I can confirm it is modified to Varchar of Netezza in my procedure in all the places. I searched on google to find good examples of creating a procedure but unfortunately I could not get desired help.

Also there is particular block code which I want to create as function and re-use it. Unfortunately stuck up with function syntax too.

Appreciate your help

答:
You are on the right track, but I can see at least one mentioning of varchar2(): the last one of your declarations:</p>

```<code>lv_ret_string VARCHAR2(1000);
</code>```

Title: Netezza stored procedure error

Body:
I am my trying to convert an oracle procedure of something like below to Netezza and facing some issues when executed, no compilation errors. The procedure was executed successfully in Oracle. About the task, it is batch process without expecting to return or take input parameters and loop through the a table to prepare an SQL statement dynamically. Logic is built well as there is no issue in Oracle.

CREATE OR REPLACE PROCEDURE proc1 ()
   RETURNS CHARACTER VARYING (ANY) EXECUTE AS OWNER  LANGUAGE NZPLSQL AS
BEGIN_PROC

DECLARE

lv_sql varchar(4000);
lv1 varchar(4000);
lv2 varchar(4000);
lv3 varchar(4000);
lv4 varchar(4000);
lv5 varchar(4000);
lv_value varchar(1000);
lv_str_cnt integer;
lv_ret_string VARCHAR(1000);

BEGIN
    FOR c1 IN (SELECT * from test)
    LOOP
            IF lv_str_cnt = 0 THEN
              lv_ret_string := '''' || c1.col1 || '''';
            ELSE IF  lv_str_cnt IS NULL THEN
              lv_ret_string := NULL;
            ELSE
                lv_ret_string := '''' || c1.col2 || '''';
            END IF;
            .............
            .............

        lv_sql := lv_sql || lv1 || lv2 || lv3 || lv4;

        EXECUTE IMMEDIATE lv_sql;

     END LOOP;

END;
END_PROC;

I get the following error when the procedure is executed
"Syntax error, unexpected WORD at or near Varchar2"

Varchar2 is an Oracle datatype and I can confirm it is modified to Varchar of Netezza in my procedure in all the places. I searched on google to find good examples of creating a procedure but unfortunately I could not get desired help.

Also there is particular block code which I want to create as function and re-use it. Unfortunately stuck up with function syntax too.

Appreciate your help

Body:
You are on the right track, but I can see at least one mentioning of varchar2(): the last one of your declarations:

lv_ret_string VARCHAR2(1000);


问:
SQL Query to Sum Values on One Table and Select Names from Another table
Apologies for the poorly written title.

I have two tables. Table a with Student ID and Names and table b with Student ID, course and course cost

I want to be able to query the database so I can show the student name and total dollars spent on courses

So far I have this:

```<code>SELECT Student.fname, Student.lname, SUM(m.CourseCost) FROM
  (SELECT DISTINCT StuID, CourseCost FROM Courses) AS m
     INNER JOIN Student ON m.StuID = Student.ID;
</code>```

Visual Studio throws an error when I try to run the query. I am using MS Access as the database. I think there is something wrong with my inner

答:
Try this query</p>

```<code> SELECT fname+' '+lname Name,courseName , SUM(CourseCost) CourseCost
    FROM Student
    INNER JOIN Courses ON Courses.StuID = Student.ID
    GROUP BY fname, lname ,courseName ;
</code>```

Body:
Apologies for the poorly written title.

I have two tables. Table a with Student ID and Names and table b with Student ID, course and course cost

I want to be able to query the database so I can show the student name and total dollars spent on courses

So far I have this:

SELECT Student.fname, Student.lname, SUM(m.CourseCost) FROM
  (SELECT DISTINCT StuID, CourseCost FROM Courses) AS m
     INNER JOIN Student ON m.StuID = Student.ID;

Visual Studio throws an error when I try to run the query. I am using MS Access as the database. I think there is something wrong with my inner

Body:
Try this query

 SELECT fname+' '+lname Name,courseName , SUM(CourseCost) CourseCost
    FROM Student
    INNER JOIN Courses ON Courses.StuID = Student.ID
    GROUP BY fname, lname ,courseName ;


问:
Azure Virtual Network / VM's Setup to Share One Public IP
I've recently setup a point to site VPN on Azure. In doing so I have created:

Azure Virtual Network

Azure Virtual Network Gateway

Azure Virtual Network Gateway IP (static)

Azure VM

I was under the impression that any VM set to use the above said Virtual Network would all share the same public IP? However it appears that the Azure VM i setup is instead using its own dynamic public IP.

Is there a way to route any VM on the Custom Virtual Network I created through one public IP? IF so - how can I do this?

According to your description, you have create a point-to-side VPN. in this scenario, we can remove the public IP addresses from VMs, then you can access your VMs with private IP addresses via VPN.

You are correct - I have the VPN working correctly. My only concern is this, it'd be great that if any of those VM's in that private network shared the same static IP - that way I could grant access to that IP in my firewall to other systems i have in other hosting platforms (as they are all typically locked down by ip).

It sounds like your reference to availablity sets may be the phrase i was looking for to further google.. i will check it out and let me know

please let me know if anything I added above changes your answer/recommendations :)

答:
I was under the impression that any VM set to use the above said
  Virtual Network would all share the same public IP?

You are talking about Azure ASM module (classic). In ASM module, VMs can use the same public IP address(NAT).

However it appears that the Azure VM i setup is instead using its own
  dynamic public IP.

In Azure resource module, we can create Azure VMs with different Public IP addresses.

Is there a way to route any VM on the Custom Virtual Network I created
  through one public IP?

According to your description, you have create a point-to-side VPN. in this scenario, we can remove the public IP addresses from VMs, then you can access your VMs with private IP addresses via VPN.

If you want to access those VMs from Internet and use one public IP address, we can create VMs in the same availability set, and deploy a Internet facing load balancer, then add NAT rules to them, in this way, we can access those VMs use the same public IP address and different ports.


问:
The name does not exist in the current context c# for the below code
I am getting 5 errors as mentioned below:

Error 1 The name 'txtTo' does not exist in the current context

Error 2 The name 'txtMessage' does not exist in the current context

Error 3 The type or namespace name 'WhatsApp' could not be found (are you missing a using directive or an assembly reference?)

Error 4 The type or namespace name 'WhatsApp' could not be found (are you missing a using directive or an assembly reference?)

Error 5 The name 'data' does not exist in the current context

Could someone please help me with the above errors?

Here is the code that i am using:

```<code>using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace WindowsFormsApplication2
{
 public partial class Form1 : Form
 {
     public Form1()
     {
         InitializeComponent();
     }

     private void btnSend_Click(object sender, EventArgs e)
     {
         //Send ( button_click )
         string from = " ";
         string to = txtTo.Text;
         string msg = txtMessage.Text;

         WhatsApp wa = new WhatsApp(from, "S2pRzjF5WnVcHCwGFkjJuFI2oCM=", "Shri", false, false);

         wa.OnConnectSuccess += () =>
         {
             MessageBox.Show("Connected to whatsapp...");

             wa.OnLoginSuccess += (phoneNumber, data) =>
             {
                 wa.sendmessage(to, msg);
             };

             wa.OnLoginFailed += (DataBindings) =>
             {
                 MessageBox.Show("Login Failed : {0}", data);
             };

             wa.Login();
         };

         wa.OnConnectFailed += (ex) =>
         {
             MessageBox.Show("Connection Failed...");
         };

         wa.Connect();

     }
 }
}
</code>```

答:
Please check below code :

First you need to Register your No on WART check below link :

http://www.c-sharpcorner.com/uploadfile/ansh06031982/send-message-on-whatsapp-number-using-web-service/

And your Method should be :

private void btnSend_Click(object sender, EventArgs e)
{
     //Send To details
     string Phnumber = textBox1.Text;
     string message = textBox2.Text;

     //send From details

     string FromNumber = "9177677377";
     string password = "bbRvfrEbePyI/uGOqyyw9yeHlys=";
     string nickName = "Laxman";

     WhatsApp wap = new WhatsApp(FromNumber, password, nickName, false, false);
     wap.OnConnectSuccess += () =>
         {
             MessageBox.Show("Connected to whatsapp SuccessFully...");

             wap.OnLoginSuccess += (PhoneNumber, data) =>
             {
                 MessageBox.Show("Enterned");
                 wap.SendMessage(Phnumber, message);
                 MessageBox.Show("Message Sent Successfully...");
             };

             wap.OnLoginFailed += (data) =>
             {
                 MessageBox.Show(data);
                 MessageBox.Show("Yes Failed login : {0}", data);
             };

             wap.Login();
         };

     wap.OnConnectFailed += (ex) =>
         {
             MessageBox.Show("Conncetion Failure");
         };

     wap.Connect();
 }
```

Cheers !!

Body:
I am getting 5 errors as mentioned below:

Error 1 The name 'txtTo' does not exist in the current context

Error 2 The name 'txtMessage' does not exist in the current context

Error 3 The type or namespace name 'WhatsApp' could not be found (are you missing a using directive or an assembly reference?)

Error 4 The type or namespace name 'WhatsApp' could not be found (are you missing a using directive or an assembly reference?)

Error 5 The name 'data' does not exist in the current context

Could someone please help me with the above errors?

Here is the code that i am using:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace WindowsFormsApplication2
{
 public partial class Form1 : Form
 {
     public Form1()
     {
         InitializeComponent();
     }

     private void btnSend_Click(object sender, EventArgs e)
     {
         //Send ( button_click )
         string from = " ";
         string to = txtTo.Text;
         string msg = txtMessage.Text;

         WhatsApp wa = new WhatsApp(from, "S2pRzjF5WnVcHCwGFkjJuFI2oCM=", "Shri", false, false);

         wa.OnConnectSuccess += () =>
         {
             MessageBox.Show("Connected to whatsapp...");

             wa.OnLoginSuccess += (phoneNumber, data) =>
             {
                 wa.sendmessage(to, msg);
             };

             wa.OnLoginFailed += (DataBindings) =>
             {
                 MessageBox.Show("Login Failed : {0}", data);
             };

             wa.Login();
         };

         wa.OnConnectFailed += (ex) =>
         {
             MessageBox.Show("Connection Failed...");
         };

         wa.Connect();

     }
 }
}

Body:
Please check below code :

First you need to Register your No on WART check below link :

http://www.c-sharpcorner.com/uploadfile/ansh06031982/send-message-on-whatsapp-number-using-web-service/

And your Method should be :

private void btnSend_Click(object sender, EventArgs e)
{
     //Send To details
     string Phnumber = textBox1.Text;
     string message = textBox2.Text;

     //send From details

     string FromNumber = "9177677377";
     string password = "bbRvfrEbePyI/uGOqyyw9yeHlys=";
     string nickName = "Laxman";

     WhatsApp wap = new WhatsApp(FromNumber, password, nickName, false, false);
     wap.OnConnectSuccess += () =>
         {
             MessageBox.Show("Connected to whatsapp SuccessFully...");

             wap.OnLoginSuccess += (PhoneNumber, data) =>
             {
                 MessageBox.Show("Enterned");
                 wap.SendMessage(Phnumber, message);
                 MessageBox.Show("Message Sent Successfully...");
             };

             wap.OnLoginFailed += (data) =>
             {
                 MessageBox.Show(data);
                 MessageBox.Show("Yes Failed login : {0}", data);
             };

             wap.Login();
         };

     wap.OnConnectFailed += (ex) =>
         {
             MessageBox.Show("Conncetion Failure");
         };

     wap.Connect();
 }

Cheers !!


问:
How to set a Date Format on iPhone
I have implemented a calendar application for iPhone.

I am getting the current date using [NSDate date].

Now I want to display only "Tuesday". So how can I get this output. I don't know which format I have to use.

Thanks.

答:
You need NSDateFormatter.

```<code>NSDateFormatter *dayFormat = [[NSDateFormatter alloc] init];
[dayFormat setDateFormat:@"EEEE"];
NSDate *now = [[NSDate alloc] init];
NSString *formattedDay = [dayFormat stringFromDate:now];
</code>```

See the Unicode reference for all of the format options you can use.

Title: How to set a Date Format on iPhone

Body:
You need NSDateFormatter.

NSDateFormatter *dayFormat = [[NSDateFormatter alloc] init];
[dayFormat setDateFormat:@"EEEE"];
NSDate *now = [[NSDate alloc] init];
NSString *formattedDay = [dayFormat stringFromDate:now];

See the Unicode reference for all of the format options you can use.


问:
foreign key in my database migration
I am developing a program in laravel, I am always creating database while I'm writing my code. And now, I want to test my program, so I reset all my database, and try to migrate, suddenly this error appear, anyone know why ?

SQLSTATE[42S01]: Base table or view already exists: 1050 Table 'paket' already exists (SQL: create table `paket` (`id` int unsigned not null aut o_increment primary key, `produk_id` int unsigned not null, `nama` varchar(191) not null, `jumlah_user` int not null, `created_at` timestamp null, `updated_at` timestamp null) default character set utf8mb4 collate utf8mb4_unicode_ci)

And this is my database migration :

User :

public function up()
{
    Schema::create('users', function (Blueprint $table) {
        $table->increments('id');
        $table->string('name');
        $table->string('username')->unique();
        $table->string('email')->unique();
        $table->string('level');
        $table->string('password');
        $table->rememberToken();
        $table->timestamps();
    });
}

a table named paket:

```<code>```public function up()
{
    Schema::create('paket',function(Blueprint $table){
      $table->increments('id');
      $table->integer('produk_id')->unsigned();
      $table->foreign('produk_id')->references('id')->on('produk');
      $table->string('nama');
      $table->integer('jumlah_user');
      // $table->date('tanggal_mulai');
      // $table->date('tanggal_terakhir');
      $table->timestamps();
    });
}```
</code>```

a table named harga :

public function up()
{
  Schema::create('harga',function(Blueprint $table){
    $table->increments('id');
    $table->integer('paket_id')->unsigned();
    $table->foreign('paket_id')->references('id')->on('paket');
    $table->decimal('harga',13,2);
    $table->string('masa_training');
    $table->string('masa_maintenance');
    $table->date('tanggal_efektif');
    $table->timestamps();
  });
}

A table named produk

public function up()
{
  Schema::create('produk',function(Blueprint $table){
    $table->increments('id');
    $table->string('nama');
    $table->timestamps();
  });
}

Thanks.

答:
Its solved.

Thanks.

======

What i do is : migrate the table from master, and ordered it so i migrate all table that have ID (that is a foreign ID in other table) first.

What i do to make that happend is just rename the timestamp in my file name.

Title: foreign key in my database migration

Body:
I am developing a program in laravel, I am always creating database while I'm writing my code. And now, I want to test my program, so I reset all my database, and try to migrate, suddenly this error appear, anyone know why ?

SQLSTATE[42S01]: Base table or view already exists: 1050 Table 'paket' already exists (SQL: create table `paket` (`id` int unsigned not null aut o_increment primary key, `produk_id` int unsigned not null, `nama` varchar(191) not null, `jumlah_user` int not null, `created_at` timestamp null, `updated_at` timestamp null) default character set utf8mb4 collate utf8mb4_unicode_ci)

And this is my database migration :

User :

public function up()
{
    Schema::create('users', function (Blueprint $table) {
        $table->increments('id');
        $table->string('name');
        $table->string('username')->unique();
        $table->string('email')->unique();
        $table->string('level');
        $table->string('password');
        $table->rememberToken();
        $table->timestamps();
    });
}

a table named paket:

```public function up()
{
    Schema::create('paket',function(Blueprint $table){
      $table->increments('id');
      $table->integer('produk_id')->unsigned();
      $table->foreign('produk_id')->references('id')->on('produk');
      $table->string('nama');
      $table->integer('jumlah_user');
      // $table->date('tanggal_mulai');
      // $table->date('tanggal_terakhir');
      $table->timestamps();
    });
}```

a table named harga :

public function up()
{
  Schema::create('harga',function(Blueprint $table){
    $table->increments('id');
    $table->integer('paket_id')->unsigned();
    $table->foreign('paket_id')->references('id')->on('paket');
    $table->decimal('harga',13,2);
    $table->string('masa_training');
    $table->string('masa_maintenance');
    $table->date('tanggal_efektif');
    $table->timestamps();
  });
}

A table named produk

public function up()
{
  Schema::create('produk',function(Blueprint $table){
    $table->increments('id');
    $table->string('nama');
    $table->timestamps();
  });
}

Thanks.


问:
443 Forbidden, how to use https with Django
Port 443 has been forbidden, so I have to use other port for https. I've tried Port 2408, and the WSGI configure file as follows:
enter image description here

Using command : netstat -lnp | grep , it shows the Port 2048 is listened by httpd，but I still cant access to the site. How should I do? Thank you very much.

答:
I have solve the problem LOL.

if port 443 not available, port 80 is ok, and the configure file is just like the image i post.

one thing should be noticed that when a browser want to access to the site, the url should be changed. It concerns about the protocol and port, and here we use http protocol and 80 port.

Normally, if we just want to view http protocol site, just input the url, like:
www.example.com, or even use example.com.

if the server make a redirection from http://www.example.com to htts://www.exmaple.com， the url input above is ok.

Above situation is under the circumstance that 443 port is open, but 443 port is not open, and no listen service running on httpd, HOW I SHOULD DO ?

you must input  https://www.example.com:80. It means the service is listening to the port 80 and using https.

Therefore, it's not about the server, but the client and browser as well, which should give more attention.


问:
Import a submodule of a package while the pacakge is being loaded
I am importing a package foo1.foo2, whose __init__.py is importing a submodule foo1.foo2.foo3.bar1, which is a file. If I try to import foo1.foo2.foo3.bar2 inside that file I get the following error:

```<code>AttributeError: module 'foo1' has no attribute 'foo2'
</code>```

Given that the use of relative imports is discouraged, how can I solve this issue without using relative imports?

Here is the package structure and file contents that I have:

```<code>/
├── foo1
│   ├── __init__.py:
│   └── foo2
│       ├── __init__.py: "import foo1.foo2.foo3.bar1"
│       └── foo3
│           ├── __init__.py
│           ├── bar1.py: "import foo1.foo2.foo3.bar2 as bar2"
│           └── bar2.py:
└── main.py: "import foo1.foo2"
</code>```

Running python main.py generates the following error:

```<code>Traceback (most recent call last):
  File "main.py", line 1, in <module>
    import foo1.foo2
  File "/foo1/foo2/__init__.py", line 1, in <module>
    import foo1.foo2.foo3.bar1
  File "/foo1/foo2/foo3/bar1.py", line 1, in <module>
    import foo1.foo2.foo3.bar2 as bar2
AttributeError: module 'foo1' has no attribute 'foo2
</code>```

I'm using Python 3.6.0 :: Anaconda 4.3.1.

Thanks!

答:
Change import foo1.foo2.foo3.bar2 as bar2 into from foo1.foo2.foo3 import bar2.

Then it works.

Body:
I am importing a package foo1.foo2, whose __init__.py is importing a submodule foo1.foo2.foo3.bar1, which is a file. If I try to import foo1.foo2.foo3.bar2 inside that file I get the following error:

AttributeError: module 'foo1' has no attribute 'foo2'

Given that the use of relative imports is discouraged, how can I solve this issue without using relative imports?

Here is the package structure and file contents that I have:

/
├── foo1
│   ├── __init__.py:
│   └── foo2
│       ├── __init__.py: "import foo1.foo2.foo3.bar1"
│       └── foo3
│           ├── __init__.py
│           ├── bar1.py: "import foo1.foo2.foo3.bar2 as bar2"
│           └── bar2.py:
└── main.py: "import foo1.foo2"

Running python main.py generates the following error:

Traceback (most recent call last):
  File "main.py", line 1, in <module>
    import foo1.foo2
  File "/foo1/foo2/__init__.py", line 1, in <module>
    import foo1.foo2.foo3.bar1
  File "/foo1/foo2/foo3/bar1.py", line 1, in <module>
    import foo1.foo2.foo3.bar2 as bar2
AttributeError: module 'foo1' has no attribute 'foo2

I'm using Python 3.6.0 :: Anaconda 4.3.1.

Thanks!


问:
Rails 5 ActiveRecord, how to include fields from associated tables?
With Rails 5, Given the models:

```<code>chef_positions
* id
* name

skills
* id
* name

chef_position_skills
* id
* chef_position_id
* skill_id
</code>```

I have a controller method to return the chef_position_skills by chef_position_id:

```<code>  def index
    chef_position = ChefPosition.find(params[:chef_position_id])
    render json: chef_position.chef_position_skills
  end
</code>```

This returns:

```<code> [{"id":1,"chef_position_id":2,"skill_id":1,"created_at":"2017-06-05T15:44:06.821Z","updated_at":"2017-06-05T15:44:06.821Z"},{"id":2,"chef_position_id":2,"skill_id":2,"created_at":"2017-06-05T15:44:06.821Z","updated_at":"2017-06-05T15:44:06.821Z"}]
</code>```

How can I get the controller to do the following:

include skill.name for each record

Do not include the timestamps

答:
```<code>def index
  chef_position = ChefPosition.find(params[:chef_position_id])
  render json: chef_position.chef_position_skills.map(&:json_data)
end

# ChefPositionSkill#json_data
def json_data
  to_json(
    include: { skill: { only: [:name] } },
    only: [:id, :chef_position_id, :skill_id]
  )
end
</code>```

Define a method json_data (just for convenience), and use .map to call it for each chef_position_skill.

The include and only are standard json serializer methods, which assist rails in what needs to be included.

The only drawback (as far as I see), is that now you will have another attribute "skill": { "name": "skill_name" } in your final json.

Body:
With Rails 5, Given the models:

chef_positions
* id
* name

skills
* id
* name

chef_position_skills
* id
* chef_position_id
* skill_id

I have a controller method to return the chef_position_skills by chef_position_id:

  def index
    chef_position = ChefPosition.find(params[:chef_position_id])
    render json: chef_position.chef_position_skills
  end

This returns:

 [{"id":1,"chef_position_id":2,"skill_id":1,"created_at":"2017-06-05T15:44:06.821Z","updated_at":"2017-06-05T15:44:06.821Z"},{"id":2,"chef_position_id":2,"skill_id":2,"created_at":"2017-06-05T15:44:06.821Z","updated_at":"2017-06-05T15:44:06.821Z"}]

How can I get the controller to do the following:

include skill.name for each record

Do not include the timestamps

Body:
def index
  chef_position = ChefPosition.find(params[:chef_position_id])
  render json: chef_position.chef_position_skills.map(&:json_data)
end

# ChefPositionSkill#json_data
def json_data
  to_json(
    include: { skill: { only: [:name] } },
    only: [:id, :chef_position_id, :skill_id]
  )
end

Define a method json_data (just for convenience), and use .map to call it for each chef_position_skill.

The include and only are standard json serializer methods, which assist rails in what needs to be included.

The only drawback (as far as I see), is that now you will have another attribute "skill": { "name": "skill_name" } in your final json.


问:
Verilog input error
I have a couple of errors in my verilog code that pop up when I compile. I believe they are all related. But I can't figure out what the error is. Any help will be greatly appreciated.

The errors are: Two for the input

vlog_a: Error 31004 Syntax error near `input' found

blog_a: Error 31004 Syntax error near 'output' found

```<code>module threeBitComparator;
  input A2,A1,A0;
  input B2,B1,B0;
  output E,GE; //E-Equal,  GE-Greater than or Equal to

  wire X1,X2,X3; //xnor gate
  wire Y1,Y2,Y3,Y4,Y5,Y6; // and & or gates

  xnor
      G1a(X1,A2,B2),
      G1b(X2,A1,B1),
      G1c(X3,A0,B0);

  and
     G2a(Y1,A2,~B2),
     G2b(Y2,A1,~B1),
     G2c(Y3,A0,~B0),
     G2d(Y4,X1,Y2),
     G2e(Y5,X1,X2,Y3),
     G2f(E,X1,X2,X3);

  or
    G3a(Y6,Y1,Y4,Y5),
    G3b(GE,Y6,E);
endmodule
</code>```

答:
I think you forgot to declare your input and output in the module port lists. Adding A2, A1..., etc to the port list will solve the compilation errors. </p>

<p>You can check the updated code here. </p>

Title: Verilog input error

Body:
I have a couple of errors in my verilog code that pop up when I compile. I believe they are all related. But I can't figure out what the error is. Any help will be greatly appreciated.

The errors are: Two for the input

vlog_a: Error 31004 Syntax error near `input' found

blog_a: Error 31004 Syntax error near 'output' found

module threeBitComparator;
  input A2,A1,A0;
  input B2,B1,B0;
  output E,GE; //E-Equal,  GE-Greater than or Equal to

  wire X1,X2,X3; //xnor gate
  wire Y1,Y2,Y3,Y4,Y5,Y6; // and & or gates

  xnor
      G1a(X1,A2,B2),
      G1b(X2,A1,B1),
      G1c(X3,A0,B0);

  and
     G2a(Y1,A2,~B2),
     G2b(Y2,A1,~B1),
     G2c(Y3,A0,~B0),
     G2d(Y4,X1,Y2),
     G2e(Y5,X1,X2,Y3),
     G2f(E,X1,X2,X3);

  or
    G3a(Y6,Y1,Y4,Y5),
    G3b(GE,Y6,E);
endmodule

Body:
I think you forgot to declare your input and output in the module port lists. Adding A2, A1..., etc to the port list will solve the compilation errors.

You can check the updated code here.


问:
Alias with variable in bash
I want to create an alias in bash like this:

```<code>alias tail_ls="ls -l $1 | tail"
</code>```

Thus, if somebody types:

```<code>tail_ls /etc/
</code>```

it will only show the last 10 files in the directory.

But $1 does not seem to work for me. Is there any way I can introduce variables in bash.

答: tail_ls() { ls -l "$1" | tail; }

Title: Alias with variable in bash

Body:
I want to create an alias in bash like this:

alias tail_ls="ls -l $1 | tail"

Thus, if somebody types:

tail_ls /etc/

it will only show the last 10 files in the directory.

But $1 does not seem to work for me. Is there any way I can introduce variables in bash.

Body: tail_ls() { ls -l "$1" | tail; }


问:
Laravel 4.2 Send email to user after post respond
so I have a ticket system, and what I want to do is when the user post a comment the other party should get an email, here is what I've accomplished so far:

In the CommentsController:

```<code>public function postComment($id) {
    $content = trim(Input::get('content'));
    if (empty($content)) {
        return Redirect::back();
    }
    if (Auth::user()->isAdmin() || $this->tickets->isTicketBelongsToUser(Auth::user()->id, $id)) {
        if (Input::hasFile('attachment')) {
            $attachmendId = Uploader::attach(Input::file('attachment'));
        }
        $comment = $this->comments->getNew(['content' => Input::get('content'), 'user_id' => Auth::user()->id, 'attachment_id' => isset($attachmendId) ? $attachmendId : null, 'ticket_id' => $id]);

    //START geting the user id and send email//

    $client = $this->users->$id;
    $this->userMailer->CommentRespond($id);

    //END geting the user id and send email//

        $this->comments->save($comment);
    }
    return Redirect::back()->withMessage('Your comment has been sent');
}
</code>```

In the UserMailer.php:

```<code> public function CommentRespond(User $user)
    {
        $view    = 'emails.new-comment';
        $subject = 'New Comment has been posted';
        $data    = [
        'name' => $user->name
        ];
        return $this->sendTo($user->email, $subject, $view, $data);
    }
</code>```

Error:

```<code> ErrorException (E_NOTICE)

Undefined property: Care\Repositories\Eloquent\UsersRepository::$93
</code>```

I know it there is something wrong with the variable assigning but I couldn't find it out, so please if you can help that will be great.

thanks

答:
I think this is the culprit.

```<code>//START geting the user id and send email//
//$client = $this->users->$id; <-- Wrong One
$client = $this->users->id;
$this->userMailer->CommentRespond($id);
</code>```

I suggest you convert in to this.

UPDATE:
change the retrieval of user row to

```<code>$client = $this->users->getById($id);
$this->userMailer->CommentRespond($client);
</code>```

then update CommentRespond

```<code>public function CommentRespond($user)
{
    $view    = 'emails.new-comment';
    $subject = 'New Comment has been posted';
    $data    = [
    'name' => $user['name']
    ];
    return $this->sendTo($user['email'], $subject, $view, $data);
}
</code>```

Body:
so I have a ticket system, and what I want to do is when the user post a comment the other party should get an email, here is what I've accomplished so far:

In the CommentsController:

public function postComment($id) {
    $content = trim(Input::get('content'));
    if (empty($content)) {
        return Redirect::back();
    }
    if (Auth::user()->isAdmin() || $this->tickets->isTicketBelongsToUser(Auth::user()->id, $id)) {
        if (Input::hasFile('attachment')) {
            $attachmendId = Uploader::attach(Input::file('attachment'));
        }
        $comment = $this->comments->getNew(['content' => Input::get('content'), 'user_id' => Auth::user()->id, 'attachment_id' => isset($attachmendId) ? $attachmendId : null, 'ticket_id' => $id]);

    //START geting the user id and send email//

    $client = $this->users->$id;
    $this->userMailer->CommentRespond($id);

    //END geting the user id and send email//

        $this->comments->save($comment);
    }
    return Redirect::back()->withMessage('Your comment has been sent');
}

In the UserMailer.php:

 public function CommentRespond(User $user)
    {
        $view    = 'emails.new-comment';
        $subject = 'New Comment has been posted';
        $data    = [
        'name' => $user->name
        ];
        return $this->sendTo($user->email, $subject, $view, $data);
    }

Error:

 ErrorException (E_NOTICE)

Undefined property: Care\Repositories\Eloquent\UsersRepository::$93

I know it there is something wrong with the variable assigning but I couldn't find it out, so please if you can help that will be great.

thanks

Body:
I think this is the culprit.

//START geting the user id and send email//
//$client = $this->users->$id; <-- Wrong One
$client = $this->users->id;
$this->userMailer->CommentRespond($id);

I suggest you convert in to this.

UPDATE:
change the retrieval of user row to

$client = $this->users->getById($id);
$this->userMailer->CommentRespond($client);

then update CommentRespond

public function CommentRespond($user)
{
    $view    = 'emails.new-comment';
    $subject = 'New Comment has been posted';
    $data    = [
    'name' => $user['name']
    ];
    return $this->sendTo($user['email'], $subject, $view, $data);
}


问:
How we can copy any file within Azure Data Lake Store folders
We already have Move-AzureRmDataLakeStoreItemwhich will move files between folders inside Azure datalake. What I am seeking is to copy files within the datalake without effecting the original file.

The possibilities that I know are-

using USQL to EXTRACT data from sourcefile and then OUTPUT to the destinationfile - but I am trying to copy all sort of files (.gz,.txt,.info,.exe,.msi) and I am not sure if USQL can help me with .gz or .exe or .msi files

using Data Factory to copy data from/to Data Lake store

So, my ask here is do we have anything else at our disposal with which we can perform a copy of files within Azure Data Lake Store?

答:
You have couple of other options,

run distcp on an HDI cluster - Similar to instructions provided here. https://learn.microsoft.com/en-us/azure/data-lake-store/data-lake-store-copy-data-wasb-distcp

use adlcopy if you are copying limited amount of data (saying 10-100's of GB) - https://learn.microsoft.com/en-us/azure/data-lake-store/data-lake-store-copy-data-azure-storage-blob

Does this suffice please? Or do you want something natively supported by Azure Data Lake Store via its REST APIs?

Thanks,
Sachin Sheth
Program Manager, Azure Data Lake.


问:
Error: Cannot find module '@ionic/app-scripts'
I'm new to Ionic. I was following the Ionic documentation "get started", created a project sample named "super". The problem is that when I run the command line ionic serve in the project directory, it threw an error Error: Cannot find module '@ionic/app-scripts'

答:
Try installing app-script from npm

npm i @ionic/app-scripts


问:
Jupyter Noterbook error
I just cannot use jupyter notebook. I have updated to the most recent version by      ananota, and it still does not work.
The error message is listed below:</p>

```<code>C:\Users\willian>jupyter notebook
Traceback (most recent call last):
File "C:\Anaconda3\Scripts\jupyter-notebook-script.py", line 3, in <module>
import notebook.notebookapp
File "C:\Anaconda3\lib\site-packages\notebook\notebookapp.py", line 40, in   <module>
ioloop.install()
File "C:\Anaconda3\lib\site-packages\zmq\eventloop\ioloop.py", line 207, in install
from tornado import ioloop
File "C:\Anaconda3\lib\site-packages\tornado\ioloop.py", line 47, in <module>
from tornado.concurrent import TracebackFuture, is_future
File "C:\Anaconda3\lib\site-packages\tornado\concurrent.py", line 34, in <module>
from tornado.util import raise_exc_info, ArgReplacer, is_finalizing
ImportError: cannot import name 'is_finalizing'
</code>```

答:
From your error it looks like the tornado package is not installed in your environment. Installing tornado with the command below should fix your problem.</p>

```<code>pip install tornado
</code>```

Title: Jupyter Noterbook error

Body:
I just cannot use jupyter notebook. I have updated to the most recent version by      ananota, and it still does not work.
The error message is listed below:

C:\Users\willian>jupyter notebook
Traceback (most recent call last):
File "C:\Anaconda3\Scripts\jupyter-notebook-script.py", line 3, in <module>
import notebook.notebookapp
File "C:\Anaconda3\lib\site-packages\notebook\notebookapp.py", line 40, in   <module>
ioloop.install()
File "C:\Anaconda3\lib\site-packages\zmq\eventloop\ioloop.py", line 207, in install
from tornado import ioloop
File "C:\Anaconda3\lib\site-packages\tornado\ioloop.py", line 47, in <module>
from tornado.concurrent import TracebackFuture, is_future
File "C:\Anaconda3\lib\site-packages\tornado\concurrent.py", line 34, in <module>
from tornado.util import raise_exc_info, ArgReplacer, is_finalizing
ImportError: cannot import name 'is_finalizing'

Body:
From your error it looks like the tornado package is not installed in your environment. Installing tornado with the command below should fix your problem.

pip install tornado


问:
Mongoid getting no server is available matching preference
I have a bunch of sidekiq jobs running that are failing with the following error when I'm trying to perform a query to the DB:

```<code>No server is available matching preference: #<Mongo::ServerSelector::Primary:0x70249928071560 tag_sets=[] server_selection_timeout=30 local_threshold=0.015>
</code>```

This seems to happen randomly, and not all the time. My mongoid.yml is structured as following:

```<code>hosts:
    - XX.XXX.XXX.X:27000
    - XX.XXX.XXX.XXX:27000
  database: acbde__production
  options:
    connect_timeout: 20
    read:
      mode: :secondary
    max_pool_size: 800
    replica_set: acbdeReplset
</code>```

Anyone had this issue before?

答:
You should check whether mongodb is actually running.

You can use mongo --host IP --port PORT to check connection.

Body:
I have a bunch of sidekiq jobs running that are failing with the following error when I'm trying to perform a query to the DB:

No server is available matching preference: #<Mongo::ServerSelector::Primary:0x70249928071560 tag_sets=[] server_selection_timeout=30 local_threshold=0.015>

This seems to happen randomly, and not all the time. My mongoid.yml is structured as following:

hosts:
    - XX.XXX.XXX.X:27000
    - XX.XXX.XXX.XXX:27000
  database: acbde__production
  options:
    connect_timeout: 20
    read:
      mode: :secondary
    max_pool_size: 800
    replica_set: acbdeReplset

Anyone had this issue before?


问:
How to wait for jQuery Ajax requests to complete from WatiN?
I'm writing WatiN tests to test an Ajax web application and have come across a timing issue with Ajax requests.

After an Ajax request is triggered by an action on the page, I'd like WatiN to wait until the request is complete before validating that the page was updated correctly.

I have a feeling that the solution will involve eval-ing JavaScript to register handlers for $.ajaxStart and $.ajaxComplete to track whether requests are in progress. I'll dig into that shortly, but wanted to see if anybody else has already solved this. Seems like it would be a common problem with Ajax testing.

答:
This solution doesn't work very well because .ajaxStart is called only for the first Ajax request, while .ajaxComplete is called each time an ajax request is finished. if you run a this simple code in your console :

```<code>$.ajax({url:"/"}); $.ajax({url:"/"})
</code>```

and add some logging in the .ajaxStart and .ajaxComplete handler methods, you can see that .ajaxStart handler will be called only once and .ajaxComplete handler twice. So ajaxRequestCount will become negative and all your design is screwed.

I suggest that you use .ajaxSend instead of .ajaxStart if you want to keep your design.

Another solution would be to use .ajaxStop instead of .ajaxComplete, but by doing so, you don't need the ajaxRequestCount, you only need a boolean that say if there are ajax requests running behind the scene.

Very useful information can be found : http://api.jquery.com/category/ajax/global-ajax-event-handlers/

Hope this helps.

Body:
This solution doesn't work very well because .ajaxStart is called only for the first Ajax request, while .ajaxComplete is called each time an ajax request is finished. if you run a this simple code in your console :

$.ajax({url:"/"}); $.ajax({url:"/"})

and add some logging in the .ajaxStart and .ajaxComplete handler methods, you can see that .ajaxStart handler will be called only once and .ajaxComplete handler twice. So ajaxRequestCount will become negative and all your design is screwed.

I suggest that you use .ajaxSend instead of .ajaxStart if you want to keep your design.

Another solution would be to use .ajaxStop instead of .ajaxComplete, but by doing so, you don't need the ajaxRequestCount, you only need a boolean that say if there are ajax requests running behind the scene.

Very useful information can be found : http://api.jquery.com/category/ajax/global-ajax-event-handlers/

Hope this helps.


问:
How to display text on GTK label using two different fonts?
I have a GTK label and I am displaying text on it in Arial Rounded Mt Bold by using following code:

```<code>PangoFontDescription *df;
df = pango_font_description_new ();
pango_font_description_set_family(df,"Arial Rounded Mt Bold");
pango_font_description_set_size(df,fontsize*PANGO_SCALE);
gtk_widget_modify_font(Message_Label, df);
gtk_label_set_text(GTK_LABEL(Label), "Hello World");
pango_font_description_free (df);
</code>```

Now this Hello World is displayed in Arial Rounded Mt Bold. But what if I want to display Hello in Arial Rounded Mt Bold and World in some other font for example Arial. Is this possible in GTK label. I am doing it in C. Any advice or any useful links. Thanks.

答:
gtk_widget_modify_font() is deprecated and won't let you do what you want.

You can use a PangoAttrList, which combines attributes (including the individual components of a PangoFontDescriptor) over ranges of text. For instance:

```<code>PangoAttrList *attrlist;
PangoAttribute *attr;
PangoFontDescription *df;

attrlist = pango_attr_list_new();

// First, let's set up the base attributes.
// This part is copied from your code (and slightly bugfixed and reformatted):
df = pango_font_description_new();
pango_font_description_set_family(df, "Arial Rounded MT");
pango_font_description_set_size(df, fontsize * PANGO_SCALE);
pango_font_description_set_weight(df, PANGO_WEIGHT_BOLD);
// You can also use pango_font_description_new_from_string() and pass in a string like "Arial Rounded MT Bold (whatever fontsize is)".
// But here's where things change:
attr = pango_attr_font_desc_new(df);
// This is not documented, but pango_attr_font_desc_new() makes a copy of df, so let's release ours:
pango_font_description_free(df);
// Pango and GTK+ use UTF-8, so our string is indexed between 0 and 11.
// Note that the end_index is exclusive!
attr->start_index = 0;
attr->end_index = 11;
pango_attr_list_insert(attrlist, attr);
// And pango_attr_list_insert() takes ownership of attr, so we don't free it ourselves.
// As an alternative to all that, you can have each component of the PangoFontDescriptor be its own attribute; see the PangoAttribute documentation page.

// And now the attribute for the word "World".
attr = pango_attr_family_new("Arial");
// "World" starts at 6 and ends at 11.
attr->start_index = 6;
attr->end_index = 11;
pango_attr_list_insert(attrlist, attr);

// And finally, give the GtkLabel our attribute list.
gtk_label_set_attributes(GTK_LABEL(Label), attrlist);
// And (IIRC this is not documented either) gtk_label_set_attributes() takes a reference on the attribute list, so we can remove ours.
pango_attr_list_unref(attrlist);
</code>```

You can also use gtk_label_set_markup() to use an HTML-like markup language to set both text and styles in one go:

```<code>gtk_label_set_markup(GTK_LABEL(Label),
    "<span face=\"Arial Rounded MT\" size=\"(whatever fontsize * PANGO_SCALE is)\" weight=\"bold\">Hello <span face=\"Arial\">World</span></span>");
// Or even...
gtk_label_set_markup(GTK_LABEL(Label),
    "<span font=\"Arial Rounded MT Bold (whatever fontsize is)\">Hello <span face=\"Arial\">World</span></span>");
</code>```

Body:
I have a GTK label and I am displaying text on it in Arial Rounded Mt Bold by using following code:

PangoFontDescription *df;
df = pango_font_description_new ();
pango_font_description_set_family(df,"Arial Rounded Mt Bold");
pango_font_description_set_size(df,fontsize*PANGO_SCALE);
gtk_widget_modify_font(Message_Label, df);
gtk_label_set_text(GTK_LABEL(Label), "Hello World");
pango_font_description_free (df);

Now this Hello World is displayed in Arial Rounded Mt Bold. But what if I want to display Hello in Arial Rounded Mt Bold and World in some other font for example Arial. Is this possible in GTK label. I am doing it in C. Any advice or any useful links. Thanks.

Body:
gtk_widget_modify_font() is deprecated and won't let you do what you want.

You can use a PangoAttrList, which combines attributes (including the individual components of a PangoFontDescriptor) over ranges of text. For instance:

PangoAttrList *attrlist;
PangoAttribute *attr;
PangoFontDescription *df;

attrlist = pango_attr_list_new();

// First, let's set up the base attributes.
// This part is copied from your code (and slightly bugfixed and reformatted):
df = pango_font_description_new();
pango_font_description_set_family(df, "Arial Rounded MT");
pango_font_description_set_size(df, fontsize * PANGO_SCALE);
pango_font_description_set_weight(df, PANGO_WEIGHT_BOLD);
// You can also use pango_font_description_new_from_string() and pass in a string like "Arial Rounded MT Bold (whatever fontsize is)".
// But here's where things change:
attr = pango_attr_font_desc_new(df);
// This is not documented, but pango_attr_font_desc_new() makes a copy of df, so let's release ours:
pango_font_description_free(df);
// Pango and GTK+ use UTF-8, so our string is indexed between 0 and 11.
// Note that the end_index is exclusive!
attr->start_index = 0;
attr->end_index = 11;
pango_attr_list_insert(attrlist, attr);
// And pango_attr_list_insert() takes ownership of attr, so we don't free it ourselves.
// As an alternative to all that, you can have each component of the PangoFontDescriptor be its own attribute; see the PangoAttribute documentation page.

// And now the attribute for the word "World".
attr = pango_attr_family_new("Arial");
// "World" starts at 6 and ends at 11.
attr->start_index = 6;
attr->end_index = 11;
pango_attr_list_insert(attrlist, attr);

// And finally, give the GtkLabel our attribute list.
gtk_label_set_attributes(GTK_LABEL(Label), attrlist);
// And (IIRC this is not documented either) gtk_label_set_attributes() takes a reference on the attribute list, so we can remove ours.
pango_attr_list_unref(attrlist);

You can also use gtk_label_set_markup() to use an HTML-like markup language to set both text and styles in one go:

gtk_label_set_markup(GTK_LABEL(Label),
    "<span face=\"Arial Rounded MT\" size=\"(whatever fontsize * PANGO_SCALE is)\" weight=\"bold\">Hello <span face=\"Arial\">World</span></span>");
// Or even...
gtk_label_set_markup(GTK_LABEL(Label),
    "<span font=\"Arial Rounded MT Bold (whatever fontsize is)\">Hello <span face=\"Arial\">World</span></span>");


问:
Python kafka consumer group id issue
AFAIK,

The concept of partitions and (consumer) groups in kafka was introduced to implement parallelism. I am working with kafka through python. I have a certain topic, which has (say) 2 partitions. This means, if I start a consumer group with 2 consumers in it, they will be mapped(subscribed) to different partitions.

But, using kafka library in python, I came across a weird issue. I started 2 consumers with essentially the same group-ids, and started the threads for them to consume messages.

But, every message in the kafka-stream is being consumed by both of them !! This seems ridiculous to me, and even conceptually incorrect. Is there anyway I can map the consumers to certain (distinct) partitions manually (if they are not mapped to different partitions automatically)?

Here is the code:

```<code>from kafka import KafkaConsumer
import thread

def con1(consumer):
    for msg in consumer:
        print msg

consumer1 = KafkaConsumer('k-test', group_id='grp1', bootstrap_servers=['10.50.23.120:9092'])
consumer2 = KafkaConsumer('k-test', group_id='grp1', bootstrap_servers=['10.50.23.120:9092'])

thread.start_new_thread(con1, (consumer1,))
thread.start_new_thread(con1, (consumer2,))
</code>```

Here is the output for some messages that I produced using kafka-console-producer:

```<code>ConsumerRecord(topic=u'k-test', partition=0, offset=47, timestamp=None, timestamp_type=None, key=None, value='polki')
ConsumerRecord(topic=u'k-test', partition=0, offset=47, timestamp=None, timestamp_type=None, key=None, value='polki')
ConsumerRecord(topic=u'k-test', partition=0, offset=48, timestamp=None, timestamp_type=None, key=None, value='qwewrg')
ConsumerRecord(topic=u'k-test', partition=0, offset=48, timestamp=None, timestamp_type=None, key=None, value='qwewrg')
ConsumerRecord(topic=u'k-test', partition=0, offset=49, timestamp=None, timestamp_type=None, key=None, value='shgjas')
ConsumerRecord(topic=u'k-test', partition=0, offset=49, timestamp=None, timestamp_type=None, key=None, value='shgjas')
</code>```

while expected was one of each. BTW, this topic k-test has 2 partitions.

答: Try running the bin/kafka-consumer-groups.sh command line tool to verify if the Python Kafka client you are using supports proper consumer group management. If both consumers are indeed in the same group then they should get messages from mutually exclusive partitions.</p>

Title: Python kafka consumer group id issue

Body:
AFAIK,

The concept of partitions and (consumer) groups in kafka was introduced to implement parallelism. I am working with kafka through python. I have a certain topic, which has (say) 2 partitions. This means, if I start a consumer group with 2 consumers in it, they will be mapped(subscribed) to different partitions.

But, using kafka library in python, I came across a weird issue. I started 2 consumers with essentially the same group-ids, and started the threads for them to consume messages.

But, every message in the kafka-stream is being consumed by both of them !! This seems ridiculous to me, and even conceptually incorrect. Is there anyway I can map the consumers to certain (distinct) partitions manually (if they are not mapped to different partitions automatically)?

Here is the code:

from kafka import KafkaConsumer
import thread

def con1(consumer):
    for msg in consumer:
        print msg

consumer1 = KafkaConsumer('k-test', group_id='grp1', bootstrap_servers=['10.50.23.120:9092'])
consumer2 = KafkaConsumer('k-test', group_id='grp1', bootstrap_servers=['10.50.23.120:9092'])

thread.start_new_thread(con1, (consumer1,))
thread.start_new_thread(con1, (consumer2,))

Here is the output for some messages that I produced using kafka-console-producer:

ConsumerRecord(topic=u'k-test', partition=0, offset=47, timestamp=None, timestamp_type=None, key=None, value='polki')
ConsumerRecord(topic=u'k-test', partition=0, offset=47, timestamp=None, timestamp_type=None, key=None, value='polki')
ConsumerRecord(topic=u'k-test', partition=0, offset=48, timestamp=None, timestamp_type=None, key=None, value='qwewrg')
ConsumerRecord(topic=u'k-test', partition=0, offset=48, timestamp=None, timestamp_type=None, key=None, value='qwewrg')
ConsumerRecord(topic=u'k-test', partition=0, offset=49, timestamp=None, timestamp_type=None, key=None, value='shgjas')
ConsumerRecord(topic=u'k-test', partition=0, offset=49, timestamp=None, timestamp_type=None, key=None, value='shgjas')

while expected was one of each. BTW, this topic k-test has 2 partitions.


问:
Left outer join with 3 tables and subquery
sorry for the late response.

For a key in table A, there may be 2 or more records present in tables B and C. That is, one another column in these tables will have a date value which would be making the keys unique. So I want to extract the record that has maximum date value. And that's why I am using the max function. I know that the subquery which I have coded should not be included in the ON clause and it would do the filtering before the join statement. So eventually I want to know how to mention the max clause in the query.

Example:
Table A
Key - AAAAA

Table B:
Record 1
Key - AAAAA
Date - 2017-10-01

Record 2
Key - AAAAA
Date - 2017-10-05

I want the only the record AAAAA/2017-10-05 to be selected from the table B

Basically records from table A where A.c3 = 'Y' should be extracted first (assume it gives 500 records)
Then join these 500 records with tables B and C (left outer, to have all the matching records and the non-matching records should have nulls in the columns from the tables B and C)
In tables B and C, if more than 1 record present with different dates, the maximum date field should be extracted.

Hence final output should contain 500 records.

答:
This is all you need for what you describe

```<code>SELECT A.A1, A.A2, B.B1, B.B2, C.C1, C.C2
FROM TABLE1 A
LEFT OUTER JOIN TABLE2 B
ON A.A1 = B.B1
LEFT OUTER JOIN TABLE3 C
ON A.A1 = C.C1
WHERE A.C3 = ‘Y’
</code>```

These lines are causing your problem...basically forcing your outer joins to an inner joins.

```<code>AND B.C3 = (SELECT MAX(B3) FROM TABLE2 T1
        WHERE T1.B1 = B.B1)
AND C.C3 = (SELECT MAX(C3) FROM TABLE3 T1
        WHERE T1.C1 = C.C1)
</code>```

If there's no match in B or C , then B.C3 and/or C.C3 will be NULL and NULL can't be = to anything (or <> to anything for that matter)

What are you trying to accomplish with the above that you've not included in the question?

Body:
This is all you need for what you describe

SELECT A.A1, A.A2, B.B1, B.B2, C.C1, C.C2
FROM TABLE1 A
LEFT OUTER JOIN TABLE2 B
ON A.A1 = B.B1
LEFT OUTER JOIN TABLE3 C
ON A.A1 = C.C1
WHERE A.C3 = ‘Y’

These lines are causing your problem...basically forcing your outer joins to an inner joins.

AND B.C3 = (SELECT MAX(B3) FROM TABLE2 T1
        WHERE T1.B1 = B.B1)
AND C.C3 = (SELECT MAX(C3) FROM TABLE3 T1
        WHERE T1.C1 = C.C1)

If there's no match in B or C , then B.C3 and/or C.C3 will be NULL and NULL can't be = to anything (or <> to anything for that matter)

What are you trying to accomplish with the above that you've not included in the question?


问:
Angular js table with dynamic columns and values
I have a data structure as follow;

```<code>[
  {
    "a1": 941,
    "b1": "abc",
    "c1": "aaa",
    "a2": 27103,
    "b2": "ttt",
    "c2": "zzz"
  },
  {
    "a1": 456,
    "b1": "xxx",
    "c1": "yyy",
    "a2": 7632,
    "b2": "mmm",
    "c2": "nnn"
  }
]
</code>```

I use angular js table with dynamic column names which are different from keys in the structure. Since there are many of them, I do not want to write key names like;

```<code> <table st-table="table_data_raw" style="" class="table table-striped forms-list-table">
    <tr>
        <th ng-repeat="dateColumnName in dateColumnNames ">{{ dateColumnName }}
        </th>
    </tr>
    <tbody>
        <tr ng-repeat="row in data">
            <td>{{row.a1 }}</td>
            <td>{{row.b1 }}</td>
            <td>{{row.a2 }}</td>
            <td>{{row.b2 }}</td>
            <td>{{row.c2 }}</td>
        </tr>
    </tbody>
 </table>
</code>```

How can I get table values dynamically without specifying their names in that structure from "data"?

答:
Try using $index to refer to the ng-repeat item you wish to access (in your example it would be index 0 or 1). Here is code/fiddle (click items in the table to get their value dynamically):
https://jsfiddle.net/AdamKMorris/ox89o7L0/

using $Index:

```<code>  <tr ng-repeat="row in data">
            <td ng-click="chosenValueA1($index);">{{row.a1 }}</td>
            ...
  </tr>
</code>```

Then the angularJs:

```<code>  $scope.chosenValueA1 = function(i)
  {
    $scope.myValue = $scope.data[i].a1;
  }
</code>```

If you want to access a1,a2,b1,b2, etc. then you will need to nest ng-repeat and use $index for each to refer to the value.

Body:
I have a data structure as follow;

[
  {
    "a1": 941,
    "b1": "abc",
    "c1": "aaa",
    "a2": 27103,
    "b2": "ttt",
    "c2": "zzz"
  },
  {
    "a1": 456,
    "b1": "xxx",
    "c1": "yyy",
    "a2": 7632,
    "b2": "mmm",
    "c2": "nnn"
  }
]

I use angular js table with dynamic column names which are different from keys in the structure. Since there are many of them, I do not want to write key names like;

        {{ dateColumnName }}

            {{row.a1 }}
            {{row.b1 }}
            {{row.a2 }}
            {{row.b2 }}
            {{row.c2 }}

How can I get table values dynamically without specifying their names in that structure from "data"?

Body:
Try using $index to refer to the ng-repeat item you wish to access (in your example it would be index 0 or 1). Here is code/fiddle (click items in the table to get their value dynamically):
https://jsfiddle.net/AdamKMorris/ox89o7L0/

using $Index:

  <tr ng-repeat="row in data">
            <td ng-click="chosenValueA1($index);">{{row.a1 }}</td>
            ...
  </tr>

Then the angularJs:

  $scope.chosenValueA1 = function(i)
  {
    $scope.myValue = $scope.data[i].a1;
  }

If you want to access a1,a2,b1,b2, etc. then you will need to nest ng-repeat and use $index for each to refer to the value.


问:
What does the "automatically adjusts font requires using a dynamic type text style" warning mean?
I am getting the following warning:

"automatically adjusts font requires using a dynamic type text style"

Which I can not get rid of the warning is on main.storyboard.

I have checked every UILabel in the Identity Inspector to make sure the "Automatically Adjusts Font" is unchecked.

答:
Open your storyboard as Source Code

Search for key "adjustsFontForContentSizeCategory"

Check which object has this option and uncheck Dynamic Type checkbox from interface builder.


问:
Dateformat dd/MM/yyyy HH:mm z is crashing while converting string to Date Swift 3.0
I am parsing this DateString 01/06/2017 14:31 GMT+10:00 into Date using date format dd/MM/yyyy HH:mm z but some times it gives nil values. and some times it works correctly.

Can you suggest correct Date format for this date string.

I am using swift 3.0 and Xcode 8.3.

My codes are :

```<code>static func getTimestampFromDateString(dateString:String) -> Int64{
    let separated = dateString.components(separatedBy: " ")
    let currentUser = User.getLoggedInUserDataModel()
    let finalDateStr = "\(String.getString(separated[0])) \(String.getString(separated[1])) \(String.getString(currentUser.timeZoneOffset))"

    let date = convertStringToDate(dateString: finalDateStr, dateFormat: "dd/MM/yyyy HH:mm z")
    let timestamp = Int64(date.timeIntervalSince1970)
    return timestamp
}
static func convertStringToDate(dateString:String,dateFormat:String)->Date{
    let dateFormatter = DateFormatter()
    dateFormatter.dateFormat = dateFormat
    let date:Date = dateFormatter.date(from: dateString)!
    return date
}
</code>```

答:
You can resolve the problem in two steps :
        1: Check the date formate of finalDateStr, if finalDateStr is same as "dd/MM/yyyy HH:mm z" then you can convert string in this formate.
        2: Check nil before force unwrapping the dateFormatter.date(from: dateString)!

example

```<code> if let date = dateFormatter.date(from: dateString)!

{

// got the date

}else {
  // check finalDateStr formate

}
</code>```

Body:
I am parsing this DateString 01/06/2017 14:31 GMT+10:00 into Date using date format dd/MM/yyyy HH:mm z but some times it gives nil values. and some times it works correctly.

Can you suggest correct Date format for this date string.

I am using swift 3.0 and Xcode 8.3.

My codes are :

static func getTimestampFromDateString(dateString:String) -> Int64{
    let separated = dateString.components(separatedBy: " ")
    let currentUser = User.getLoggedInUserDataModel()
    let finalDateStr = "\(String.getString(separated[0])) \(String.getString(separated[1])) \(String.getString(currentUser.timeZoneOffset))"

    let date = convertStringToDate(dateString: finalDateStr, dateFormat: "dd/MM/yyyy HH:mm z")
    let timestamp = Int64(date.timeIntervalSince1970)
    return timestamp
}
static func convertStringToDate(dateString:String,dateFormat:String)->Date{
    let dateFormatter = DateFormatter()
    dateFormatter.dateFormat = dateFormat
    let date:Date = dateFormatter.date(from: dateString)!
    return date
}

Body:
You can resolve the problem in two steps :
        1: Check the date formate of finalDateStr, if finalDateStr is same as "dd/MM/yyyy HH:mm z" then you can convert string in this formate.
        2: Check nil before force unwrapping the dateFormatter.date(from: dateString)!

example

 if let date = dateFormatter.date(from: dateString)!

{

// got the date

}else {
  // check finalDateStr formate

}


问:
Redirecting PDF links from another domain using htaccess
We have two domains, let's call them first.com and second.com

We have a directory in second.com called reports, where all our PDFs are located, but we would like to these same PDFs accessible from first.com as well.

Can we redirect let's say first.com/reports/84839049.pdf to second.com/reports/84839049.pdf using htaccess?

答:
```<code>Options +FollowSymLinks
RewriteEngine on
RewriteCond %{HTTP_HOST} .
RewriteCond %{HTTP_HOST} !^domain\.com
RewriteRule (.*) http://domain1.com/$1 [R=301, L]
</code>```


问:
Unable to retrieve JSON file in Angular 2 project
I am trying to display static JSON data in my angular 2 project. I am getting a console error 'GET http://localhost:4200/app/data/MOCK_DATA.json 404 (Not Found)' I have added my services.ts and component.ts pages.

service.ts

```<code>import { Injectable } from '@angular/core';
import { ConfigurationService } from '../../configuration.service';
import { Http, Response, RequestOptions, Headers } from '@angular/http';
import { Observable } from 'rxjs';
import { ListItem } from './list-item';

@Injectable()
export class DataService {

  constructor(
    private _http: Http,
    private _configurationService: ConfigurationService
  ) {}

 get() : Observable<ListItem[]> {
      return this._http.get("app/data/MOCK_DATA.json")
      .map((response: Response) => <ListItem[]> response.json())

  }
}
</code>```

app.component.ts

```<code>import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';
import { DataService } from '../data.service';
import { ListItem } from './list-item';
import { Subscription } from 'rxjs';

@Component({
  selector: 'app-component',
  templateUrl: 'component.html',
  styleUrls: ['component.css']
})
export class Component implements OnInit {

  busy:Subscription;
  datas: ListItem[] = [];

  constructor(
    private _dataService: DataService,
    private _confirmationService: ConfirmationService,
    private _authService: AuthService,
    private _router: Router,
  ) {

  }

  ngOnInit(){

  }
getdatas() {
    this.busy =
      this._dataService.get()
        .subscribe(data => this.datas = data)
  }
</code>```

答:
Since it is static. there is no need to http.get.

Create a json.ts file

export your JSON file as

```<code>export const json={
    "key":"value"
}
</code>```

then import it where required

import { json } from './json.ts'

then console.log(json) inside the class to check the file/json.

Body:
I am trying to display static JSON data in my angular 2 project. I am getting a console error 'GET http://localhost:4200/app/data/MOCK_DATA.json 404 (Not Found)' I have added my services.ts and component.ts pages.

service.ts

import { Injectable } from '@angular/core';
import { ConfigurationService } from '../../configuration.service';
import { Http, Response, RequestOptions, Headers } from '@angular/http';
import { Observable } from 'rxjs';
import { ListItem } from './list-item';

@Injectable()
export class DataService {

  constructor(
    private _http: Http,
    private _configurationService: ConfigurationService
  ) {}

 get() : Observable<ListItem[]> {
      return this._http.get("app/data/MOCK_DATA.json")
      .map((response: Response) => <ListItem[]> response.json())

  }
}

app.component.ts

import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';
import { DataService } from '../data.service';
import { ListItem } from './list-item';
import { Subscription } from 'rxjs';

@Component({
  selector: 'app-component',
  templateUrl: 'component.html',
  styleUrls: ['component.css']
})
export class Component implements OnInit {

  busy:Subscription;
  datas: ListItem[] = [];

  constructor(
    private _dataService: DataService,
    private _confirmationService: ConfirmationService,
    private _authService: AuthService,
    private _router: Router,
  ) {

  }

  ngOnInit(){

  }
getdatas() {
    this.busy =
      this._dataService.get()
        .subscribe(data => this.datas = data)
  }

Body:
Since it is static. there is no need to http.get.

Create a json.ts file

export your JSON file as

export const json={
    "key":"value"
}

then import it where required

import { json } from './json.ts'

then console.log(json) inside the class to check the file/json.


问:
Json event does not work, and the weekday is not right
On my calendar there are dates that have events. The dates with the events should be highlighted with data received from a JSON call. When I click on an event date the event should be shown. The problem is my JSON data is not being fetched and the events don't show. Also, the weekday isn't right.

My showInfo code that makes the JSON request is below. The Codepen shows the full code example.

```<code> // show info
function showInfo(event) {
  // link
  var url = 'https://codepen.io/nakome/pen/EWBMzm.css';
  // get json
  getjson(url, function(obj) {
    for (var key in obj) {
      // if has envent add class
      if(_('[data-id="' + key + '"]')){
        _('[data-id="' + key + '"]').classList.add('event');
      }
      if (event === key) {
        _('#calendar_data').classList.toggle('show_data');
        // template info
        var data = '<a href="#" class="hideEvent" '+
            'onclick="return hideEvent();">×</a>'+
            '<h3>' + obj[key].type + '</h3>' +
            '<dl>' +
            '<dt><dfn>Title:</dfn></dt><dd>' + obj[key].title + '</dd>' +
            '<dt><dfn>Hour:</dfn></dt><dd>' + obj[key].time + '</dd>' +
            '<dt><dfn>Venue:</dfn></dt><dd>' + obj[key].venue + '</dd>' +
            '<dt><dfn>Location:</dfn></dt><dd>' + obj[key].location + '</dd>' +
            '<dt><dfn>Description:</dfn></dt><dd>' + obj[key].desc + '</dd>' +
            '<dt><dfn>More Info:</dfn></dt><dd><a href="' + obj[key].more +
            '" title="More info">Here</a></dd>' +
            '</dl>';

        return _('#calendar_data').innerHTML = data;
      }
    }
  });
  return false;
}
// toggle event show or hide
function hideEvent(){
    _('#calendar_data').classList.toggle('show_data');
}
</code>```

答:
I think the problem is that your showInfo() was commented out at the start of the calendar() function. Remove the comment so this:

```<code>// showInfo();
</code>```

Becomes this:

```<code>showInfo();
</code>```

I have updated the Codepen for the original question here so you can see that the events are showing up. I'm not sure what you meant by the 'weekday is not right'.

Body:
On my calendar there are dates that have events. The dates with the events should be highlighted with data received from a JSON call. When I click on an event date the event should be shown. The problem is my JSON data is not being fetched and the events don't show. Also, the weekday isn't right.

My showInfo code that makes the JSON request is below. The Codepen shows the full code example.

 // show info
function showInfo(event) {
  // link
  var url = 'https://codepen.io/nakome/pen/EWBMzm.css';
  // get json
  getjson(url, function(obj) {
    for (var key in obj) {
      // if has envent add class
      if(_('[data-id="' + key + '"]')){
        _('[data-id="' + key + '"]').classList.add('event');
      }
      if (event === key) {
        _('#calendar_data').classList.toggle('show_data');
        // template info
        var data = '×'+
            '
' + obj[key].type + '
' +
            '
' +
            '
<dfn>Title:</dfn>

' + obj[key].title + '
' +
            '
<dfn>Hour:</dfn>

' + obj[key].time + '
' +
            '
<dfn>Venue:</dfn>

' + obj[key].venue + '
' +
            '
<dfn>Location:</dfn>

' + obj[key].location + '
' +
            '
<dfn>Description:</dfn>

' + obj[key].desc + '
' +
            '
<dfn>More Info:</dfn>

Here
' +
            '
';

        return _('#calendar_data').innerHTML = data;
      }
    }
  });
  return false;
}
// toggle event show or hide
function hideEvent(){
    _('#calendar_data').classList.toggle('show_data');
}

Body:
I think the problem is that your showInfo() was commented out at the start of the calendar() function. Remove the comment so this:

// showInfo();

Becomes this:

showInfo();

I have updated the Codepen for the original question here so you can see that the events are showing up. I'm not sure what you meant by the 'weekday is not right'.


问:
How can we generate unique links in angularjs?
I want to generate a unique link for the user when he click on the generate link button.How can I write the onclick function for generating unique links using javascript in angularjs?</p>

答:
You can do something like this to generate random strings and links:</p>

```<code>$scope.randomString = function(length) {
  var chars = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
  var result = '';
  for (var i = length; i > 0; --i) {
    result += chars[Math.floor(Math.random() * chars.length)];
  }
  return result;
}
</code>```

Body:
You can do something like this to generate random strings and links:

$scope.randomString = function(length) {
  var chars = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
  var result = '';
  for (var i = length; i > 0; --i) {
    result += chars[Math.floor(Math.random() * chars.length)];
  }
  return result;
}


问:
What this syntax meaning in Javascript
I am looking for API of TWILIO in javascript , and i found something like

```<code>const { connect, createLocalTracks } = Twilio.Video;

navigator.mediaDevices.enumerateDevices().then(devices => {
  var videoInput = devices.find(device => device.kind === 'videoinput');
  return createLocalTracks({ audio: true, video: { deviceId: videoInput.deviceId } });
}).then(localTracks => {
  return connect('my-token', { name: 'my-room-name', tracks: localTracks });
}).then(room => {
  console.log('Connected to room ' + room.name);
});
</code>```

I could not understand what is the meaning of this code

```<code>const { connect, createLocalTracks } = Twilio.Video;
</code>```

https://www.twilio.com/docs/api/video/configuring-audio-video-inputs-and-outputs

I have seen something same in typescript but not in core js

答:
It's a destructuring assignment. It is equivalent to:

```<code>const connect = Twilio.Video.connect;
const createLocalTracks = Twilio.Video.createLocalTracks;
</code>```

See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment for details, including which browsers support it.

Title: What this syntax meaning in Javascript

Body:
I am looking for API of TWILIO in javascript , and i found something like

const { connect, createLocalTracks } = Twilio.Video;

navigator.mediaDevices.enumerateDevices().then(devices => {
  var videoInput = devices.find(device => device.kind === 'videoinput');
  return createLocalTracks({ audio: true, video: { deviceId: videoInput.deviceId } });
}).then(localTracks => {
  return connect('my-token', { name: 'my-room-name', tracks: localTracks });
}).then(room => {
  console.log('Connected to room ' + room.name);
});

I could not understand what is the meaning of this code

const { connect, createLocalTracks } = Twilio.Video;

https://www.twilio.com/docs/api/video/configuring-audio-video-inputs-and-outputs

I have seen something same in typescript but not in core js

Body:
It's a destructuring assignment. It is equivalent to:

const connect = Twilio.Video.connect;
const createLocalTracks = Twilio.Video.createLocalTracks;

See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment for details, including which browsers support it.


答:
The pattern is object destructuring and assignment, for example

const Twilio = { Video: { connect:1, createLocalTracks:2 } };

const { connect, createLocalTracks } = Twilio.Video;

console.log(connect, createLocalTracks); // 1, 2```

Title: What this syntax meaning in Javascript


问:
Simulating data for a Gompertz curve
I have a set of data that I have collected which consists of a time series, where each y-value is found by taking the mean of 30 samples of grape cluster weight.

The growth follows a Gompertz curve with formula y = a*exp(-exp(-(x-x0)/b)), with

a = 88.8

b = 11.7

x0 = 15.1.

The data:

```<code>x = c(0, 28, 36, 42, 50, 58, 63, 71, 79, 85, 92, 99, 106, 112)
y = c(0, 15, 35, 55, 62, 74, 80, 96, 127, 120, 146, 160, 177, 165).
</code>```

x refers to the days from fruit set (i.e. 0 is when the time series starts)

x values correspond to the days in which the measurements are taken (which depends on certain growth stages of grapes)

I want to simulate more data from this, with the same number of x and y values, so that I can carry out some Bayesian analysis to find the posterior distribution of the data.

Effectively what I need is:

to simulate data which follows the Gompertz curve to create the posterior distribution. This data would technically be for "previous years" time series data.

to construct and test the fit of the predictive time-series model based on the distribution

If there is some skeleton code where it is possible to change around the parameters, then this could potentially be very helpful for me too.

Thanks

答:
Let's inspect your data

```<code>x <- c(0, 28, 36, 42, 50, 58, 63, 71, 79, 85, 92, 99, 106, 112)
y <- c(0, 15, 35, 55, 62, 74, 80, 96, 127, 120, 146, 160, 177, 165)
</code>```

and fitted Gompertz curve

```<code>gFun <- function(x){
 a <- 88.8
 b <- 11.7
 x0 <- 15.1
 est <- a*exp(-exp(-(x-x0)/b))
  return(est)
}
</code>```

by visualisation:

```<code>library(ggplot2)
 ggplot(ggData, aes(x=x, y=y) ) +
  geom_point() +
  stat_function(fun=gFun, colour="blue") +
  theme_bw()
</code>```

This doesn't look as a good fit. However, simulating data y|x at fixed x as in the vector above can be done by adding error term. I've used normal distribution with sd=4 for illustration.

```<code>nSim <- 10

simData <- data.frame(x=c(0, rep(x[-1], each=nSim)) ) # x[-1] removes 0 from simulation
simData$y <- gFun(simData$x) + rnorm(n=nrow(simData), sd=4)

ggplot(simData, aes(x=x, y=y) ) +
 geom_point(alpha=0.4) +
 stat_function(fun=gFun, colour="blue") +
 scale_x_continuous(limits=c(0, max(x)) ) +
 theme_bw()
</code>```

Title: Simulating data for a Gompertz curve

Body:
I have a set of data that I have collected which consists of a time series, where each y-value is found by taking the mean of 30 samples of grape cluster weight.

The growth follows a Gompertz curve with formula y = a*exp(-exp(-(x-x0)/b)), with

a = 88.8

b = 11.7

x0 = 15.1.

The data:

x = c(0, 28, 36, 42, 50, 58, 63, 71, 79, 85, 92, 99, 106, 112)
y = c(0, 15, 35, 55, 62, 74, 80, 96, 127, 120, 146, 160, 177, 165).

x refers to the days from fruit set (i.e. 0 is when the time series starts)

x values correspond to the days in which the measurements are taken (which depends on certain growth stages of grapes)

I want to simulate more data from this, with the same number of x and y values, so that I can carry out some Bayesian analysis to find the posterior distribution of the data.

Effectively what I need is:

to simulate data which follows the Gompertz curve to create the posterior distribution. This data would technically be for "previous years" time series data.

to construct and test the fit of the predictive time-series model based on the distribution

If there is some skeleton code where it is possible to change around the parameters, then this could potentially be very helpful for me too.

Thanks

Body:
Let's inspect your data

x <- c(0, 28, 36, 42, 50, 58, 63, 71, 79, 85, 92, 99, 106, 112)
y <- c(0, 15, 35, 55, 62, 74, 80, 96, 127, 120, 146, 160, 177, 165)

and fitted Gompertz curve

gFun <- function(x){
 a <- 88.8
 b <- 11.7
 x0 <- 15.1
 est <- a*exp(-exp(-(x-x0)/b))
  return(est)
}

by visualisation:

library(ggplot2)
 ggplot(ggData, aes(x=x, y=y) ) +
  geom_point() +
  stat_function(fun=gFun, colour="blue") +
  theme_bw()

This doesn't look as a good fit. However, simulating data y|x at fixed x as in the vector above can be done by adding error term. I've used normal distribution with sd=4 for illustration.

nSim <- 10

simData <- data.frame(x=c(0, rep(x[-1], each=nSim)) ) # x[-1] removes 0 from simulation
simData$y <- gFun(simData$x) + rnorm(n=nrow(simData), sd=4)

ggplot(simData, aes(x=x, y=y) ) +
 geom_point(alpha=0.4) +
 stat_function(fun=gFun, colour="blue") +
 scale_x_continuous(limits=c(0, max(x)) ) +
 theme_bw()


问:
Abort Trap: 6 error in the new Swift 3.1/Xcode 8.3
I have a finished project with about 30vcs, Firebase, Googlemaps integration, etc - ie a really big complicated project, it is a geolocation based game that I've finally finished after several months of work.

Worked and compiled just fine, until I tried to compile it in the new Swift 3.1/ Xcode 8.3.

After changing the recommended syntax on a few lines to clear the new XCODE 8.3 errors, compiling fails with "Abort Trap: 6" error.

This is the last few lines of the debugger (prior to that theres about 100 lines of incomprehensible file names/numbers etc).

0  swift                    0x00000001089f1eb7
  PrintStackTraceSignalHandler(void*) + 39 1  swift

  0x00000001089f1366 SignalHandler(int) + 646 2
  libsystem_platform.dylib 0x00007fffc602eb3a _sigtramp + 26 3
  libsystem_platform.dylib 0x0000000100000001 _sigtramp + 972887265 4
  libsystem_c.dylib        0x00007fffc5eb3420 abort + 129 5  swift

  0x0000000106454644
  swift::ModuleFile::getDecl(llvm::PointerEmbeddedInt,
  llvm::Optional) + 38404 6  swift

  0x00000001064564fa
  swift::ModuleFile::getType(llvm::PointerEmbeddedInt)
  + 2106 7  swift                    0x000000010644f373 swift::ModuleFile::getDecl(llvm::PointerEmbeddedInt,
  llvm::Optional) + 17203 8  swift

  0x0000000106459f24
  swift::ModuleFile::maybeReadPattern(swift::DeclContext*) + 740 9
  swift                    0x000000010644f605
  swift::ModuleFile::getDecl(llvm::PointerEmbeddedInt,
  llvm::Optional) + 17861 10 swift

  0x00000001064607c8 swift::ModuleFile::loadAllMembers(swift::Decl*,
  unsigned long long) + 600 11 swift

  0x0000000106840f0d swift::NominalTypeDecl::getMembers() const + 125 12
  swift                    0x0000000106828c75 (anonymous
  namespace)::Traversal::visitNominalTypeDecl(swift::NominalTypeDecl*) +
  869 13 swift                    0x0000000106826645 (anonymous
  namespace)::Traversal::doIt(swift::Decl*) + 277 14 swift

  0x000000010619a75f
  swift::SILPassManager::SILPassManager(swift::SILModule*,
  llvm::StringRef) + 1471 15 swift                    0x00000001061a135f
  swift::runSILDiagnosticPasses(swift::SILModule&) + 159 16 swift

  0x0000000105811282 swift::performFrontend(llvm::ArrayRef,
  char const*, void*, swift::FrontendObserver*) + 42866 17 swift

  0x00000001057c088c main + 9052 18 libdyld.dylib

  0x00007fffc5e1f235 start + 1 Stack dump:

(here is about 150 lines of incomprehensible debugging numbers/files/alphanumericals - followed by this in the end):

While loading members for 'homePage' in module 'googleMapsPractice'

While deserializing PatternBindingDecl #295in 'googleMapsPractice'

While deserializing 'gameDBRef' (VarDecl #296)in 'googleMapsPractice'

While deserializing decl #1009 (XREF)in 'googleMapsPractice'

Cross-reference to module 'FirebaseDatabase'    ... FIRDatabaseReference

I am really stuck as I don't know where to look to debug this.

'homePage.swift' is the set-up page VC of the game, and is the only VC referenced in the debugger, is there any common solutions to Abort Trap 6 errors that I could try weed out on this VC? It is probably 2000 lines of code and i'm not even sure the problem lies in that VC as the debugger is so vague.

Any help would be greatly appreciated

答: I have run into the same problem. I finally figured out that it was caused by overriding 'var description' on any class that inherits from NSObject. I note that in Swift 3.1 there is a 'class func description()' on NSObject that I don't necessarily recall being in Swift 3.0 (although I could easily be mistaken in this assumption; I've never had any to look for or use it). See also https://forums.developer.apple.com/thread/75700</p>


问:
How do I check when a UITextField changes?
I am trying to check when a text field changes, equivalent too the function used for textView - textViewDidChange so far I have done this:

```<code>  func textFieldDidBeginEditing(textField: UITextField) {
        if self.status.text == "" && self.username.text == "" {
            self.topRightButton.enabled = false
        } else {
            self.topRightButton.enabled = true
        }
    }
</code>```

Which kind of works, but the topRightButton is enabled as soon as the text field is pressed on, I want it to be enabled only when text is actually typed in?

答:
Maybe use RxSwift ?

need

```<code>pod 'RxSwift',    '~> 3.0'
pod 'RxCocoa',    '~> 3.0'
</code>```

add imports obviously

```<code>import RxSwift
import RxCocoa
</code>```

So u have a textfield : UITextField

```<code>let observable: Observable<String?> = textField.rx.text.asObservable()
observable.subscribe(
            onNext: {(string: String?) in
                print(string!)
        })
</code>```

U have other 3 methods..

onError

onCompleted

onDisposed

onNext

Body:
I am trying to check when a text field changes, equivalent too the function used for textView - textViewDidChange so far I have done this:

  func textFieldDidBeginEditing(textField: UITextField) {
        if self.status.text == "" && self.username.text == "" {
            self.topRightButton.enabled = false
        } else {
            self.topRightButton.enabled = true
        }
    }

Which kind of works, but the topRightButton is enabled as soon as the text field is pressed on, I want it to be enabled only when text is actually typed in?

Body:
Maybe use RxSwift ?

need

pod 'RxSwift',    '~> 3.0'
pod 'RxCocoa',    '~> 3.0'

add imports obviously

import RxSwift
import RxCocoa

So u have a textfield : UITextField

let observable: Observable<String?> = textField.rx.text.asObservable()
observable.subscribe(
            onNext: {(string: String?) in
                print(string!)
        })

U have other 3 methods..

onError

onCompleted

onDisposed

onNext