问:
Ext.Ajax.request vs model.save cross origin cookies
I'm having an issue with model.save not sending the cookies back with my cross origin request, but Ext.Ajax.request has no issue sending back the cookies.  In our local development at work, we override the beforerequest on all Ajax requests (which includes model actions) to set withCredentials = true and useDefaultXhrHeader = false, which helps with CORS on a normal Ext.Ajax.request.

From what I understand, having a proxy of type ajax is similar to doing Ext.Ajax.request, and that's apparent because model.save hits the beforerequest (you'll see this in the example below).  You'll also notice in the example that the model.save sends an OPTIONS call first, and then never follows up with the POST (but that's most likely because of the server)... either way, OPTIONS instead of POST seems a little fishy.

Here's the example:

```<code>Ext.Ajax.on({
    beforerequest: function (conn, options, eOpts) {
        console.log('here', conn, options)
        options.useDefaultXhrHeader = false;
        options.withCredentials = true;
    }
});
Ext.define('MyModel', {
    extend: 'Ext.data.Model',
    fields: ['test'],
    proxy: {
        type: 'ajax',
        url: 'https://docs.sencha.com'
    }
});
var model = Ext.create('MyModel');
// This will fire off an OPTIONS call and not send the cookies
model.save();
// This will fire off with the POST and send the cookies
Ext.Ajax.request({
    url: 'https://docs.sencha.com',
    method: 'POST'
});
</code>```

Is there any way to get model.save to send the cookies to the cross domain?

答:
No, you can't get around the OPTIONS request.

The browser will start sending an OPTIONS request once you add a payload to the POST request, like model.save() does. This also happens to your Ext.Ajax.request operation if you change it slightly to match the model.save operation:

```<code>// This will fire off an OPTIONS request.
Ext.Ajax.request({
    url: 'https://docs.sencha.com',
    method: 'POST',
    jsonData: {id: "MyModel-1"}
});
</code>```

This OPTIONS request is a so-called "preflight request" intended to get the information from the server whether the server is allowing the actual cross-origin request. The server has to answer that positively, including Http Response Headers containing a set of CORS headers. docs.sencha.com does indeed answer the OPTIONS request, but it does not return the required headers, so you find an error message in the browser console:

XMLHttpRequest cannot load https://docs.sencha.com/?_dc=1499412133932. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'https://fiddle.sencha.com' is therefore not allowed access.

As a counter-example, my CORS-enabled backend sends to the client the following headers:

```<code>Access-Control-Allow-Origin: *
Access-Control-Allow-Methods: GET, POST, PATCH, PUT, DELETE, OPTIONS
Access-Control-Allow-Headers: Origin, Content-Type, X-Auth-Token, X-Requested-With
</code>```

Origin contains all domains from which CORS requests may be sent, or * for all domains.

Methods contains all allowed methods, you will need at least OPTIONS, POST.

Headers contains all headers that your request may send to the server. Chrome console will tell you if you are missing one the browser expects; at least that's how I got to my list.

If these conditions are met on an OPTIONS request, the actual POST request will be sent; otherwise, you will find said error message in the browser console.

Body:
I'm having an issue with model.save not sending the cookies back with my cross origin request, but Ext.Ajax.request has no issue sending back the cookies.  In our local development at work, we override the beforerequest on all Ajax requests (which includes model actions) to set withCredentials = true and useDefaultXhrHeader = false, which helps with CORS on a normal Ext.Ajax.request.

From what I understand, having a proxy of type ajax is similar to doing Ext.Ajax.request, and that's apparent because model.save hits the beforerequest (you'll see this in the example below).  You'll also notice in the example that the model.save sends an OPTIONS call first, and then never follows up with the POST (but that's most likely because of the server)... either way, OPTIONS instead of POST seems a little fishy.

Here's the example:

Ext.Ajax.on({
    beforerequest: function (conn, options, eOpts) {
        console.log('here', conn, options)
        options.useDefaultXhrHeader = false;
        options.withCredentials = true;
    }
});
Ext.define('MyModel', {
    extend: 'Ext.data.Model',
    fields: ['test'],
    proxy: {
        type: 'ajax',
        url: 'https://docs.sencha.com'
    }
});
var model = Ext.create('MyModel');
// This will fire off an OPTIONS call and not send the cookies
model.save();
// This will fire off with the POST and send the cookies
Ext.Ajax.request({
    url: 'https://docs.sencha.com',
    method: 'POST'
});

Is there any way to get model.save to send the cookies to the cross domain?

Body:
No, you can't get around the OPTIONS request.

The browser will start sending an OPTIONS request once you add a payload to the POST request, like model.save() does. This also happens to your Ext.Ajax.request operation if you change it slightly to match the model.save operation:

// This will fire off an OPTIONS request.
Ext.Ajax.request({
    url: 'https://docs.sencha.com',
    method: 'POST',
    jsonData: {id: "MyModel-1"}
});

This OPTIONS request is a so-called "preflight request" intended to get the information from the server whether the server is allowing the actual cross-origin request. The server has to answer that positively, including Http Response Headers containing a set of CORS headers. docs.sencha.com does indeed answer the OPTIONS request, but it does not return the required headers, so you find an error message in the browser console:

XMLHttpRequest cannot load https://docs.sencha.com/?_dc=1499412133932. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'https://fiddle.sencha.com' is therefore not allowed access.

As a counter-example, my CORS-enabled backend sends to the client the following headers:

Access-Control-Allow-Origin: *
Access-Control-Allow-Methods: GET, POST, PATCH, PUT, DELETE, OPTIONS
Access-Control-Allow-Headers: Origin, Content-Type, X-Auth-Token, X-Requested-With

Origin contains all domains from which CORS requests may be sent, or * for all domains.

Methods contains all allowed methods, you will need at least OPTIONS, POST.

Headers contains all headers that your request may send to the server. Chrome console will tell you if you are missing one the browser expects; at least that's how I got to my list.

If these conditions are met on an OPTIONS request, the actual POST request will be sent; otherwise, you will find said error message in the browser console.


来源: stackexchange

问:
How Spark handle data larger than cluster memory
If I have only 1 executor with memory 25 GB and if it can run only one task at a time then is it possible to process(transformation and action) 1 TB data if Yes then how it will be read and where intermediate data will be store ?

Also for the same scenario if hadoop file is having 300 input split then there will be 300 partitions in RDD so in this case where will be those partitions ?
will it remain on hadoop disk only and my single task will be run 300 times ?

答:
I find a good answer on hortonworks website.

Contrary to popular believe Spark is not in-memory only

a) Simple read no shuffle ( no joins, ... )

For the initial reads Spark like MapReduce reads the data in a stream and > processes it as it comes along. I.e. unless there is a reason spark will NOT materialize the full RDDs in memory ( you can tell him to do it however if you want to cache a small dataset ) An RDD is resilient because spark knows how to recreate it ( re read a block from hdfs for example ) not because its stored in mem in different locations. ( that can be done too though. )

So if you filter out most of your data or do an efficient aggregation that aggregates on the map side you will never have the full table in memory.

b) Shuffle

This is done very similarly to MapReduce as it writes the map outputs to disc and reads them with the reducers through http. However spark uses an aggressive filesystem buffer strategy on the Linux filesystem so if the OS has memory available the data will not be actually written to physical disc.

c) After Shuffle

RDDs after shuffle are normally cached by the engine ( otherwise a failed node or RDD would require a complete re run of the job ) however as abdelkrim mentions Spark can spill these to disc unless you overrule that.

d) Spark Streaming

This is a bit different. Spark streaming expects all data to fit in memory unless you overwrite settings.

Here's is the original page.

And the initial Spark's design dissertation by Matei Zaharia also helps. (section 2.6.4 Behavior with Insufficient Memory)

Wish there is something useful.

ContentLicense: CC BY-SA 3.0


问:
Not able to align imageview with respect to relative layout
Following is the screen I am trying to design and I am using CoordinatorLayout
but not able to align my image along with RelativeLayout the way its shown in the screenshot.

following is my code

```<code><android.support.design.widget.CoordinatorLayout
        android:id="@+id/layoutDocumentVerification"
        android:layout_below="@+id/layoutTitles"
        android:layout_marginTop="16dp"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <RelativeLayout
            android:id="@+id/layoutContent"
            android:background="@drawable/drawable_rectangle_white_grey_border"
            android:padding="10dp"
            android:layout_width="match_parent"
            android:layout_height="wrap_content">

            <ImageView
                android:id="@+id/imgDocVerification"
                android:layout_marginRight="10dp"
                app:srcCompat="@drawable/ic_document_verification"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content" />

            <com.widgets.TextViewRobotoRegular
                android:id="@+id/lblDocVerify"
                android:layout_toRightOf="@+id/imgDocVerification"
                android:text="Document Verification"
                android:textSize="14sp"
                android:textColor="@color/ekyc_black"
                android:layout_marginTop="10dp"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content" />

            <com.widgets.TextViewRobotoLight
                android:id="@+id/lblUploadDoc"
                android:layout_toRightOf="@+id/imgDocVerification"
                android:layout_below="@+id/lblDocVerify"
                android:text="Please upload your documents"
                android:textSize="13sp"
                android:layout_marginTop="8dp"
                android:textColor="@color/ekyc_light_gray"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content" />

            <com.widgets.TextViewRobotoBold
                android:id="@+id/lblKnowMore"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_toRightOf="@+id/imgDocVerification"
                android:layout_below="@+id/lblUploadDoc"
                android:layout_marginTop="8dp"
                android:layout_marginBottom="16dp"
                android:text="@string/know_more_about_sips"
                android:textColor="@color/color_view_history"
                android:textSize="13sp" />

        </RelativeLayout>

        <ImageView
            android:id="@+id/imgExpand"
            android:src="@drawable/ic_crm_accepted"
            app:layout_anchor="@id/layoutContent"
            app:layout_anchorGravity="center|bottom"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" />

    </android.support.design.widget.CoordinatorLayout>
</code>```

Problem occuring to me is dropdown image not getting placed to the center of the horizontal line, but getting placed above that line. please help

答:
This is a solution for your problem. Instead of use Coordinator with nested Relative Layout, I use LinearLayout with nested FrameLayout and LinearLayout

This is the layout xml

```<code><LinearLayout android:id="@+id/layoutDocumentVerification"
android:layout_below="@+id/layoutTitles"
android:layout_marginTop="16dp"
android:layout_width="match_parent"
android:layout_height="wrap_content"
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal">

<FrameLayout
    android:layout_width="wrap_content"
    android:layout_height="match_parent"
    android:layout_marginLeft="16dp"
    android:layout_marginRight="16dp">

    <ImageView
        android:id="@+id/imgExpand"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:padding="5dp"
        android:src="@drawable/ic_crm_accepted"/>
</FrameLayout>

<LinearLayout
    android:id="@+id/layoutContent"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <ImageView
        android:id="@+id/imgDocVerification"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

    <TextView
        android:id="@+id/lblDocVerify"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginBottom="8dp"
        android:text="Document Verification"
        android:textSize="14sp"
        android:textColor="@android:color/black"/>

    <TextView
        android:id="@+id/lblUploadDoc"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginBottom="8dp"
        android:text="Please upload your documents"
        android:textSize="13sp"
        android:textColor="@android:color/darker_gray"/>

    <TextView
        android:id="@+id/lblKnowMore"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Know more"
        android:textAllCaps="true"
        android:textStyle="bold"
        android:textColor="@android:color/holo_orange_dark"
        android:textSize="13sp" />
</LinearLayout>
</code>```

If you need a TextView with custom font, you should set fontFamily attribute in your custom theme.

Body:
Following is the screen I am trying to design and I am using CoordinatorLayout
but not able to align my image along with RelativeLayout the way its shown in the screenshot.

following is my code

<android.support.design.widget.CoordinatorLayout
        android:id="@+id/layoutDocumentVerification"
        android:layout_below="@+id/layoutTitles"
        android:layout_marginTop="16dp"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <RelativeLayout
            android:id="@+id/layoutContent"
            android:background="@drawable/drawable_rectangle_white_grey_border"
            android:padding="10dp"
            android:layout_width="match_parent"
            android:layout_height="wrap_content">

            <ImageView
                android:id="@+id/imgDocVerification"
                android:layout_marginRight="10dp"
                app:srcCompat="@drawable/ic_document_verification"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content" />

            <com.widgets.TextViewRobotoRegular
                android:id="@+id/lblDocVerify"
                android:layout_toRightOf="@+id/imgDocVerification"
                android:text="Document Verification"
                android:textSize="14sp"
                android:textColor="@color/ekyc_black"
                android:layout_marginTop="10dp"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content" />

            <com.widgets.TextViewRobotoLight
                android:id="@+id/lblUploadDoc"
                android:layout_toRightOf="@+id/imgDocVerification"
                android:layout_below="@+id/lblDocVerify"
                android:text="Please upload your documents"
                android:textSize="13sp"
                android:layout_marginTop="8dp"
                android:textColor="@color/ekyc_light_gray"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content" />

            <com.widgets.TextViewRobotoBold
                android:id="@+id/lblKnowMore"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_toRightOf="@+id/imgDocVerification"
                android:layout_below="@+id/lblUploadDoc"
                android:layout_marginTop="8dp"
                android:layout_marginBottom="16dp"
                android:text="@string/know_more_about_sips"
                android:textColor="@color/color_view_history"
                android:textSize="13sp" />

        </RelativeLayout>

        <ImageView
            android:id="@+id/imgExpand"
            android:src="@drawable/ic_crm_accepted"
            app:layout_anchor="@id/layoutContent"
            app:layout_anchorGravity="center|bottom"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" />

    </android.support.design.widget.CoordinatorLayout>

Problem occuring to me is dropdown image not getting placed to the center of the horizontal line, but getting placed above that line. please help

Body:
This is a solution for your problem. Instead of use Coordinator with nested Relative Layout, I use LinearLayout with nested FrameLayout and LinearLayout

This is the layout xml

<LinearLayout android:id="@+id/layoutDocumentVerification"
android:layout_below="@+id/layoutTitles"
android:layout_marginTop="16dp"
android:layout_width="match_parent"
android:layout_height="wrap_content"
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal">

<FrameLayout
    android:layout_width="wrap_content"
    android:layout_height="match_parent"
    android:layout_marginLeft="16dp"
    android:layout_marginRight="16dp">

    <ImageView
        android:id="@+id/imgExpand"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:padding="5dp"
        android:src="@drawable/ic_crm_accepted"/>
</FrameLayout>

<LinearLayout
    android:id="@+id/layoutContent"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <ImageView
        android:id="@+id/imgDocVerification"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

    <TextView
        android:id="@+id/lblDocVerify"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginBottom="8dp"
        android:text="Document Verification"
        android:textSize="14sp"
        android:textColor="@android:color/black"/>

    <TextView
        android:id="@+id/lblUploadDoc"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginBottom="8dp"
        android:text="Please upload your documents"
        android:textSize="13sp"
        android:textColor="@android:color/darker_gray"/>

    <TextView
        android:id="@+id/lblKnowMore"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Know more"
        android:textAllCaps="true"
        android:textStyle="bold"
        android:textColor="@android:color/holo_orange_dark"
        android:textSize="13sp" />
</LinearLayout>

If you need a TextView with custom font, you should set fontFamily attribute in your custom theme.


问:
My excel export does not bring me the styles of my table
I have a table where I paint cell I also have filters and I have a header with style. Now when I want to export to excel it does not do it with the style of my table, does anyone know how to do it?

In advance I thank you for the help!

答:
You can use excelExport event to manually change color of your cells.

Example:

```<code>excelExport: function(e) {
      var sheet = e.workbook.sheets[0];
      for (var rowIndex = 1; rowIndex < sheet.rows.length; rowIndex++) {
        if (rowIndex % 2 == 0) {
          var row = sheet.rows[rowIndex];
          for (var cellIndex = 0; cellIndex < row.cells.length; cellIndex ++) {
            row.cells[cellIndex].background = "#aabbcc";
          }
        }
      }
</code>```

Body:
You can use excelExport event to manually change color of your cells.

Example:

excelExport: function(e) {
      var sheet = e.workbook.sheets[0];
      for (var rowIndex = 1; rowIndex < sheet.rows.length; rowIndex++) {
        if (rowIndex % 2 == 0) {
          var row = sheet.rows[rowIndex];
          for (var cellIndex = 0; cellIndex < row.cells.length; cellIndex ++) {
            row.cells[cellIndex].background = "#aabbcc";
          }
        }
      }


问:
How to deal with different amount of inputs that user will choose in a windows form?
I'm trying to make a database application with C# and an Excel file. I got three tables 'Person', 'City' and 'District'. Each one is a class and they have 5, 2 and 3 properties respectively.

In Form1, I got a data grid view and I want to user to choose which table he/she want to do something(insert, update ect.), but my tables have a different amount of properties, so I need a different amount of textboxes depends on user's choice. (For City I need 3; for Person, I need 5). Also, I'm making this project by three-layered architecture so I have some constraints to deal with problems.

I've started to do this by user control but I'm really stuck. Can anybody explain widely how to deal with it? Thank you.

答:
You can use a List of controls for each option.
When you choose to manage table 1, you clear a panel, and for each needed value you create a new control(text box or combo box or...) and you give each control a location and a size and add it to a List of controls.
When submitting you loop over the list knowing that list(0) is username for example</p>


问:
Problem resizing image using Code Ignitor1.7.3
Following is the code which resize the image, but here i am not able to resize the image</p>

```<code>function processHome(){
    $this->load->library('image_lib');

    $img_path =  base_url().'img/image/50X50/ori.jpeg';

    $config['image_library'] = 'gd2';
    $config['source_image'] = $img_path;
    $config['create_thumb'] = TRUE;
    $config['maintain_ratio'] = TRUE;
    $config['width'] = 50;
    $config['height'] = 50;

    $this->load->library('image_lib', $config);
    $this->image_lib->resize();

    if ( ! $this->image_lib->resize()){
        echo $this->image_lib->display_errors();
    }

    echo "No error";
    exit;

    $this->load->view('index', $data);
}
</code>```

答:
For a start, remove the

```<code>$this->load->library('image_lib');
</code>```

at the beginning - you only need to load the library once, and only after you set the parameters.

Then, give the relative/server path to your image folder, instead of the url - as in, no base_url().

Finally, check the permissions for the folder the image is in - it must be readable/writable by all, and php should be allowed to create new files.

I guess that's all.

ContentLicense: CC BY-SA 2.5

Body:
Following is the code which resize the image, but here i am not able to resize the image

function processHome(){
    $this->load->library('image_lib');

    $img_path =  base_url().'img/image/50X50/ori.jpeg';

    $config['image_library'] = 'gd2';
    $config['source_image'] = $img_path;
    $config['create_thumb'] = TRUE;
    $config['maintain_ratio'] = TRUE;
    $config['width'] = 50;
    $config['height'] = 50;

    $this->load->library('image_lib', $config);
    $this->image_lib->resize();

    if ( ! $this->image_lib->resize()){
        echo $this->image_lib->display_errors();
    }

    echo "No error";
    exit;

    $this->load->view('index', $data);
}

Body:
For a start, remove the

$this->load->library('image_lib');

at the beginning - you only need to load the library once, and only after you set the parameters.

Then, give the relative/server path to your image folder, instead of the url - as in, no base_url().

Finally, check the permissions for the folder the image is in - it must be readable/writable by all, and php should be allowed to create new files.

I guess that's all.


问:
Can I use react or CSS to target a specific component to change onclick?
I'm trying to have a navbar that when a link on it is clicked, it renders the new component into the component B box in the picture and nowhere else on the screen (aka everything else stays the same). Do I need react router for this or can I do this using straight up React and CSS?

Aka I click link 1, or link 2 or link 3 and the result shows up in Component box B.

答:
Do I need react router for this or can I do this using straight up
  React and CSS?

You could do it w/o react-router by making some statefull component that uses links to change its path and selecting component to render based on this path. In the end react-router is using React.

```<code>handleLinkClick(e, path) {
  ev.preventDefault()
  this.setState({path})
}

renderBComponent() {
   const { path } = this.state;

   const ComponentToRender = {path1: ComponentB1, path2: ComponentB2, etc}
   return <ComponentToRender />
}
</code>```

But you'd better use react-router :) to avoid reinventing the wheel.

Body:
Do I need react router for this or can I do this using straight up
  React and CSS?

You could do it w/o react-router by making some statefull component that uses links to change its path and selecting component to render based on this path. In the end react-router is using React.

handleLinkClick(e, path) {
  ev.preventDefault()
  this.setState({path})
}

renderBComponent() {
   const { path } = this.state;

   const ComponentToRender = {path1: ComponentB1, path2: ComponentB2, etc}
   return <ComponentToRender />
}

But you'd better use react-router :) to avoid reinventing the wheel.


问:
Asp.net website on AWS ec2 t2 medium
We have an asp.net application currently running on a shared hosting provider.
The application specifications are

.NET 4.5 Web forms webiste.

1 MSSQL data base of size - 100 MB

Web Application size including images -  1.2GB

Page visits/day - ~2500

Bandwidth consumed/day - ~200MB

We are not happy with the Hosting providers and have faced a lot of issues recently. Our application requires trust level as full for some of the services and the hosting provider is unwilling to set the trust of the application as full.

Statistics obtained(1 week) from the hosting provider(See image below)

(We have around 2500 page visits a day on week days and 500 page visits on weekends)

Based on the above information, we are planning to move to AWS. I was thinking to go with a t2 medium reserved windows instance(It has 2 cores and 4 gb ram) and EBS storage(Will cost us around 50 USD a month)

Since we have a small database when compared to enterprise standards, I was thinking to host it in the same instance. We are also planning to go with Sequel server express as this does not need licensing rights.

I have read up a lot of documentation and I am not able to reach a conclusion about the size of the instance to go for and will the t2 medium EC2 instance be able to serve my purpose?

1. It would be great if anyone can tell me if the above t2 medium ec2 infrastructure will suit our needs?

2. Do I need a t2 medium instance or can I go for a lower level
    configuration ?

Open to suggestions on change of above mentioned infrastructure as well.

答:
Instead of quoting page visits, etc, you are better off showing RAM and CPU utilisation.

A couple of things to consider:

1 - The t instance is a burstable throughput CPU. That means you gain 'credits' when your CPU is not being used, and when you use it (I cant remember exactly but possibly >10%?) you use up credits. This means if your average workload is either very low, or very bursty, the t series is a good choice, but if your workload is quite constant and high, it is a very bad choice.

2 - How static is the website? You might see benefit in decoupling the database onto an RDS instance that matches your needs, and then having the website on a spot instance to reduce cost, for example.

3 - With respect to configuration requirements, only you can answer this.

Title: Asp.net website on AWS ec2 t2 medium


问:
Counter on Button “Save”
Hello everyone i need help guys)... i wanna make a button "snapShotButton" with counter when i press on button 3 times, i want to make a alert where write"you need to pay for use this app". And when i press "ok" he will pay with MKStoreKit... I have MKStoreKit and my app is Video Editor... Thanks for help best regards!!

func addButtons() {

let snapShotButton = UIButton(type: .system)
        snapShotButton.setImage(#imageLiteral(resourceName: "snapShot").withRenderingMode(.alwaysOriginal), for: .normal)
        snapShotButton.translatesAutoresizingMaskIntoConstraints = false
        bottomTabBar.addSubview(snapShotButton)
        snapShotButton.centerYAnchor.constraint(equalTo: bottomTabBar.centerYAnchor).isActive = true
        snapShotButton.centerXAnchor.constraint(equalTo: bottomTabBar.centerXAnchor).isActive = true
        snapShotButton.heightAnchor.constraint(equalToConstant: 32).isActive = true
        snapShotButton.widthAnchor.constraint(equalToConstant: 32).isActive = true
        snapShotButton.addTarget(self, action: #selector(snapShotButtonTapped), for: .touchUpInside)
        snapShotButton.addTarget(self, action: #selector(counterAction), for: .touchUpInside)
    }

func counterAction(sender:UIButton){

        counter -= 1
        print(counter)

        if counter == 0 {
        MKStoreKit.shared().initiatePaymentRequestForProduct(withIdentifier: "com.steinlogic.iapdemo.quarterly")
        }
    }

    func snapShotButtonTapped() {
        pauseVideo()
        PHPhotoLibrary.shared().performChanges({
            PHAssetChangeRequest.creationRequestForAssetFromVideo(atFileURL: self.videoURL)
        }) { saved, error in
            if saved {
                DispatchQueue.main.async { _ in
                    self.dismiss(animated: true, completion: nil)
                }
            }
            else {
                self.alertErrors()
            }
        }
        //alertNotAvailable()
    }```

答: You should save the counter's value in UserDefaults and retreive it after every app start. After the payment has happened, you can skip the counter decrementation alltogether.

Title: Counter on Button “Save”


问:
ricfaces xhtml edit problem for jetty
I am using Richfaces with facelets (xhtml). I use maven jetty plugin for development.

When jetty is running, I modify a xhtml file but the change does not work until I restart jetty.

Here is my maven jetty plugin configuration:

```<code><plugin>
                <groupId>org.mortbay.jetty</groupId>
                <artifactId>maven-jetty-plugin</artifactId>
                <version>6.1.9</version>
                <configuration>
                    <jettyEnvXml>${basedir}/src/test/resources/${jetty-env-file}</jettyEnvXml>
                    <webDefaultXml>${basedir}/src/test/resources/webdefault.xml</webDefaultXml>
                </configuration>
</plugin>
</code>```

When I edit css, jsp or html files I can see the changes without restarting.

But for xhtml files in every change I need to restart jetty again and again.

Is there any solution for that?

Thanks

答:
In case the above link ever disappears, in web.xml of your faces application do add this:

```<code><context-param>
    <param-name>facelets.DEVELOPMENT</param-name>
    <param-value>true</param-value>
</context-param>
<context-param>
    <param-name>facelets.REFRESH_PERIOD</param-name>
    <param-value>1</param-value>
</context-param>
</code>```

Title: ricfaces xhtml edit problem for jetty

Body:
I am using Richfaces with facelets (xhtml). I use maven jetty plugin for development.

When jetty is running, I modify a xhtml file but the change does not work until I restart jetty.

Here is my maven jetty plugin configuration:

<plugin>
                <groupId>org.mortbay.jetty</groupId>
                <artifactId>maven-jetty-plugin</artifactId>
                <version>6.1.9</version>
                <configuration>
                    <jettyEnvXml>${basedir}/src/test/resources/${jetty-env-file}</jettyEnvXml>
                    <webDefaultXml>${basedir}/src/test/resources/webdefault.xml</webDefaultXml>
                </configuration>
</plugin>

When I edit css, jsp or html files I can see the changes without restarting.

But for xhtml files in every change I need to restart jetty again and again.

Is there any solution for that?

Thanks

Body:
In case the above link ever disappears, in web.xml of your faces application do add this:

<context-param>
    <param-name>facelets.DEVELOPMENT</param-name>
    <param-value>true</param-value>
</context-param>
<context-param>
    <param-name>facelets.REFRESH_PERIOD</param-name>
    <param-value>1</param-value>
</context-param>


问:
Androids Facebook SDK, single sign on question?
On Androids Facebook SDK there is a single login feature which I can't get to work.
Done all the key hash thing but maybe there is something wrong with this method.
What exactly should I pass on, or could somebody explain what this is supposed to do?

@Override

protected void onActivityResult(int requestCode, int resultCode, Intent data) {
facebook.authorizeCallback(requestCode, resultCode, data);
}

答:
Facebook Single Sign On works fine, but the documentation is not all that great. Get your class to override the Facebook DialogListener.

To request Single Sign On, make sure you're calling Facebook to authorize your app -

```<code> facebookClient = new Facebook(FB_APP_ID);

        facebookClient.authorize(this,
            new String[] {"publish_stream", "read_stream", "offline_access"}, this);
</code>```

And you also need to override the OnComplete method. Your OnActivityResult method is absolutely fine.

I used the code given by this gentleman here, and it worked perfectly fine for me, except that some of the code that he'd written was using the old API, so you might need to change some parameters passed to methods.

Body:
Facebook Single Sign On works fine, but the documentation is not all that great. Get your class to override the Facebook DialogListener.

To request Single Sign On, make sure you're calling Facebook to authorize your app -

 facebookClient = new Facebook(FB_APP_ID);

        facebookClient.authorize(this,
            new String[] {"publish_stream", "read_stream", "offline_access"}, this);

And you also need to override the OnComplete method. Your OnActivityResult method is absolutely fine.

I used the code given by this gentleman here, and it worked perfectly fine for me, except that some of the code that he'd written was using the old API, so you might need to change some parameters passed to methods.


问:
Change position of JavaScript object key and data
I am working on javascript object. And I want to pass data to next array in a specific sequence. like I get data like this

```<code>var obj = [{
  0: "Owner Name"
  1: "Mailing Address"
  2: "Situs Address"
  3: "APN"
}]
</code>```

And want this sequence to be like this

```<code>var obj = [{
  3: "APN"
  0: "Owner Name"
  2: "Situs Address"
  1: "Mailing Address"
}];
</code>```

Is it possible to do that, on bases of data? As I don't know from database sequence maybe change.
edit:  For those who are saying I should use array. I am getting data on basis of this object like,

```<code> var data[{
  0:"CHANCE WILLIAM C & KATHRYN L"
  1:"P O BOX 7642 CHICO CA 95927"
  2:"LOT 4 PM 150-99/100"
  3:"040-310-086-000" }]
</code>```

答:
The keys in a JavaScript object do not have any order. They will be displayed in any order and can change because order is not preserved.

If you need your data in a particular order, use an Array.

Example of an array of strings preserving order

```<code>var orderedItems = [
  "3: APN",
  "0: Owner Name",
  "2: Situs Address",
  "1: Mailing Address"
];
</code>```

Body:
I am working on javascript object. And I want to pass data to next array in a specific sequence. like I get data like this

var obj = [{
  0: "Owner Name"
  1: "Mailing Address"
  2: "Situs Address"
  3: "APN"
}]

And want this sequence to be like this

var obj = [{
  3: "APN"
  0: "Owner Name"
  2: "Situs Address"
  1: "Mailing Address"
}];

Is it possible to do that, on bases of data? As I don't know from database sequence maybe change.
edit:  For those who are saying I should use array. I am getting data on basis of this object like,

 var data[{
  0:"CHANCE WILLIAM C & KATHRYN L"
  1:"P O BOX 7642 CHICO CA 95927"
  2:"LOT 4 PM 150-99/100"
  3:"040-310-086-000" }]

Body:
The keys in a JavaScript object do not have any order. They will be displayed in any order and can change because order is not preserved.

If you need your data in a particular order, use an Array.

Example of an array of strings preserving order

var orderedItems = [
  "3: APN",
  "0: Owner Name",
  "2: Situs Address",
  "1: Mailing Address"
];


问:
Pygame Making A Sprite Face The Mouse
Im New To Pygame But Kinda OK On Python, Im Creating A Zombie Shooting Game With an overhead view.

I managed to make the character move when pressing the arrow keys. But now i need to get the player to FACE the mouse/cursor without clicking the screen all the time.

Any Help?

答:
working code :</p>

```<code>import pygame, sys, math
from pygame.locals import *

#converte in base ai gradi le cordinate x,y
#maxXY= surface MaxXY
#gradoRot = grado di rotazione
#distXY = spostamento in x,y lungo il vettore di cordinate locali dalle cordinate x,y

#movement from one point to another
def Move(t0,t1,psx,psy,speed):
    global mx
    global my

    speed = speed

    distance = [t0 - psx, t1 - psy]
    norm = math.sqrt(distance[0] ** 2 + distance[1] ** 2)
    direction = [distance[0] / norm, distance[1 ] / norm]

    bullet_vector = [direction[0] * speed, direction[1] * speed]
    return bullet_vector
# Main Function
if __name__ == '__main__':
    pygame.init()
    FPS = 30 # frames per second setting
    fpsClock = pygame.time.Clock()
    # set up the window
    DISPLAYSURF = pygame.display.set_mode((800, 600), 0, 32)
    alfhaSurface = DISPLAYSURF.convert_alpha()
    pygame.display.set_caption('test')
    shipImg = pygame.image.load('ship.png')
    shipImgcpy=shipImg.copy()
    vetShip=pygame.math.Vector2(400,300)
    gradi = 0
    gradiRot=0
    mouseX=0
    mouseY=0
    SHIP_W=40
    SHIP_H=40
    vetMouse=pygame.math.Vector2(mouseX,mouseY)
    #main loop
    while True:
        DISPLAYSURF.fill((0,0,0))
        alfhaSurface.fill((0,0,0))
        for event in pygame.event.get():
            if event.type == QUIT:
                pygame.quit()
                sys.exit()
            if event.type == MOUSEBUTTONDOWN:
                mouseX, mouseY = pygame.mouse.get_pos()
                vetMouse=pygame.math.Vector2(mouseX,mouseY)

                gradiRot=**math.atan2(vetShip.x-vetMouse.x, vetShip.y-vetMouse.y)**
                gradiRot=**math.degrees(gradiRot)**
                pygame.display.set_caption(""+str(gradi) +"="+ str(gradiRot)+" "+ str(vetMouse.angle_to(vetShip)) )
        pygame.draw.line(alfhaSurface, (255,255,255), (vetShip.x+SHIP_W,vetShip.y+SHIP_H),(vetMouse.x,vetMouse.y),1)
        if gradi != int(gradiRot) :
            if gradiRot > gradi and gradi != gradiRot :
                gradi=gradi+1

            if gradiRot < gradi and gradi != gradiRot :
                gradi=gradi-1

            shipImgcpy=pygame.transform.rotate(shipImg.copy(),gradi)

        elif int(vetMouse.distance_to(vetShip)) >0:
            posNext=Move(mouseX,mouseY,vetShip.x+SHIP_W,vetShip.y+SHIP_H,1)
          vetShip=pygame.math.Vector2(vetShip.x+posNext[0],vetShip.y+posNext[1])

        alfhaSurface.blit(shipImgcpy, tuple(vetShip))
        DISPLAYSURF.blit(alfhaSurface,(0,0))
        pygame.display.update()
        fpsClock.tick(FPS)
</code>```

Title: Pygame Making A Sprite Face The Mouse

Body:
working code :

import pygame, sys, math
from pygame.locals import *

#converte in base ai gradi le cordinate x,y
#maxXY= surface MaxXY
#gradoRot = grado di rotazione
#distXY = spostamento in x,y lungo il vettore di cordinate locali dalle cordinate x,y

#movement from one point to another
def Move(t0,t1,psx,psy,speed):
    global mx
    global my

    speed = speed

    distance = [t0 - psx, t1 - psy]
    norm = math.sqrt(distance[0] ** 2 + distance[1] ** 2)
    direction = [distance[0] / norm, distance[1 ] / norm]

    bullet_vector = [direction[0] * speed, direction[1] * speed]
    return bullet_vector
# Main Function
if __name__ == '__main__':
    pygame.init()
    FPS = 30 # frames per second setting
    fpsClock = pygame.time.Clock()
    # set up the window
    DISPLAYSURF = pygame.display.set_mode((800, 600), 0, 32)
    alfhaSurface = DISPLAYSURF.convert_alpha()
    pygame.display.set_caption('test')
    shipImg = pygame.image.load('ship.png')
    shipImgcpy=shipImg.copy()
    vetShip=pygame.math.Vector2(400,300)
    gradi = 0
    gradiRot=0
    mouseX=0
    mouseY=0
    SHIP_W=40
    SHIP_H=40
    vetMouse=pygame.math.Vector2(mouseX,mouseY)
    #main loop
    while True:
        DISPLAYSURF.fill((0,0,0))
        alfhaSurface.fill((0,0,0))
        for event in pygame.event.get():
            if event.type == QUIT:
                pygame.quit()
                sys.exit()
            if event.type == MOUSEBUTTONDOWN:
                mouseX, mouseY = pygame.mouse.get_pos()
                vetMouse=pygame.math.Vector2(mouseX,mouseY)

                gradiRot=**math.atan2(vetShip.x-vetMouse.x, vetShip.y-vetMouse.y)**
                gradiRot=**math.degrees(gradiRot)**
                pygame.display.set_caption(""+str(gradi) +"="+ str(gradiRot)+" "+ str(vetMouse.angle_to(vetShip)) )
        pygame.draw.line(alfhaSurface, (255,255,255), (vetShip.x+SHIP_W,vetShip.y+SHIP_H),(vetMouse.x,vetMouse.y),1)
        if gradi != int(gradiRot) :
            if gradiRot > gradi and gradi != gradiRot :
                gradi=gradi+1

            if gradiRot < gradi and gradi != gradiRot :
                gradi=gradi-1

            shipImgcpy=pygame.transform.rotate(shipImg.copy(),gradi)

        elif int(vetMouse.distance_to(vetShip)) >0:
            posNext=Move(mouseX,mouseY,vetShip.x+SHIP_W,vetShip.y+SHIP_H,1)
          vetShip=pygame.math.Vector2(vetShip.x+posNext[0],vetShip.y+posNext[1])

        alfhaSurface.blit(shipImgcpy, tuple(vetShip))
        DISPLAYSURF.blit(alfhaSurface,(0,0))
        pygame.display.update()
        fpsClock.tick(FPS)


问:
Slicing columns in Python
I am new in Python. I want to slice columns from index 1 to end of a marix and perform some operations on the those sliced out columns. Following is the code:

```<code>import numpy as np
import pandas as pd

train_df = pd.read_csv('train_475_60_W1.csv',header = None)
train = train_df.as_matrix()
y = train[:,0]
X = train[:,1:-1]
</code>```

The problem is if I execeute "train.shape", it gives me (89512, 61). But when I execute "X.shape", it give me (89512, 59). I was expecting to get 60 as I want to execute operations on all the colunms except the first one. Can anyone please help me in solving this?

答:
In the line

```<code>X = train[:,1:-1]
</code>```

you cut off the last column. -1 refers to the last column, and Python includes the beginning but not the end of a slice - so lst[2:6] would give you entries 2,3,4, and 5. Correct it to

```<code>X = train[:,1:]
</code>```

BTW, you can make your code format properly by including four spaces before each line (you can just highlight it and hit Ctrl+K).

Title: Slicing columns in Python

Body:
I am new in Python. I want to slice columns from index 1 to end of a marix and perform some operations on the those sliced out columns. Following is the code:

import numpy as np
import pandas as pd

train_df = pd.read_csv('train_475_60_W1.csv',header = None)
train = train_df.as_matrix()
y = train[:,0]
X = train[:,1:-1]

The problem is if I execeute "train.shape", it gives me (89512, 61). But when I execute "X.shape", it give me (89512, 59). I was expecting to get 60 as I want to execute operations on all the colunms except the first one. Can anyone please help me in solving this?

Body:
In the line

X = train[:,1:-1]

you cut off the last column. -1 refers to the last column, and Python includes the beginning but not the end of a slice - so lst[2:6] would give you entries 2,3,4, and 5. Correct it to

X = train[:,1:]

BTW, you can make your code format properly by including four spaces before each line (you can just highlight it and hit Ctrl+K).


问:
Infinite scroll on already populated div
I have a div with large data (many sub-div),I want to implement a infinite scroll on this div, I tried with some jquery scripts which is available on internet for example :

JScroll

MetaFizzy Infinite Scroll

and many more which i could find on google.

Most of the scripts do ajax call to fetch data (but i already have data with me)

I am able to implement Custom Pagination with next and previous functionality
as used in this example
Custom Pagination with Next and Prev Button

But i want to implement a infinite scroll

Here's is div example

```<code><div class="InfiniteScroll">
  <div class="line-content">1 I have some content</div>
  <div class="line-content">2 I have some content</div>
  <div class="line-content">3 I have some content</div>
  <div class="line-content">4 I have some content</div>
  <div class="line-content">5 I have some content</div>
  <div class="line-content">6 I have some content</div>
  <div class="line-content">7 I have some content</div>
  <div class="line-content">8 I have some content</div>
  <div class="line-content">9 I have some content</div>
  <div class="line-content">10 I have some content</div>
  <div class="line-content">11 I have some content</div>
  ..
  ..
  ..
  ..
  ..
  ..
  ..
  <div>AND MANY MORE</div>
</div>
</code>```

Fiddle For Testing :   Fiddle For Test

答:
<!DOCTYPE html>

1 I have some content

1 I have some content

1 I have some content

1 I have some content

1 I have some content

1 I have some content

1 I have some content

1 I have some content

1 I have some content

1 I have some content

1 I have some content

1 I have some content

1 I have some content

1 I have some content

1 I have some content

1 I have some content

1 I have some content

1 I have some content

1 I have some content

1 I have some content

1 I have some content

1 I have some content

```

I tried the existing plugin and modified according to your requirement.Run it in the browser,hope this solved your problem.

Body:
I have a div with large data (many sub-div),I want to implement a infinite scroll on this div, I tried with some jquery scripts which is available on internet for example :

JScroll

MetaFizzy Infinite Scroll

and many more which i could find on google.

Most of the scripts do ajax call to fetch data (but i already have data with me)

I am able to implement Custom Pagination with next and previous functionality
as used in this example
Custom Pagination with Next and Prev Button

But i want to implement a infinite scroll

Here's is div example

1 I have some content

2 I have some content

3 I have some content

4 I have some content

5 I have some content

6 I have some content

7 I have some content

8 I have some content

9 I have some content

10 I have some content

11 I have some content

  ..
  ..
  ..
  ..
  ..
  ..
  ..

AND MANY MORE

Fiddle For Testing :   Fiddle For Test

Body:
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<style>
body {
    margin: 0;
    font-family: 'Liberation Sans', Arial, sans-serif;
}

h1 {
    text-align: center;
}

#posts {
    margin: 0 auto;
    padding: 0;
    width: 700px;
    list-style-type: none;
}

article h1 {
    text-align: left;
    border-bottom: 1px dotted #E3E3E3;
}

article p {
    text-align: justify;
    line-height: 1.5;
    font-size: 1.1em;
}

#loading {
    display: none;
    text-align: center;
}
</style>
<script>

$(document).ready(function() {
    var win = $(window);

    // Each time the user scrolls
    win.scroll(function() {
        // End of the document reached?
        if ($(document).height() - win.height() == win.scrollTop()) {
            $('#loading').show();

            // Uncomment this AJAX call to test it
            /*
            $.ajax({
                url: 'get-post.php',
                dataType: 'html',
                success: function(html) {
                    $('#posts').append(html);
                    $('#loading').hide();
                }
            });
            */

            $('#posts').append(randomPost());
            $('#loading').hide();
        }
    });
});

// Generate a random post
function randomPost() {
    // Paragraphs that will appear in the post
    var paragraphs = [
        '<p> </p>'];

    // Shuffle the paragraphs
    for (var i = paragraphs.length - 1; !!i; --i) {
        var j = Math.floor(Math.random() * i);
        var p = paragraphs[i];
        paragraphs[i] = paragraphs[j];
        paragraphs[j] = p;
    }

    // Generate the post
    var post = '<li>';
    post += '<article>';
    post += '<header><h1>Datas</h1></header>';
    post += paragraphs.join('');
    post += '</article>';
    post += '</li>';

    return post;
}
</script>
</head>
<body>

        <div id="posts">

                    <p class="line-content">1 I have some content</p>
        <p class="line-content">1 I have some content</p>
           <p class="line-content">1 I have some content</p>
           <p class="line-content">1 I have some content</p>
           <p class="line-content">1 I have some content</p>
           <p class="line-content">1 I have some content</p>
              <p class="line-content">1 I have some content</p>
              <p class="line-content">1 I have some content</p>
           <p class="line-content">1 I have some content</p>
           <p class="line-content">1 I have some content</p>
              <p class="line-content">1 I have some content</p>
           <p class="line-content">1 I have some content</p>
           <p class="line-content">1 I have some content</p>
           <p class="line-content">1 I have some content</p>
           <p class="line-content">1 I have some content</p>
           <p class="line-content">1 I have some content</p>

           <p class="line-content">1 I have some content</p>
           <p class="line-content">1 I have some content</p>
           <p class="line-content">1 I have some content</p>
           <p class="line-content">1 I have some content</p>
           <p class="line-content">1 I have some content</p>
           <p class="line-content">1 I have some content</p>

        </div>

</body>
</html>

I tried the existing plugin and modified according to your requirement.Run it in the browser,hope this solved your problem.


问:
How to enable disable sup tag in javascript
i have 2 radio buttons and one text box i need to make(*)appear on the textbox when yes radiobutton is clicked and removed when no radio button is clicked.

my view:

```<code>  <label>code<sup id="star" disabled>*</sup></label>
      >Add to electronic<input type="radio" name="yes" id="yes"/>onchange="starenable()"/><input type="radio" name="yes"
        > id="no"/>onchange="starenable()"/>no
</code>```

my javascript:

```<code> function starenable() {
        if (document.getElementById('yes').checked) {
            document.getElementById("star").disabled = false;
        } else if (document.getElementById('no').checked) {
            document.getElementById("star").disabled = true;
        }
    }
</code>```

i tried this but no change in view. any ideas?

答:
Here is your solution https://jsfiddle.net/me9uwL2d/</p>

```<code><input type="radio" name="test" value="Yes" />Yes
<input type="radio" name="test" value="No" />No
<input type="text" />

$('input[type="radio"]').change(function() {
    if( $(this).is(':checked') && ($(this).attr('value') == 'Yes')) {
        $('input[type="text"]').val("*");
    }else{
        $('input[type="text"]').val('');
    }
});
</code>```

Body:
i have 2 radio buttons and one text box i need to make(*)appear on the textbox when yes radiobutton is clicked and removed when no radio button is clicked.

my view:

  code*
      >Add to electronic<input type="radio" name="yes" id="yes"/>onchange="starenable()"/><input type="radio" name="yes"
        > id="no"/>onchange="starenable()"/>no

my javascript:

 function starenable() {
        if (document.getElementById('yes').checked) {
            document.getElementById("star").disabled = false;
        } else if (document.getElementById('no').checked) {
            document.getElementById("star").disabled = true;
        }
    }

i tried this but no change in view. any ideas?

Body:
Here is your solution https://jsfiddle.net/me9uwL2d/

<input type="radio" name="test" value="Yes" />Yes
<input type="radio" name="test" value="No" />No
<input type="text" />

$('input[type="radio"]').change(function() {
    if( $(this).is(':checked') && ($(this).attr('value') == 'Yes')) {
        $('input[type="text"]').val("*");
    }else{
        $('input[type="text"]').val('');
    }
});


问:
No data when attempting to get JSONP data from cross domain PHP script
I am trying to pull latitude and longitude values from another server on a different domain using a singe id string. I am not very familiar with JQuery, but it seems to be the easiest way to go about getting around the same origin problem. I am unable to use iframes and I cannot install PHP on the server running this javascript, which is forcing my hand on this.

My queries appear to be going through properly, but I am not getting any results back. I was hoping someone here might have an idea that could help, seeing as I probably wouldn't recognize most obvious errors here.

My javascript function is:

```<code>var surl = "http://...omitted.../pull.php";
var idnum = 5a; //in practice this is defined above

alert("BEFORE");

$.ajax({
    url: surl,
    data: {id: idnum},
    dataType: "jsonp",
    jsonp : "callback",
    jsonp: "jsonpcallback",
    success: function (rdata) {
        alert(rdata.lat + ", " + rdata.lon);
    }
});

alert("BETWEEN");

function jsonpcallback(rtndata) {
    alert("CALLED");
    alert(rtndata.lat + ", " + rtndata.lon);
}

    alert("AFTER");
</code>```

When my javascript is run, the BEFORE, BETWEEN and AFTER alerts are displayed. The CALLED and other jsonpcallback alerts are not shown.

Is there another way to tell if the jsoncallback function has been called?

Below is the PHP code I have running on the second server. I added the count table to my database just so that I can tell when this script is run. Every time I call the javascript, count has had an extra item inserted and the id number is correct.

```<code><?php

    header("content-type: application/json");

if (isset($_GET['id']) || isset($_POST['id'])){

    $db_handle = mysql_connect($server, $username, $password);
    if (!$db_handle)
    {
        die('Could not connect: ' . mysql_error());
    }

    $db_found = mysql_select_db($database, $db_handle);
    if ($db_found)
    {
        if (isset($_POST['id'])){
            $SQL = sprintf("SELECT * FROM %s WHERE loc_id='%s'", $loctable, mysql_real_escape_string($_POST['id']));
        }
        if (isset($_GET['id'])){
            $SQL = sprintf("SELECT * FROM %s WHERE loc_id='%s'", $loctable, mysql_real_escape_string($_GET['id']));
        }
        $result = mysql_query($SQL, $db_handle);
        $db_field = mysql_fetch_assoc($result);

        $rtnjsonobj -> lat = $db_field["lat"];
        $rtnjsonobj -> lon = $db_field["lon"];

        if (isset($_POST['id'])){
            echo $_POST['jsonpcallback']. '('. json_encode($rtnjsonobj) . ')';
        }
        if (isset($_GET['id'])){
            echo $_GET['jsonpcallback']. '('. json_encode($rtnjsonobj) . ')';
        }

        $SQL = sprintf("INSERT INTO count (bullshit) VALUES ('%s')", $_GET['id']);
        $result = mysql_query($SQL, $db_handle);
        $db_field = mysql_fetch_assoc($result);
    }

    mysql_close($db_handle);
} else {
    $rtnjsonobj -> lat = 404;
    $rtnjsonobj -> lon = 404;
    echo $_GET['jsonpcallback']. '('. json_encode($rtnjsonobj) . ')';
}?>
</code>```

I am not entirely sure if the jsonp returned by this PHP is correct. When I go directly to the PHP script without including any parameters, I do get the following.

```<code> ({"lat":404,"lon":404})
</code>```

The callback function is not included, but that much can be expected when it isn't included in the original call.

Does anyone have any idea what might be going wrong here?

Thanks in advance!

答:
Change this part of the code

```<code>jsonp: "jsonpcallback",
</code>```

with:

```<code>jsonpCallback : "jsonpcallback",
</code>```

Body:
I am trying to pull latitude and longitude values from another server on a different domain using a singe id string. I am not very familiar with JQuery, but it seems to be the easiest way to go about getting around the same origin problem. I am unable to use iframes and I cannot install PHP on the server running this javascript, which is forcing my hand on this.

My queries appear to be going through properly, but I am not getting any results back. I was hoping someone here might have an idea that could help, seeing as I probably wouldn't recognize most obvious errors here.

My javascript function is:

var surl = "http://...omitted.../pull.php";
var idnum = 5a; //in practice this is defined above

alert("BEFORE");

$.ajax({
    url: surl,
    data: {id: idnum},
    dataType: "jsonp",
    jsonp : "callback",
    jsonp: "jsonpcallback",
    success: function (rdata) {
        alert(rdata.lat + ", " + rdata.lon);
    }
});

alert("BETWEEN");

function jsonpcallback(rtndata) {
    alert("CALLED");
    alert(rtndata.lat + ", " + rtndata.lon);
}

    alert("AFTER");

When my javascript is run, the BEFORE, BETWEEN and AFTER alerts are displayed. The CALLED and other jsonpcallback alerts are not shown.

Is there another way to tell if the jsoncallback function has been called?

Below is the PHP code I have running on the second server. I added the count table to my database just so that I can tell when this script is run. Every time I call the javascript, count has had an extra item inserted and the id number is correct.

<?php

    header("content-type: application/json");

if (isset($_GET['id']) || isset($_POST['id'])){

    $db_handle = mysql_connect($server, $username, $password);
    if (!$db_handle)
    {
        die('Could not connect: ' . mysql_error());
    }

    $db_found = mysql_select_db($database, $db_handle);
    if ($db_found)
    {
        if (isset($_POST['id'])){
            $SQL = sprintf("SELECT * FROM %s WHERE loc_id='%s'", $loctable, mysql_real_escape_string($_POST['id']));
        }
        if (isset($_GET['id'])){
            $SQL = sprintf("SELECT * FROM %s WHERE loc_id='%s'", $loctable, mysql_real_escape_string($_GET['id']));
        }
        $result = mysql_query($SQL, $db_handle);
        $db_field = mysql_fetch_assoc($result);

        $rtnjsonobj -> lat = $db_field["lat"];
        $rtnjsonobj -> lon = $db_field["lon"];

        if (isset($_POST['id'])){
            echo $_POST['jsonpcallback']. '('. json_encode($rtnjsonobj) . ')';
        }
        if (isset($_GET['id'])){
            echo $_GET['jsonpcallback']. '('. json_encode($rtnjsonobj) . ')';
        }

        $SQL = sprintf("INSERT INTO count (bullshit) VALUES ('%s')", $_GET['id']);
        $result = mysql_query($SQL, $db_handle);
        $db_field = mysql_fetch_assoc($result);
    }

    mysql_close($db_handle);
} else {
    $rtnjsonobj -> lat = 404;
    $rtnjsonobj -> lon = 404;
    echo $_GET['jsonpcallback']. '('. json_encode($rtnjsonobj) . ')';
}?>

I am not entirely sure if the jsonp returned by this PHP is correct. When I go directly to the PHP script without including any parameters, I do get the following.

 ({"lat":404,"lon":404})

The callback function is not included, but that much can be expected when it isn't included in the original call.

Does anyone have any idea what might be going wrong here?

Thanks in advance!

Body:
Change this part of the code

jsonp: "jsonpcallback",

with:

jsonpCallback : "jsonpcallback",


问:
How to time different parts of a loop in Javascript
Not a duplicate of How to measure time taken by a function to execute. Please actually read my question before marking it as a duplicate of something else. Regardless, it's been answered.

I have code like

```<code>for (var i = 0 ; i < 10000 ; i++) {

    doSomething();

    doSomethingElse();

}
</code>```

And I want to know how much time each function inside the loop is taking overall. How do I measure that?

答:
Create a test object and register the individual time differences:

function doSomething() {
  t = Date.now();
  while (Date.now() < t + 13) {}
}

function doSomethingElse() {
  t = Date.now();
  while (Date.now() < t + 27) {}
}
var tests = {
  "doSomething": [],
  "doSomethingElse": []
};
for (var i_1 = 0; i_1 < 10; i_1++) {
  var t = Date.now();
  doSomething();
  tests.doSomething.push(Date.now() - t);
  t = Date.now();
  doSomethingElse();
  tests.doSomethingElse.push(Date.now() - t);
}
for (var key in tests) {
  if (tests.hasOwnProperty(key)) {
    tests[key] = tests[key]
      .reduce(function(sum, value) {
        return sum + value;
      }, 0);
  }
}
console.log(tests);```

Body:
Not a duplicate of How to measure time taken by a function to execute. Please actually read my question before marking it as a duplicate of something else. Regardless, it's been answered.

I have code like

for (var i = 0 ; i < 10000 ; i++) {

    doSomething();

    doSomethingElse();

}

And I want to know how much time each function inside the loop is taking overall. How do I measure that?


问:
Submit ajax form on enter press in textbox
I have a textbox that is my message textbox.
At the moment, my ajax form works by the click of a button.
Im guessing because the button's name.

I want it so that when I press enter in my textbox, it submits the form but without refreshing the page.

Adding some jquery on enter makes my page refresh.

Below is the code to my refreshing page current state.
My working state with a button is included with this form instead:

```<code>    <form class="chat-form form -dark" method="POST" onsubmit="return submitchat();">
        <input class="form-control" type="text" name="chat" id="chatbox" placeholder="Type something.." />
        <input type='submit' name='send' id='send' class='btn btn-send' value='Send' />
    </form>
</code>```

My php script is :

```<code>    <form class="chat-form form -dark" method="POST" onsubmit="return submitchat();">
        <input class="form-control entryMsg" type="text" name="chat" id="chatbox" placeholder="Type something.." />
    </form>
</code>```

My Javascript  / Jquery is :`

```<code><script>
    // Javascript function to submit new chat entered by user
    function submitchat(){
            if($('#chat').val()=='' || $('#chatbox').val()==' ') return false;
            $.ajax({
                url:'chat/chat.php',
                data:{chat:$('#chatbox').val(),ajaxsend:true},
                method:'post',
                success:function(data){
                    $('#result').html(data); // Get the chat records and add it to result div
                    $('#chatbox').val(''); //Clear chat box after successful submition
                    document.getElementById('result').scrollTop=document.getElementById('result').scrollHeight; // Bring the scrollbar to bottom of the chat resultbox in case of long chatbox
                }
            })
            return false;
    };

    // Function to continously check the some has submitted any new chat
    setInterval(function(){
        $.ajax({
                url:'chat/chat.php',
                data:{ajaxget:true},
                method:'post',
                success:function(data){
                    $('#result').html(data);
                }
        })
    },1000);

    // Function to chat history
    $(document).ready(function(){
        $('#clear').click(function(){
            if(!confirm('Are you sure you want to clear chat?'))
                return false;
            $.ajax({
                url:'chat/chat.php',
                data:{username:"<?php echo $_SESSION['username'] ?>",ajaxclear:true},
                method:'post',
                success:function(data){
                    $('#result').html(data);
                }
            })
        })
    })
</script>
<script>
    $(document).ready(function() {
        $('.entryMsg').keydown(function(event) {
            if (event.keyCode == 13) {
                this.form.submit();
                return false;
             }
        });
    });
</script>`
</code>```

答:
change the function to this</p>

```<code>    function submitchat(e){
    e.preventDefault();
// rest  code
}
</code>```

Body:
I have a textbox that is my message textbox.
At the moment, my ajax form works by the click of a button.
Im guessing because the button's name.

I want it so that when I press enter in my textbox, it submits the form but without refreshing the page.

Adding some jquery on enter makes my page refresh.

Below is the code to my refreshing page current state.
My working state with a button is included with this form instead:

    <form class="chat-form form -dark" method="POST" onsubmit="return submitchat();">
        <input class="form-control" type="text" name="chat" id="chatbox" placeholder="Type something.." />
        <input type='submit' name='send' id='send' class='btn btn-send' value='Send' />
    </form>

My php script is :

    <form class="chat-form form -dark" method="POST" onsubmit="return submitchat();">
        <input class="form-control entryMsg" type="text" name="chat" id="chatbox" placeholder="Type something.." />
    </form>

My Javascript  / Jquery is :`

`

Body:
change the function to this

    function submitchat(e){
    e.preventDefault();
// rest  code
}


问:
How to get credit memo by order id
I am trying to get credit memo collection by order id in external php file in magento 1.9.x

Here is my code to get credit memo by order id.

```<code>$collection = Mage::getResourceModel('sales/order_creditmemo_collection')
              ->addFieldToFilter('order_id', $order->getId());
foreach($collection as $item) {
    echo $item->getId();
}
</code>```

But it is showing NULL

i tried with various example available on SO but they didn't help me.

Any help will be greatly appreciated.

答:
Try this code.

```<code><?php
    $orderid = 6; //you order id
    $creditMemos = Mage::getResourceModel('sales/order_creditmemo_collection');
    $creditMemos->addFieldToFilter('order_id', $orderid);
    $creditMemos->setOrder('created_at','DESC');
    $creditMemos->load();

    foreach ($creditMemos as $creditMemo) {
       var_dump($creditMemo->getData());
    }
?>
</code>```

you can remove this line to get full collection.

```<code>$creditMemos->addFieldToFilter('order_id', $orderid);
</code>```

Title: How to get credit memo by order id

Body:
I am trying to get credit memo collection by order id in external php file in magento 1.9.x

Here is my code to get credit memo by order id.

$collection = Mage::getResourceModel('sales/order_creditmemo_collection')
              ->addFieldToFilter('order_id', $order->getId());
foreach($collection as $item) {
    echo $item->getId();
}

But it is showing NULL

i tried with various example available on SO but they didn't help me.

Any help will be greatly appreciated.

Body:
Try this code.

<?php
    $orderid = 6; //you order id
    $creditMemos = Mage::getResourceModel('sales/order_creditmemo_collection');
    $creditMemos->addFieldToFilter('order_id', $orderid);
    $creditMemos->setOrder('created_at','DESC');
    $creditMemos->load();

    foreach ($creditMemos as $creditMemo) {
       var_dump($creditMemo->getData());
    }
?>

you can remove this line to get full collection.

$creditMemos->addFieldToFilter('order_id', $orderid);


问:
How to check for last item when looping through a structure in ColdFusion?
I want to loop over a structure and output something for all items except the last one. For arrays this can easily be done by checking whether the current index is the last one, though how to do it for structures?

Example code:

```<code><cfscript>
myStruct = {
  item1 = "foo",
  item2 = "bar",
  item3 = "baz"
};
</cfscript>

<cfoutput>
<cfloop collection="#myStruct#" item="item">
  #myStruct[item]#
  <!--- Here should be the conditional output --->
</cfloop>
</cfoutput>
</code>```

答:
This would be a simple solution. </p>

```<code><cfscript>
    myStruct = {
      item1 = "foo",
      item2 = "bar",
      item3 = "baz"
   };
</cfscript>
<cfset KeyListArray = ListToArray(StructKeyList(myStruct))>
<cfoutput>
    <cfloop from="1" to="#(ArrayLen(KeyListArray)-1)#" index="i">
       #myStruct[i]#
      <!--- Here should be the conditional output --->
    </cfloop>
</cfoutput>
</code>```

Body:
I want to loop over a structure and output something for all items except the last one. For arrays this can easily be done by checking whether the current index is the last one, though how to do it for structures?

Example code:

<cfscript>
myStruct = {
  item1 = "foo",
  item2 = "bar",
  item3 = "baz"
};
</cfscript>

<cfoutput>
<cfloop collection="#myStruct#" item="item">
  #myStruct[item]#

</cfloop>
</cfoutput>

Body:
This would be a simple solution.

<cfscript>
    myStruct = {
      item1 = "foo",
      item2 = "bar",
      item3 = "baz"
   };
</cfscript>
<cfset KeyListArray = ListToArray(StructKeyList(myStruct))>
<cfoutput>
    <cfloop from="1" to="#(ArrayLen(KeyListArray)-1)#" index="i">
       #myStruct[i]#
      <!--- Here should be the conditional output --->
    </cfloop>
</cfoutput>


问:
Leaflet Loop Snake function on several polyline routes
I currently have two routes, both I stored in an array. I am trying to sequentially animate the routes (polyline) using the following for loop.

```<code>var pathmat = [path1, path2];
for (var p = 0; p < 1; p++)
    {
    function snake() {
        pathmat[p].snakeIn();
    }

    pathmat[p].on('snakestart snake snakeend', function(ev){
        console.log(ev.type);
    });
    }
</code>```

It skips directly to animating path2.

Please help.

NOTE: I am an absolute noob in JS.

答:
You seem to be using my very own Leaflet.SnakeAnim plugin (you should have mentioned this in your question).

The documentation states that you can use snakeIn() on a L.Polyline but also on a L.LayerGroup, and has examples of that. Also look at the source code demo-group.html, which animates several polylines one after another.

Body:
I currently have two routes, both I stored in an array. I am trying to sequentially animate the routes (polyline) using the following for loop.

var pathmat = [path1, path2];
for (var p = 0; p < 1; p++)
    {
    function snake() {
        pathmat[p].snakeIn();
    }

    pathmat[p].on('snakestart snake snakeend', function(ev){
        console.log(ev.type);
    });
    }

It skips directly to animating path2.

Please help.

NOTE: I am an absolute noob in JS.


问:
Why do changes made to a cell propagate to other cells in this 2 dimensional array created using fill?
I have a problem with this 2-dimensional array in JS. When I change a[1][0], a[0][0] changes with it. Is there something wrong in the way I am initializing it? If yes, how can I initialize it properly?

```<code>>var a = Array(100).fill(Array(100).fill(false));
>a[0][0]
>false
>a[1][0]
>false
>a[1][0] = true
>true
>a[1][0]
>true
>a[0][0]
>true
</code>```

答:
Since arrays are reference types, creating an N Dimensional array in JS is not so trivial. You need to create a clone tool first.

Array.prototype.clone = function(){
  return this.map(e => Array.isArray(e) ? e.clone() : e);
};

function arrayND(...n){
  return n.reduceRight((p,c) => c = (new Array(c)).fill().map(e => Array.isArray(p) ? p.clone() : p ));
}

var arr = arrayND(2,3,4,"x")
console.log(JSON.stringify(arr));```

arrayND takes indefinite number of integer arguments each designating the size of a dimension and the last argument is the fill value.

Body:
I have a problem with this 2-dimensional array in JS. When I change a[1][0], a[0][0] changes with it. Is there something wrong in the way I am initializing it? If yes, how can I initialize it properly?

>var a = Array(100).fill(Array(100).fill(false));
>a[0][0]
>false
>a[1][0]
>false
>a[1][0] = true
>true
>a[1][0]
>true
>a[0][0]
>true

Body:
Since arrays are reference types, creating an N Dimensional array in JS is not so trivial. You need to create a clone tool first.

Array.prototype.clone = function(){
  return this.map(e => Array.isArray(e) ? e.clone() : e);
};

function arrayND(...n){
  return n.reduceRight((p,c) => c = (new Array(c)).fill().map(e => Array.isArray(p) ? p.clone() : p ));
}

var arr = arrayND(2,3,4,"x")
console.log(JSON.stringify(arr));

arrayND takes indefinite number of integer arguments each designating the size of a dimension and the last argument is the fill value.


问:
How to setup automation testing project in visual studio 2017 using C# & How to RUN the Test Scripts in TFS
Environment is
1. Visual Studio 2017
2. Visual Studio Team server

In My requirement is, If i update "TEST SCRIPTS" code in Visual Studio Team server its will build automatically every release. But i need to to RUN the updated "TEST SCRIPTS" in Visual Studio Team server.

答:
There are many tasks to run test, such as Visual Studio Test, Maven Test, Run Functional Test. So you can create a unit test/coded UI test project in VS 2017 and run the test through Visual Studio Test task.

Related article: Get started with continuous testing.

I recommend you run the test during the build.

Regarding run the test once the Test Script code be changed, you can setup a CI build (Triggers tab). If you want to do test in release, you need to publish artifact (test project build result), and configure release with Continuous Deployment mode (Triggers)


问:
Creating optional nested formgroups in Angular 2
I am trying to implement a model-driven form in Angular 2. The structure of my data model is as follows:

```<code>archive (FormGroup)
    name (FormControl)
    description (FormControl)
    connection (FormGroup)
        url (FormControl)
        authentication (FormGroup)
            username (FormControl)
            password (FormControl)
</code>```

Within this data model, the top-level name is required but the description field is optional. I can apply a required validator to name, and omit a validator from description.

For the connection, I want it to be optional but if a connection is present its URL becomes required. Similarly for the authentication model of the connection: It is optional but if present the username and password would be required.

I am trying to understand how to set up validators to enforce these rules. I have tried just omitting any validators from the connection form group, but that seemed to be requiring me to have a connection. I've seen online tutorials explaining how to implement custom validation on a nested form groups but nothing that describes how to make the entire nested formgroup optional.

Is there a straightforward way to implement this model with Angular 2 FormGroup?

答:
I had a similar need and here is a way to solve it:

```<code>this.form = new FormGroup({
    'name': new FormControl(null, Validators.required),
    'description': new FormControl(null),
    'connection': new FormGroup({
        'url': new FormControl(null),
        'authentification': new FormGroup({
            'username': new FormControl(null, Validators.minLength(5)),
            'password': new FormControl(null),
        }, this.authentificationValidator.bind(this)),
    }, this.connectionValidator.bind(this))
});
</code>```

The 2 validator functions:

```<code>authentificationValidator(g: FormGroup): any {
    const username = g.get('username').value;
    const password = g.get('password').value;

    if( (username && !password) || (!username && password) ) {
        return {
            authentification: true
        };
    }
}

connectionValidator(g: FormGroup): any {
    const url = g.get('url').value;

    const authentification = g.get('authentification');
    const username = authentification.get('username').value;
    const password = authentification.get('password').value;

    if( (username || password) && !url ) {
      return {
          connection: true
      };
    }
}
</code>```

And for the output, if you fill only the name, you will still have:

```<code>{
  "name": null,
  "description": null,
  "connection": {
    "url": null,
    "authentification": {
      "username": null,
      "password": null
    }
  }
}
</code>```

So you have to conditionnaly create a new object to have:

```<code>{
  "name": null,
  "description": null,
  "connection": null
}
</code>```

Check this plunker to experiment this solution

Body:
I am trying to implement a model-driven form in Angular 2. The structure of my data model is as follows:

archive (FormGroup)
    name (FormControl)
    description (FormControl)
    connection (FormGroup)
        url (FormControl)
        authentication (FormGroup)
            username (FormControl)
            password (FormControl)

Within this data model, the top-level name is required but the description field is optional. I can apply a required validator to name, and omit a validator from description.

For the connection, I want it to be optional but if a connection is present its URL becomes required. Similarly for the authentication model of the connection: It is optional but if present the username and password would be required.

I am trying to understand how to set up validators to enforce these rules. I have tried just omitting any validators from the connection form group, but that seemed to be requiring me to have a connection. I've seen online tutorials explaining how to implement custom validation on a nested form groups but nothing that describes how to make the entire nested formgroup optional.

Is there a straightforward way to implement this model with Angular 2 FormGroup?

Body:
I had a similar need and here is a way to solve it:

this.form = new FormGroup({
    'name': new FormControl(null, Validators.required),
    'description': new FormControl(null),
    'connection': new FormGroup({
        'url': new FormControl(null),
        'authentification': new FormGroup({
            'username': new FormControl(null, Validators.minLength(5)),
            'password': new FormControl(null),
        }, this.authentificationValidator.bind(this)),
    }, this.connectionValidator.bind(this))
});

The 2 validator functions:

authentificationValidator(g: FormGroup): any {
    const username = g.get('username').value;
    const password = g.get('password').value;

    if( (username && !password) || (!username && password) ) {
        return {
            authentification: true
        };
    }
}

connectionValidator(g: FormGroup): any {
    const url = g.get('url').value;

    const authentification = g.get('authentification');
    const username = authentification.get('username').value;
    const password = authentification.get('password').value;

    if( (username || password) && !url ) {
      return {
          connection: true
      };
    }
}

And for the output, if you fill only the name, you will still have:

{
  "name": null,
  "description": null,
  "connection": {
    "url": null,
    "authentification": {
      "username": null,
      "password": null
    }
  }
}

So you have to conditionnaly create a new object to have:

{
  "name": null,
  "description": null,
  "connection": null
}

Check this plunker to experiment this solution


问:
Postman REST API automation without duplicating tests
I have 8 requests and I want to run the first three before running each of the other requests. E.g.

```<code>1st collection: 1 -> 2 -> 3 -> 4
2nd collection: 1 -> 2 -> 3 -> 5
3rd collection: 1 -> 2 -> 3 -> 6
4th collection: 1 -> 2 -> 3 -> 7
5th collection: 1 -> 2 -> 3 -> 8
</code>```

Currently I've duplicated the first three requests for each of the other requests, but this makes changing them time consuming.

Is there a way to use the Postman Runner to execute the above without duplication?

答:
you may have a a collection with all your tests and use the setNextRequest feature (refer to http://blog.getpostman.com/2016/03/23/conditional-workflows-in-postman/). With that, I guess you could manage to select request 4 at the first iteration, request 5 at the next, etc. conditioning setNextRequest with an incrementing global variable.

Alexandre

Body:
I have 8 requests and I want to run the first three before running each of the other requests. E.g.

1st collection: 1 -> 2 -> 3 -> 4
2nd collection: 1 -> 2 -> 3 -> 5
3rd collection: 1 -> 2 -> 3 -> 6
4th collection: 1 -> 2 -> 3 -> 7
5th collection: 1 -> 2 -> 3 -> 8

Currently I've duplicated the first three requests for each of the other requests, but this makes changing them time consuming.

Is there a way to use the Postman Runner to execute the above without duplication?


答:
Add a keydown function to run the function.

$("#txtSearchProdAssign").keydown(function (e) {

  if (e.keyCode == 13) {
   console.log("put function call here");
   e.preventDefault();
   submitchat();
  }

});

function submitchat(){
  console.log("SUBMITCHAT function");
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<form type="post">
<input type="text" id="txtSearchProdAssign">
</form></code>```

Title: Submit ajax form on enter press in textbox

Body:
Add a keydown function to run the function.

$("#txtSearchProdAssign").keydown(function (e) {

  if (e.keyCode == 13) {
   console.log("put function call here");
   e.preventDefault();
   submitchat();
  }

});

function submitchat(){
  console.log("SUBMITCHAT function");
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<form type="post">
<input type="text" id="txtSearchProdAssign">
</form>


问:
FIFO implementation - VHDL
I come across one more difficulty  while instantiate the fifo code to my top module. I want to store some set of data say "WELCOME TO THE WORLD OF FPGA" from my serial port ( receiving subsystem)  then i want to retrieve it back say when button on fpga board is pressed or FIFO is full. I have my fifo code and serial communication code written.  Idea is data sent from keyboard ->receiving subsystem  -> FIFO -> transmitting subsystem -> hyperterminal.  I am at present using fifo of 8 bit wide and say 28 deep just to store some small data. Please help me in this regard how can I implement it.I have byte coming from receiver saved in register_save.
fifo code

```<code>inst_bit8_recieve_unit : entity work.byte_recieve_8N1
port map ( ck => ck,
         reset => reset,
         new_byte_in_buffer => new_byte_in_buffer,
         byte_read_from_buffer => byte_read_from_buffer,
         recieve_buffer => register_save,
         JA_2 => JA(2));

---------------------FIFO instantiate-------------------------------
inst_of_fifo_Recieve_unit : entity work.fifo
generic map (B => data_bits, W => fifo_width)
port map ( ck => ck,
            reset => reset,
            rd => rd_rx,
            wr => wr_rx,
            write_data => num_recieved,
            read_data => num_recieved_fifo,
            empty => empty_rx,
            full => full_rx );

inst_bit8_transmit_unit : entity work.byte_transmit_8N1
port map ( ck => ck,
           reset => reset,
           send_byte_ready => send_byte_ready,
           send_byte_done => send_byte_done ,
           send_buffer => num_send,
           JAOUT_0 => JAOUT );
proc_send5byte: process(ck, reset, state_byte5, send_byte_done, num_send, state_button_0, num_recieved_fifo, rd_rx)

begin

if reset = '1' THEN
            state_byte5 <= idle;
            send_byte_ready <='0';
            num_send <= "00000000" ;

  else
  if rising_edge(ck) then

    case state_byte5 is

         when idle =>          ---- in this, if btn(0) is high i.e pressed then only state_byte5 will go to next state
                if state_button_0 = transit_pressed then
                     state_byte5 <= byte;
                     end if;
            -----===============================================================
            when byte =>
                    if (not empty_rx = '1') then

                           if send_byte_ready ='0' and send_byte_done = '0'  then    ----here if condition is satified the send_byte_ready will be set
                                    send_byte_ready <='1';  --------- shows next byte is ready
                                    num_send <= num_recieved_fifo;
                                     rd_rx <='1';

                         end if;
                            end if;

                       if send_byte_ready = '1' and send_byte_done = '1'  then  --- during load state send_byte will be resets
                         send_byte_ready <='0';
                         rd_rx <= '0';
                              state_byte5  <= idle;         ----------- go back to idle
                       end if;
                --end if;
            ---===============================================================

         when others =>
                        state_byte5 <= idle;     ------------- for other cases state state _byte5 will be in idle
                        send_byte_ready <= '0';
                            rd_rx <= '0';
       end case;

   end if;
end if;
end process;
proc_recieving_byte : process (ck, reset, register_save, new_byte_in_buffer, full_rx, num_recieved, wr_rx)
begin

if reset = '1' then
  byte_read_from_buffer <= '0';
  else

      if rising_edge(ck) then
                     if full_rx = '0' then
                         if new_byte_in_buffer = '1' and byte_read_from_buffer = '0' then
                              byte_read_from_buffer <= '1';
                       wr_rx <= '1';
                             num_recieved(7 downto 0 ) <= register_save( 7 downto 0);

                    end if;
                        end if;
                            if new_byte_in_buffer = '0' then
                               byte_read_from_buffer <= '0';
                                wr_rx <= '0';
                       end if;
                   --end if;
     end if;
end if;
end process;
</code>```

Just added the corrected code now which seems to be working. Problem araises when increase the depth of fifo. When depth>2 then every third byte is missing.
Please help, why I am loosing data.

答:
The principe of a fifo is First In First Out. You have not to manage it.

You place your data on input of fifo

You set write enable bit to '1'

You wait for one clock cycle

You set write enable bit to '0'

then the data is store, you do it again to store another value.

When you want to read all data (Fifo full / any case you want)

You set Read enable bit to '1' and every clock cycle, you will receive a data.

Title: FIFO implementation - VHDL

Body:
I come across one more difficulty  while instantiate the fifo code to my top module. I want to store some set of data say "WELCOME TO THE WORLD OF FPGA" from my serial port ( receiving subsystem)  then i want to retrieve it back say when button on fpga board is pressed or FIFO is full. I have my fifo code and serial communication code written.  Idea is data sent from keyboard ->receiving subsystem  -> FIFO -> transmitting subsystem -> hyperterminal.  I am at present using fifo of 8 bit wide and say 28 deep just to store some small data. Please help me in this regard how can I implement it.I have byte coming from receiver saved in register_save.
fifo code

inst_bit8_recieve_unit : entity work.byte_recieve_8N1
port map ( ck => ck,
         reset => reset,
         new_byte_in_buffer => new_byte_in_buffer,
         byte_read_from_buffer => byte_read_from_buffer,
         recieve_buffer => register_save,
         JA_2 => JA(2));

---------------------FIFO instantiate-------------------------------
inst_of_fifo_Recieve_unit : entity work.fifo
generic map (B => data_bits, W => fifo_width)
port map ( ck => ck,
            reset => reset,
            rd => rd_rx,
            wr => wr_rx,
            write_data => num_recieved,
            read_data => num_recieved_fifo,
            empty => empty_rx,
            full => full_rx );

inst_bit8_transmit_unit : entity work.byte_transmit_8N1
port map ( ck => ck,
           reset => reset,
           send_byte_ready => send_byte_ready,
           send_byte_done => send_byte_done ,
           send_buffer => num_send,
           JAOUT_0 => JAOUT );
proc_send5byte: process(ck, reset, state_byte5, send_byte_done, num_send, state_button_0, num_recieved_fifo, rd_rx)

begin

if reset = '1' THEN
            state_byte5 <= idle;
            send_byte_ready <='0';
            num_send <= "00000000" ;

  else
  if rising_edge(ck) then

    case state_byte5 is

         when idle =>          ---- in this, if btn(0) is high i.e pressed then only state_byte5 will go to next state
                if state_button_0 = transit_pressed then
                     state_byte5 <= byte;
                     end if;
            -----===============================================================
            when byte =>
                    if (not empty_rx = '1') then

                           if send_byte_ready ='0' and send_byte_done = '0'  then    ----here if condition is satified the send_byte_ready will be set
                                    send_byte_ready <='1';  --------- shows next byte is ready
                                    num_send <= num_recieved_fifo;
                                     rd_rx <='1';

                         end if;
                            end if;

                       if send_byte_ready = '1' and send_byte_done = '1'  then  --- during load state send_byte will be resets
                         send_byte_ready <='0';
                         rd_rx <= '0';
                              state_byte5  <= idle;         ----------- go back to idle
                       end if;
                --end if;
            ---===============================================================

         when others =>
                        state_byte5 <= idle;     ------------- for other cases state state _byte5 will be in idle
                        send_byte_ready <= '0';
                            rd_rx <= '0';
       end case;

   end if;
end if;
end process;
proc_recieving_byte : process (ck, reset, register_save, new_byte_in_buffer, full_rx, num_recieved, wr_rx)
begin

if reset = '1' then
  byte_read_from_buffer <= '0';
  else

      if rising_edge(ck) then
                     if full_rx = '0' then
                         if new_byte_in_buffer = '1' and byte_read_from_buffer = '0' then
                              byte_read_from_buffer <= '1';
                       wr_rx <= '1';
                             num_recieved(7 downto 0 ) <= register_save( 7 downto 0);

                    end if;
                        end if;
                            if new_byte_in_buffer = '0' then
                               byte_read_from_buffer <= '0';
                                wr_rx <= '0';
                       end if;
                   --end if;
     end if;
end if;
end process;

Just added the corrected code now which seems to be working. Problem araises when increase the depth of fifo. When depth>2 then every third byte is missing.
Please help, why I am loosing data.


问:
Coloring the checkboxGroupInput choices
In my Shiny UI I have

```<code>ui <- checkboxGroupInput("my_cbgi", "Choose Something", c("A", "B", "C", "D"))
</code>```

And I would like it so that the choices (the text) A and B are colored red, but C and D are not. I tried HTML but then in the UI weird boxes like "attribs" and "children" showed up.

Thanks in advance

答:
Since shiny_1.0.1, checkboxGroupInput have a choiceNames and choiceValues arguments for passing arbitrary UI to display to the user, check this example :

```<code>library("shiny")

ui <- fluidPage(
  checkboxGroupInput(
    inputId = "my_cbgi",
    label = "Choose Something",
    choiceNames = list(
      tags$span("A", style = "color: red;"),
      tags$span("B", style = "color: red;"),
      tags$span("C", style = "color: blue;"),
      tags$span("D", style = "font-weight: bold;")
    ),
    choiceValues = c("A", "B", "C", "D")
  )
)

server <- function(input, output) {

}

shinyApp(ui = ui, server = server)
</code>```

Title: Coloring the checkboxGroupInput choices

Body:
In my Shiny UI I have

ui <- checkboxGroupInput("my_cbgi", "Choose Something", c("A", "B", "C", "D"))

And I would like it so that the choices (the text) A and B are colored red, but C and D are not. I tried HTML but then in the UI weird boxes like "attribs" and "children" showed up.

Thanks in advance

Body:
Since shiny_1.0.1, checkboxGroupInput have a choiceNames and choiceValues arguments for passing arbitrary UI to display to the user, check this example :

library("shiny")

ui <- fluidPage(
  checkboxGroupInput(
    inputId = "my_cbgi",
    label = "Choose Something",
    choiceNames = list(
      tags$span("A", style = "color: red;"),
      tags$span("B", style = "color: red;"),
      tags$span("C", style = "color: blue;"),
      tags$span("D", style = "font-weight: bold;")
    ),
    choiceValues = c("A", "B", "C", "D")
  )
)

server <- function(input, output) {

}

shinyApp(ui = ui, server = server)