问:
nodejs how to serve node_modules directory to front end for access?
Without using any packaging software such as Browserify or Webpack, I have a simple server that in nodejs.

```<code>var express = require('express');
var bodyParser = require('body-parser');
var request = require('request');
var app = express();
app.use(bodyParser());
app.use(express.static('public'));
app.use(express.static('node_modules'));

app.post('/api/searchjob', function (req, res) {
  res.json({data: "hello"});
});

app.get('/', function(req,res) {
  res.sendfile('public/index.html');
});

app.get('/*', function(req, res){
  res.redirect('/');
})

app.listen(process.env.PORT || 3000, function () {
  console.log('Example app listening on port 3000!')
});
</code>```

I want the front end to also have access to some node_modules packages, what can i do? my index.html file is in "public" directory, the folder structure look like this:

```<code>├── README.md
├── index.js
├── node_modules
├── package.json
├── public
└── yarn.lock
</code>```

I tried simply put the script tag in index.html, but doesn't work
>

答:
I write this:</p>

```<code>  app.use(express.static(path.join(__dirname, 'node_modules')));
  <script src="/vue2-google-maps/dist/vue-google-maps.js"></script>
</code>```

Body:
Without using any packaging software such as Browserify or Webpack, I have a simple server that in nodejs.

var express = require('express');
var bodyParser = require('body-parser');
var request = require('request');
var app = express();
app.use(bodyParser());
app.use(express.static('public'));
app.use(express.static('node_modules'));

app.post('/api/searchjob', function (req, res) {
  res.json({data: "hello"});
});

app.get('/', function(req,res) {
  res.sendfile('public/index.html');
});

app.get('/*', function(req, res){
  res.redirect('/');
})

app.listen(process.env.PORT || 3000, function () {
  console.log('Example app listening on port 3000!')
});

I want the front end to also have access to some node_modules packages, what can i do? my index.html file is in "public" directory, the folder structure look like this:

├── README.md
├── index.js
├── node_modules
├── package.json
├── public
└── yarn.lock

I tried simply put the script tag in index.html, but doesn't work
>

Body:
I write this:

  app.use(express.static(path.join(__dirname, 'node_modules')));
  <script src="/vue2-google-maps/dist/vue-google-maps.js"></script>


来源: stackexchange

问:
How to Call Remote Method service?
I'm developing in app, in which user can add weather card to know city weather. I'm able to populate cities with Google Places Autocomplete API & also can able to retrieve weather of selected city.

But my problem is as weather data is not fixed, it changes over time. So how can I update weather data in background once user creates that weather card. I need to do updates in background, I think I've to use android service but don't know where to start.

答:
Ok, I will only guide you here,Nobody will provide you full code neither i will recommend anybody to do so, It is for your own good. You need to practice and explore the android programming world. So, here is my guidelines for you.

FirebaseJobDispatcher will fix you problem here. Before moving towards the FirebaseJobDispatcher you need to create a service class. For Services in android you should check this out.

Lets Talk about your service class.
Lets say it is FetchWeatherData class FetchWeatherData will extend to IntentService and will implement some methods. Inside onCreate you will write logic for fetching data from the server. Once you get the data from server you will store into the Database. Before storing into database you should check if database have the any record in it? If it does then delete it and store the new records in it.

Lets Talk about your Activity. Lets say it is ShowWeatherActivity. You will check first if you have any record in your database if there is no record then you will use FetchWeatherData to download weather data. Then show it.

Answer to your question can be very lengthy but i tried to explain as much which can help you get the idea of sync flow. Ofcourse your problem won't solve by reading this answer only. You need to go through these concepts

Services (Runs on main Thread)

Intent-Services (Runs in background)

Sqlite (For storing data)

I have added the helpful links in answer. Follow them. I hope this will help you somewhat.

ContentLicense: CC BY-SA 3.0

Title: How to Call Remote Method service?


问:
OnMarkerClick within a loop
While trying to develop a map app with multiple markers, that allows displaying a popup window with information when click on a marker ,I faced this problem when it comes to displaying the info (it has to be different info according to the loop order but it keeps demanding that the variables needs to be final ) but I keep having the same result for all popup windows (the last record's value) even if I make the variables global ,Sorry for my English and Please HELP.</p>

```<code>@Override
protected void onResume() {
super.onResume();
if(broadcastReceiver == null){
    broadcastReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {

Response.Listener<String> responseListener =new Response.Listener<String>() {

                @Override
                public void onResponse(String response) {
                    if(response== null){

                        Toast.makeText(getApplicationContext(),response,Toast.LENGTH_LONG);

                    }
                    else {
                        try {
                             jsonObject = new JSONObject(response);
                              jsonArray = jsonObject.getJSONArray("response");
                            int i=0 ;
                            int id,e;
                            Double lt,lg;
                            while (i<jsonArray.length()) {
                                 jo = jsonArray.getJSONObject(i);
                                e=  jo.getInt("etat");

                                id= jo.getInt("driver_id");

                                lt=jo.getDouble("latitude");

                                lg= jo.getDouble("longitude");

                                map.setOnMarkerClickListener(new GoogleMap.OnMarkerClickListener() {
                                    @Override
                                    public boolean onMarkerClick( Marker marker) {
                                        if(marker.getTitle() != null){
                                            return true;
                                        }else{

                                            layoutInflater = (LayoutInflater) getApplicationContext().getSystemService(LAYOUT_INFLATER_SERVICE);
                                            ViewGroup container = (ViewGroup) layoutInflater.inflate(R.layout.popup,null);

                                            popupWindow = new PopupWindow(container, 500,500,true);
                                            popupWindow.showAtLocation(relativeLayout, Gravity.NO_GRAVITY, 100,100);
                                            TextView tvNom= (TextView) container.findViewById(R.id.tvNom);

                                            tvNom.setText(id +"");

                                            container.setOnTouchListener(new View.OnTouchListener() {
                                                @Override
                                                public boolean onTouch(View view, MotionEvent motionEvent) {
                                                    popupWindow.dismiss();
                                                    return true;
                                                }
                                            });

                                            return false;}
                                    }
                                });
                                if(e==0) {
                                    marker = markerMap.get(d);
                                    if (marker != null) {
                                        marker.remove();
                                        markerMap.remove(d);
                                    } else {
                                        markerMap.remove(d);
                                    }

                                }
                                else{

                                    if (markerMap.containsKey(id)) {
                                        Intent intent= new Intent(MapActivity.this,InfoWindow.class);
                                        intent.putExtra("id",id+"");

                                        // Update the location.
                                        marker = markerMap.get(id);
                                        marker.remove();
                                        markerMap.remove(id); //added
                                        MarkerOptions markerOpt = new MarkerOptions()
                                                .position(new LatLng(lt,lg)).visible(true);
                                        marker = map.addMarker(markerOpt);
                                        markerMap.put(id, marker);

                                    } else {

                                        MarkerOptions markerOpt = new MarkerOptions()
                                                .position(new LatLng(lt, lg)).visible(true);

                                        marker = map.addMarker(markerOpt);
                                        markerMap.put(id, marker);

                                    }   }

                              i++;}

                        }catch (JSONException e) {
                            e.printStackTrace();
                            AlertDialog.Builder nbuilder = new AlertDialog.Builder(MapActivity.this);
                            nbuilder.setMessage("Error")
                                    .setNegativeButton("Retry", null)
                                    .create()
                                    .show();
                        }

                    }

                }
            };
            RetrieveCoordinates retrieve = new RetrieveCoordinates ( responseListener );
            RequestQueue queue = Volley.newRequestQueue(MapActivity.this);
            queue.add( retrieve);

        }
    };
}
registerReceiver(broadcastReceiver, new IntentFilter("location_update"));

}
</code>```

答:
As you've pointed out, all your listeners are added to the map object only. What the API provides for attaching different info on each marker object is a property called tag.

Use setTag(Object) on your marker object(s).

Wherever you've declared your markers, loop through them attaching your wanted tag:

```<code>for(int i=0; i < allMarkers.length; i++)
    marker.setTag();
</code>```

And then assign listener like:

```<code>map.setOnMarkerClickListener(new GoogleMap.OnMarkerClickListener() {
                                @Override
                                public boolean onMarkerClick( Marker marker) {
                                    if(marker.getTitle() != null){
                                        return true;
                                    }else{

                                        layoutInflater = (LayoutInflater) getApplicationContext().getSystemService(LAYOUT_INFLATER_SERVICE);
                                        ViewGroup container = (ViewGroup) layoutInflater.inflate(R.layout.popup,null);

                                        popupWindow = new PopupWindow(container, 500,500,true);
                                        popupWindow.showAtLocation(relativeLayout, Gravity.NO_GRAVITY, 100,100);
                                        TextView tvNom= (TextView) container.findViewById(R.id.tvNom);
                                        //---------retrieve this marker's tag - could be Integer or any other Object.
                                        int id = (Integer)marker.getTag();

                                        tvNom.setText(id +"");

                                        container.setOnTouchListener(new View.OnTouchListener() {
                                            @Override
                                            public boolean onTouch(View view, MotionEvent motionEvent) {
                                                popupWindow.dismiss();
                                                return true;
                                            }
                                        });

                                        return false;}
                                }
                            });
</code>```

Title: OnMarkerClick within a loop

Body:
While trying to develop a map app with multiple markers, that allows displaying a popup window with information when click on a marker ,I faced this problem when it comes to displaying the info (it has to be different info according to the loop order but it keeps demanding that the variables needs to be final ) but I keep having the same result for all popup windows (the last record's value) even if I make the variables global ,Sorry for my English and Please HELP.

@Override
protected void onResume() {
super.onResume();
if(broadcastReceiver == null){
    broadcastReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {

Response.Listener<String> responseListener =new Response.Listener<String>() {

                @Override
                public void onResponse(String response) {
                    if(response== null){

                        Toast.makeText(getApplicationContext(),response,Toast.LENGTH_LONG);

                    }
                    else {
                        try {
                             jsonObject = new JSONObject(response);
                              jsonArray = jsonObject.getJSONArray("response");
                            int i=0 ;
                            int id,e;
                            Double lt,lg;
                            while (i<jsonArray.length()) {
                                 jo = jsonArray.getJSONObject(i);
                                e=  jo.getInt("etat");

                                id= jo.getInt("driver_id");

                                lt=jo.getDouble("latitude");

                                lg= jo.getDouble("longitude");

                                map.setOnMarkerClickListener(new GoogleMap.OnMarkerClickListener() {
                                    @Override
                                    public boolean onMarkerClick( Marker marker) {
                                        if(marker.getTitle() != null){
                                            return true;
                                        }else{

                                            layoutInflater = (LayoutInflater) getApplicationContext().getSystemService(LAYOUT_INFLATER_SERVICE);
                                            ViewGroup container = (ViewGroup) layoutInflater.inflate(R.layout.popup,null);

                                            popupWindow = new PopupWindow(container, 500,500,true);
                                            popupWindow.showAtLocation(relativeLayout, Gravity.NO_GRAVITY, 100,100);
                                            TextView tvNom= (TextView) container.findViewById(R.id.tvNom);

                                            tvNom.setText(id +"");

                                            container.setOnTouchListener(new View.OnTouchListener() {
                                                @Override
                                                public boolean onTouch(View view, MotionEvent motionEvent) {
                                                    popupWindow.dismiss();
                                                    return true;
                                                }
                                            });

                                            return false;}
                                    }
                                });
                                if(e==0) {
                                    marker = markerMap.get(d);
                                    if (marker != null) {
                                        marker.remove();
                                        markerMap.remove(d);
                                    } else {
                                        markerMap.remove(d);
                                    }

                                }
                                else{

                                    if (markerMap.containsKey(id)) {
                                        Intent intent= new Intent(MapActivity.this,InfoWindow.class);
                                        intent.putExtra("id",id+"");

                                        // Update the location.
                                        marker = markerMap.get(id);
                                        marker.remove();
                                        markerMap.remove(id); //added
                                        MarkerOptions markerOpt = new MarkerOptions()
                                                .position(new LatLng(lt,lg)).visible(true);
                                        marker = map.addMarker(markerOpt);
                                        markerMap.put(id, marker);

                                    } else {

                                        MarkerOptions markerOpt = new MarkerOptions()
                                                .position(new LatLng(lt, lg)).visible(true);

                                        marker = map.addMarker(markerOpt);
                                        markerMap.put(id, marker);

                                    }   }

                              i++;}

                        }catch (JSONException e) {
                            e.printStackTrace();
                            AlertDialog.Builder nbuilder = new AlertDialog.Builder(MapActivity.this);
                            nbuilder.setMessage("Error")
                                    .setNegativeButton("Retry", null)
                                    .create()
                                    .show();
                        }

                    }

                }
            };
            RetrieveCoordinates retrieve = new RetrieveCoordinates ( responseListener );
            RequestQueue queue = Volley.newRequestQueue(MapActivity.this);
            queue.add( retrieve);

        }
    };
}
registerReceiver(broadcastReceiver, new IntentFilter("location_update"));

}

Body:
As you've pointed out, all your listeners are added to the map object only. What the API provides for attaching different info on each marker object is a property called tag.

Use setTag(Object) on your marker object(s).

Wherever you've declared your markers, loop through them attaching your wanted tag:

for(int i=0; i < allMarkers.length; i++)
    marker.setTag();

And then assign listener like:

map.setOnMarkerClickListener(new GoogleMap.OnMarkerClickListener() {
                                @Override
                                public boolean onMarkerClick( Marker marker) {
                                    if(marker.getTitle() != null){
                                        return true;
                                    }else{

                                        layoutInflater = (LayoutInflater) getApplicationContext().getSystemService(LAYOUT_INFLATER_SERVICE);
                                        ViewGroup container = (ViewGroup) layoutInflater.inflate(R.layout.popup,null);

                                        popupWindow = new PopupWindow(container, 500,500,true);
                                        popupWindow.showAtLocation(relativeLayout, Gravity.NO_GRAVITY, 100,100);
                                        TextView tvNom= (TextView) container.findViewById(R.id.tvNom);
                                        //---------retrieve this marker's tag - could be Integer or any other Object.
                                        int id = (Integer)marker.getTag();

                                        tvNom.setText(id +"");

                                        container.setOnTouchListener(new View.OnTouchListener() {
                                            @Override
                                            public boolean onTouch(View view, MotionEvent motionEvent) {
                                                popupWindow.dismiss();
                                                return true;
                                            }
                                        });

                                        return false;}
                                }
                            });


问:
Node.js encode ISO8859-1 to UTF-8
I have an application that allows users to persist strings to a database and those strings may contain emojis. The problem I have is an emoji such as  will get stored in MySQL as ðŸ˜Š

When I retrieve this string using a PHP MySQL client and render it in a web browser, it renders fine probably because the Content-Type is set to UTF-8. When I try to read the string in node.js, I get back what I think is the ISO8859-1 encoding a literal ðŸ˜Š. The charset on the table is set to latin1 and that's where I'm getting ISO8859-1 from.

What's the right way to encode the string in node.js so that I can see the emoji and not the encoding set by MySQL when I console.log the string?

答:
Maybe try to look at node-iconv.</p>

```<code>const iconv = new Iconv('ISO-8859-2', 'UTF-8');
const buffer = iconv.convert(something);
console.log(buffer);
console.log(buffer.toString('UTF8'));
</code>```

Title: Node.js encode ISO8859-1 to UTF-8

Body:
Maybe try to look at node-iconv.

const iconv = new Iconv('ISO-8859-2', 'UTF-8');
const buffer = iconv.convert(something);
console.log(buffer);
console.log(buffer.toString('UTF8'));


问:
Splitting large html file in several files
I want to preface the following by saying that I am pretty novice at html coding.

I am currently building a relatively large database (2000 entries) in excel and I want to make that database available on my website. What I started doing is converting the excel data to html data, and then using the DataTables jQuery plugin to convert it into a nice searchable html table. Here is what my code looks like:

```<code><html>
<head>

<link rel="stylesheet" type="text/css" href="DataTables-1.10.13/datatables.min.css"/>
<script type="text/javascript" src="https://cdn.datatables.net/v/dt/jq-2.2.4/dt-1.10.13/fh-3.1.2/datatables.min.js"></script>

<style>
  some style options
</style>

<script type="text/javascript" charset="utf-8">
  $(document).ready(function() {
    $('#booklist').dataTable({
    });
  });
</script>
</head>

<body>
<table id="booklist" class="display">
 Table data here
</table>
</body>
</html>
</code>```

I am still updating periodically the database, and having to copy and paste the new table data in the document every time is annoying, especially since it represents around 10000 lines.

I was wondering if there is a way to keep the table data in a separate file, say b.html, and importing it in such a way as it would be interpreted the same way as simply pasting the content of it directly where "Table data here" appears in my original code.

I tried using jQuery .load() function, but could not get it to work. Is it problematic that I am using CSS formatting?

Let me know what you think is the best solution to my problem.

Thank you!

答:
I was wondering if there is a way to keep the table data in a separate file, say b.html, and importing it in such a way as it would be interpreted the same way as simply pasting the content of it directly where "Table data here" appears in my original code.

You definitely have the right idea. You can make an HTTP request for HTML (or data of any kind really). There are multiple ways to do this but an easy way is to use jQuery's $(...).load('/...') function as you're doing now.

```<code>$( "#result" ).load( "test.html" );
</code>```

where result is the id of the div you want to populate with the value of test.html

This will make a request for test.html and put in the document in a div with the id result.

Under the hood, $(...).load() sends a request asynchronously and updates the element when the request completes. In addition to the URL, you should also provide a callback to run code after the load call has been finishes. Therefore, we can call DataTable() after the html loads.

// this URL would be an http://... in actual use
// table taken from w3schools
let url = "data:text/html,%3Ctable%20id%3D%22my-table%22%3E%0A%20%20%3Ctr%3E%0A%20%20%20%20%3Cth%3ECompany%3C%2Fth%3E%0A%20%20%20%20%3Cth%3EContact%3C%2Fth%3E%0A%20%20%20%20%3Cth%3ECountry%3C%2Fth%3E%0A%20%20%3C%2Ftr%3E%0A%20%20%3Ctr%3E%0A%20%20%20%20%3Ctd%3EAlfreds%20Futterkiste%3C%2Ftd%3E%0A%20%20%20%20%3Ctd%3EMaria%20Anders%3C%2Ftd%3E%0A%20%20%20%20%3Ctd%3EGermany%3C%2Ftd%3E%0A%20%20%3C%2Ftr%3E%0A%20%20%3Ctr%3E%0A%20%20%20%20%3Ctd%3ECentro%20comercial%20Moctezuma%3C%2Ftd%3E%0A%20%20%20%20%3Ctd%3EFrancisco%20Chang%3C%2Ftd%3E%0A%20%20%20%20%3Ctd%3EMexico%3C%2Ftd%3E%0A%20%20%3C%2Ftr%3E%0A%20%20%3Ctr%3E%0A%20%20%20%20%3Ctd%3EErnst%20Handel%3C%2Ftd%3E%0A%20%20%20%20%3Ctd%3ERoland%20Mendel%3C%2Ftd%3E%0A%20%20%20%20%3Ctd%3EAustria%3C%2Ftd%3E%0A%20%20%3C%2Ftr%3E%0A%20%20%3Ctr%3E%0A%20%20%20%20%3Ctd%3EIsland%20Trading%3C%2Ftd%3E%0A%20%20%20%20%3Ctd%3EHelen%20Bennett%3C%2Ftd%3E%0A%20%20%20%20%3Ctd%3EUK%3C%2Ftd%3E%0A%20%20%3C%2Ftr%3E%0A%20%20%3Ctr%3E%0A%20%20%20%20%3Ctd%3ELaughing%20Bacchus%20Winecellars%3C%2Ftd%3E%0A%20%20%20%20%3Ctd%3EYoshi%20Tannamuri%3C%2Ftd%3E%0A%20%20%20%20%3Ctd%3ECanada%3C%2Ftd%3E%0A%20%20%3C%2Ftr%3E%0A%20%20%3Ctr%3E%0A%20%20%20%20%3Ctd%3EMagazzini%20Alimentari%20Riuniti%3C%2Ftd%3E%0A%20%20%20%20%3Ctd%3EGiovanni%20Rovelli%3C%2Ftd%3E%0A%20%20%20%20%3Ctd%3EItaly%3C%2Ftd%3E%0A%20%20%3C%2Ftr%3E%0A%3C%2Ftable%3E";

// need to give `load` a callback so we can run code *after* the HTML loads
$('#result').load(url, function () {
  $('#my-table').DataTable();
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link href="https://cdn.datatables.net/1.10.13/css/jquery.dataTables.min.css" rel="stylesheet"/>
<script src="https://cdn.datatables.net/1.10.13/js/jquery.dataTables.min.js"></script>

<div>
  <div>result get populated below:</div>
  <div id="result">
  </div>
</div></code>```

Let me know what you think is the best solution to my problem.

If you have a giant spreadsheet, you could probably save that as a CSV and use a CSV parser to transform each row in the table to a row in html. This involves:

an ajax request with jquery (or fetch) for the data as CSV

parsing it into arrays

transforming that to rows of HTML and adding them to the document

then finally calling DataTables()

But if your database is relatively large, then you should try going for dynamic pagination which is hard without server code (nodejs, php, java etc).

Body:
I want to preface the following by saying that I am pretty novice at html coding.

I am currently building a relatively large database (2000 entries) in excel and I want to make that database available on my website. What I started doing is converting the excel data to html data, and then using the DataTables jQuery plugin to convert it into a nice searchable html table. Here is what my code looks like:

<link rel="stylesheet" type="text/css" href="DataTables-1.10.13/datatables.min.css"/>

 Table data here

I am still updating periodically the database, and having to copy and paste the new table data in the document every time is annoying, especially since it represents around 10000 lines.

I was wondering if there is a way to keep the table data in a separate file, say b.html, and importing it in such a way as it would be interpreted the same way as simply pasting the content of it directly where "Table data here" appears in my original code.

I tried using jQuery .load() function, but could not get it to work. Is it problematic that I am using CSS formatting?

Let me know what you think is the best solution to my problem.

Thank you!

Body:
I was wondering if there is a way to keep the table data in a separate file, say b.html, and importing it in such a way as it would be interpreted the same way as simply pasting the content of it directly where "Table data here" appears in my original code.

You definitely have the right idea. You can make an HTTP request for HTML (or data of any kind really). There are multiple ways to do this but an easy way is to use jQuery's $(...).load('/...') function as you're doing now.

$( "#result" ).load( "test.html" );

where result is the id of the div you want to populate with the value of test.html

This will make a request for test.html and put in the document in a div with the id result.

Under the hood, $(...).load() sends a request asynchronously and updates the element when the request completes. In addition to the URL, you should also provide a callback to run code after the load call has been finishes. Therefore, we can call DataTable() after the html loads.

// this URL would be an http://... in actual use
// table taken from w3schools
let url = "data:text/html,%3Ctable%20id%3D%22my-table%22%3E%0A%20%20%3Ctr%3E%0A%20%20%20%20%3Cth%3ECompany%3C%2Fth%3E%0A%20%20%20%20%3Cth%3EContact%3C%2Fth%3E%0A%20%20%20%20%3Cth%3ECountry%3C%2Fth%3E%0A%20%20%3C%2Ftr%3E%0A%20%20%3Ctr%3E%0A%20%20%20%20%3Ctd%3EAlfreds%20Futterkiste%3C%2Ftd%3E%0A%20%20%20%20%3Ctd%3EMaria%20Anders%3C%2Ftd%3E%0A%20%20%20%20%3Ctd%3EGermany%3C%2Ftd%3E%0A%20%20%3C%2Ftr%3E%0A%20%20%3Ctr%3E%0A%20%20%20%20%3Ctd%3ECentro%20comercial%20Moctezuma%3C%2Ftd%3E%0A%20%20%20%20%3Ctd%3EFrancisco%20Chang%3C%2Ftd%3E%0A%20%20%20%20%3Ctd%3EMexico%3C%2Ftd%3E%0A%20%20%3C%2Ftr%3E%0A%20%20%3Ctr%3E%0A%20%20%20%20%3Ctd%3EErnst%20Handel%3C%2Ftd%3E%0A%20%20%20%20%3Ctd%3ERoland%20Mendel%3C%2Ftd%3E%0A%20%20%20%20%3Ctd%3EAustria%3C%2Ftd%3E%0A%20%20%3C%2Ftr%3E%0A%20%20%3Ctr%3E%0A%20%20%20%20%3Ctd%3EIsland%20Trading%3C%2Ftd%3E%0A%20%20%20%20%3Ctd%3EHelen%20Bennett%3C%2Ftd%3E%0A%20%20%20%20%3Ctd%3EUK%3C%2Ftd%3E%0A%20%20%3C%2Ftr%3E%0A%20%20%3Ctr%3E%0A%20%20%20%20%3Ctd%3ELaughing%20Bacchus%20Winecellars%3C%2Ftd%3E%0A%20%20%20%20%3Ctd%3EYoshi%20Tannamuri%3C%2Ftd%3E%0A%20%20%20%20%3Ctd%3ECanada%3C%2Ftd%3E%0A%20%20%3C%2Ftr%3E%0A%20%20%3Ctr%3E%0A%20%20%20%20%3Ctd%3EMagazzini%20Alimentari%20Riuniti%3C%2Ftd%3E%0A%20%20%20%20%3Ctd%3EGiovanni%20Rovelli%3C%2Ftd%3E%0A%20%20%20%20%3Ctd%3EItaly%3C%2Ftd%3E%0A%20%20%3C%2Ftr%3E%0A%3C%2Ftable%3E";

// need to give `load` a callback so we can run code *after* the HTML loads
$('#result').load(url, function () {
  $('#my-table').DataTable();
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link href="https://cdn.datatables.net/1.10.13/css/jquery.dataTables.min.css" rel="stylesheet"/>
<script src="https://cdn.datatables.net/1.10.13/js/jquery.dataTables.min.js"></script>

<div>
  <div>result get populated below:</div>
  <div id="result">
  </div>
</div>

Let me know what you think is the best solution to my problem.

If you have a giant spreadsheet, you could probably save that as a CSV and use a CSV parser to transform each row in the table to a row in html. This involves:

an ajax request with jquery (or fetch) for the data as CSV

parsing it into arrays

transforming that to rows of HTML and adding them to the document

then finally calling DataTables()

But if your database is relatively large, then you should try going for dynamic pagination which is hard without server code (nodejs, php, java etc).


问:
React-Bootstrap DropDown Button pullRight/Left
I am using react bootstrap dropdown menu https://react-bootstrap.github.io/components.html#btn-dropdowns. pullRight and pullLeft allows us to align the position of the menu .

I do not know the width of the menu items initially. I need to calculate on run time and conditionally align the dropdown items (pass the props pullLeft/pullRight to DropdownButton) . The children (MenuItem) are visible none when the drop down loads, only on button click I get the height.

My question is that, do I need to calculate the height on click and re-render the entire DropdownButton component? Any better way to pass the prop to DropdownButton component without re rendering?

```<code>      <DropdownButton
          buttonClassName={buttonAttrs.className}
          pullLeft
          onClick={this.callToggle}
          bsStyle={(metadata.displayStyle === 'button' ? 'button' : 'link' )}
          noCaret
          title={title}
          key={"0"}
          id={"test"}
      >
          {this.renderChildren().map((child, index) => {
              return (<MenuItem eventKey={index}>{child}</MenuItem>)
          })}
     </DropdownButton> : <button {...buttonAttrs} ref="button">
</code>```

答:
Live demo:

http://codepen.io/blackmiaool/pen/dvwxzN

css

```<code>.dropdown:not(.open) ul.dropdown-menu{
    display:block !important;
    opacity:0;
    pointer-events:none;
}
</code>```

part of jsx

```<code><DropdownButton ref="dropdown"
      onClick={()=>{
        const dir=Math.random()>0.5
        console.log(dir)
        console.log(ReactDOM.findDOMNode(this).querySelector("ul").clientWidth);
        this.setState({
          dir:dir
        })

      }}
      pullLeft={this.state.dir}
      pullRight={this.state.dir}
</code>```

Why?

To get the correct width of ul.dropdown-menu, you should show the menu first. But you want to get the width before showing it, so just set its opacity to 0 and pointer-events to none. In this way, the menu is hidden and can be measured.

I don't know how you want to set the pullLeft and pullRight, so I just  set the direction as Math.random() and output the direction and the width to the console for checking.

Body:
I am using react bootstrap dropdown menu https://react-bootstrap.github.io/components.html#btn-dropdowns. pullRight and pullLeft allows us to align the position of the menu .

I do not know the width of the menu items initially. I need to calculate on run time and conditionally align the dropdown items (pass the props pullLeft/pullRight to DropdownButton) . The children (MenuItem) are visible none when the drop down loads, only on button click I get the height.

My question is that, do I need to calculate the height on click and re-render the entire DropdownButton component? Any better way to pass the prop to DropdownButton component without re rendering?

      <DropdownButton
          buttonClassName={buttonAttrs.className}
          pullLeft
          onClick={this.callToggle}
          bsStyle={(metadata.displayStyle === 'button' ? 'button' : 'link' )}
          noCaret
          title={title}
          key={"0"}
          id={"test"}
      >
          {this.renderChildren().map((child, index) => {
              return (<MenuItem eventKey={index}>{child}</MenuItem>)
          })}
     </DropdownButton> : <button {...buttonAttrs} ref="button">

Body:
Live demo:

http://codepen.io/blackmiaool/pen/dvwxzN

css

.dropdown:not(.open) ul.dropdown-menu{
    display:block !important;
    opacity:0;
    pointer-events:none;
}

part of jsx

<DropdownButton ref="dropdown"
      onClick={()=>{
        const dir=Math.random()>0.5
        console.log(dir)
        console.log(ReactDOM.findDOMNode(this).querySelector("ul").clientWidth);
        this.setState({
          dir:dir
        })

      }}
      pullLeft={this.state.dir}
      pullRight={this.state.dir}

Why?

To get the correct width of ul.dropdown-menu, you should show the menu first. But you want to get the width before showing it, so just set its opacity to 0 and pointer-events to none. In this way, the menu is hidden and can be measured.

I don't know how you want to set the pullLeft and pullRight, so I just  set the direction as Math.random() and output the direction and the width to the console for checking.


问:
Character Segmentation for Handwriting Recognition
I am trying to read the handwritten documents. For which I am going to segment the characters and then OCR/ICR the characters thus segmented.

I want results like this! Although this is a very trivial case. The handwriting may be cursive, the single stroke can be used to segment characters but it doesn't always work.

答:
After a lot of reading and researching, realized that I was tackling the problem in a wrong way. For Handwriting recognition it's tough to segment characters and then recognize them.

As the paradox goes

A letter can't be segmented before having recognized and can't be recognized before having segmented.

So the correct way is to treat the problem as "Supervised Sequence Labelling".
What distinguishes such problems from the traditional
framework of supervised pattern classication is that the individual data points
cannot be assumed to be independent. Instead, both the inputs and the labels
form strongly correlated sequences.

I would suggest the paper here using Multi Dimensional RNN and CTC.

ContentLicense: CC BY-SA 4.0


问:
Java Concurrent Modification Error HashMap
Fun question here. Why does the first version of this throw a concurrent modification error, while the second does not. Should this happen?</p>

```<code>Map<String,Integer> map = new HashMap<>();
... // Populate the map
for(String key : map.keySet()){
    if(map.get(key) < 50){
        map.remove(key);
    }
}

Map<String,Integer> map = new HashMap<>();
... // Populate the map
for(String key : new ArrayList<String>(map.keySet())){
    if(map.get(key) < 50){
        map.remove(key);
    }
}
</code>```

答:
In the first case you get a concurrentModificationException because there's a modification count associated with iteration in terms of internal implementation. If the modification count changes during iteration a concurrentModificaitonException is thrown.

The solution is to use iterator.remove() instead of removing an element directly from the map.

In the second case, you are iterating not the map but a different collection while removing an element from the map. In this case, the modification count never changes during iteration because you are iterating a different collection.

Also, in a multithreaded environment always use synchronized on a collection that represents shared mutable state in a class before iterating it otherwise you can get a concurrentModificationException .

In a multithreaded environment, your second solution would not be correct because you haven't synchronized the statement where you transfer the keyset of the original map to a new collection. So there's potential to get a concurrentModificationException. Use a ConcurrentHashMap in a multithreaded environment while knowing that not every operation or set of operations on a ConcurrentHashMap is threadsafe by default.

Body:
Fun question here. Why does the first version of this throw a concurrent modification error, while the second does not. Should this happen?

Map<String,Integer> map = new HashMap<>();
... // Populate the map
for(String key : map.keySet()){
    if(map.get(key) < 50){
        map.remove(key);
    }
}

Map<String,Integer> map = new HashMap<>();
... // Populate the map
for(String key : new ArrayList<String>(map.keySet())){
    if(map.get(key) < 50){
        map.remove(key);
    }
}


问:
Process Array in parallel using GCD
I have a large array that I would like to process by handing slices of it to a few asynchronous tasks. As a proof of concept, I have the written the following code:

```<code>class TestParallelArrayProcessing {
    let array: [Int]
    var summary: [Int]

    init() {
        array = Array<Int>(count: 500000, repeatedValue: 0)
        for i in 0 ..< 500000 {
            array[i] = Int(arc4random_uniform(10))
        }
        summary = Array<Int>(count: 10, repeatedValue: 0)
    }

    func calcSummary() {
        let group = dispatch_group_create()
        let queue = dispatch_get_global_queue(QOS_CLASS_USER_INITIATED, 0)

        for i in 0 ..< 10 {
            dispatch_group_async(group, queue, {
                let base = i * 50000
                for x in base ..< base + 50000 {
                    self.summary[i] += self.array[x]
                }
            })
        }
        dispatch_group_notify(group, queue, {
            println(self.summary)
        })
    }
}
</code>```

After init(), array will be initialized with random integers between 0 and 9.

The calcSummary function dispatches 10 tasks that take disjoint chunks of 50000 items from array and add them up, using their respective slot in summary as an accummulator.

This program crashes at the self.summary[i] += self.array[x] line. The error is:

```<code> EXC_BAD_INSTRUCTION (code = EXC_I386_INVOP).
</code>```

I can see, in the debugger, that it has managed to iterate a few times before crashing, and that the variables, at the time of the crash, have values within correct bounds.

I have read that EXC_I386_INVOP can happen when trying to access an object that has already been released. I wonder if this has anything to do with Swift making a copy of the array if it is modified, and, if so, how to avoid it.

答:
You can also use concurrentPerform(iterations: Int, execute work: (Int) -> Swift.Void) (since Swift 3).

It has a much simpler syntax and will wait for all threads to finalise before returning.:

```<code>DispatchQueue.concurrentPerform(iterations: iterations) { i in
    performOperation(i)
}
</code>```

Title: Process Array in parallel using GCD

Body:
I have a large array that I would like to process by handing slices of it to a few asynchronous tasks. As a proof of concept, I have the written the following code:

class TestParallelArrayProcessing {
    let array: [Int]
    var summary: [Int]

    init() {
        array = Array<Int>(count: 500000, repeatedValue: 0)
        for i in 0 ..< 500000 {
            array[i] = Int(arc4random_uniform(10))
        }
        summary = Array<Int>(count: 10, repeatedValue: 0)
    }

    func calcSummary() {
        let group = dispatch_group_create()
        let queue = dispatch_get_global_queue(QOS_CLASS_USER_INITIATED, 0)

        for i in 0 ..< 10 {
            dispatch_group_async(group, queue, {
                let base = i * 50000
                for x in base ..< base + 50000 {
                    self.summary[i] += self.array[x]
                }
            })
        }
        dispatch_group_notify(group, queue, {
            println(self.summary)
        })
    }
}

After init(), array will be initialized with random integers between 0 and 9.

The calcSummary function dispatches 10 tasks that take disjoint chunks of 50000 items from array and add them up, using their respective slot in summary as an accummulator.

This program crashes at the self.summary[i] += self.array[x] line. The error is:

 EXC_BAD_INSTRUCTION (code = EXC_I386_INVOP).

I can see, in the debugger, that it has managed to iterate a few times before crashing, and that the variables, at the time of the crash, have values within correct bounds.

I have read that EXC_I386_INVOP can happen when trying to access an object that has already been released. I wonder if this has anything to do with Swift making a copy of the array if it is modified, and, if so, how to avoid it.

Body:
You can also use concurrentPerform(iterations: Int, execute work: (Int) -> Swift.Void) (since Swift 3).

It has a much simpler syntax and will wait for all threads to finalise before returning.:

DispatchQueue.concurrentPerform(iterations: iterations) { i in
    performOperation(i)
}


问:
Magento: Custom module works in localhost but not in server
Using magento 1.9 I have a custom module that should appear in the product view, it works fine on the xampp server in my localhost, but when i upload the module files to the server it doesnt work, despite it appear as enable in the System>Confinguration on Disable Modules Output.
Is it something on my code or is the server?

This is the in the csharls_productmeasure.xml inside app\etc\modules

```<code><?xml version="1.0" encoding="UTF-8"?>
    <config>
        <modules>
            <csharls_productmeasure>
                <active>true</active>
                <codePool>local</codePool>
            </csharls_productmeasure>
        </modules>
    </config>
</code>```

This is the config.xml inside of app\code\local\csharls\productmeasure\etc

```<code><?xml version="1.0" encoding="UTF-8"?>
 <config>
    <modules>
        <csharls_productmeasure>
        <version>0.0.1</version>
        </csharls_productmeasure>
    </modules>
    <global>
        <models>
            <productmeasure>
                <class>csharls_productmeasure_Model</class>
            </productmeasure>
        </models>
        <blocks>
            <productmeasure>
                <class>csharls_productmeasure_Block</class>
            </productmeasure>
        </blocks>
        <events>
          <sales_quote_add_item>
           <observers>
             <productmeasure>
                  <type>singleton</type>
                  <class>csharls_productmeasure_Model_Observer</class>
                    <method>updatePrice</method>
                  </productmeasure>
              </observers>
           </sales_quote_add_item>
       </events>
    </global>
    <frontend>
      <routers>
          <productmeasure>
                <use>standard</use>
                <args>
                    <module>csharls_productmeasure</module>
                    <frontName>productmeasure</frontName>
                </args>
            </productmeasure>
        </routers>
        <layout>
            <updates>
                <csharls_productmeasure>
                    <file>csharls_productmeasure.xml</file>
                </csharls_productmeasure>
            </updates>
        </layout>
    </frontend>
</config>
</code>```

答:
Step 1 : Please permission your file 755 in server

Step 2 : Check your php version local & live are same or not

Step 3 : Refresh the cache

Body:
Using magento 1.9 I have a custom module that should appear in the product view, it works fine on the xampp server in my localhost, but when i upload the module files to the server it doesnt work, despite it appear as enable in the System>Confinguration on Disable Modules Output.
Is it something on my code or is the server?

This is the in the csharls_productmeasure.xml inside app\etc\modules

<?xml version="1.0" encoding="UTF-8"?>
    <config>
        <modules>
            <csharls_productmeasure>
                <active>true</active>
                <codePool>local</codePool>
            </csharls_productmeasure>
        </modules>
    </config>

This is the config.xml inside of app\code\local\csharls\productmeasure\etc

<?xml version="1.0" encoding="UTF-8"?>
 <config>
    <modules>
        <csharls_productmeasure>
        <version>0.0.1</version>
        </csharls_productmeasure>
    </modules>
    <global>
        <models>
            <productmeasure>
                <class>csharls_productmeasure_Model</class>
            </productmeasure>
        </models>
        <blocks>
            <productmeasure>
                <class>csharls_productmeasure_Block</class>
            </productmeasure>
        </blocks>
        <events>
          <sales_quote_add_item>
           <observers>
             <productmeasure>
                  <type>singleton</type>
                  <class>csharls_productmeasure_Model_Observer</class>
                    <method>updatePrice</method>
                  </productmeasure>
              </observers>
           </sales_quote_add_item>
       </events>
    </global>
    <frontend>
      <routers>
          <productmeasure>
                <use>standard</use>
                <args>
                    <module>csharls_productmeasure</module>
                    <frontName>productmeasure</frontName>
                </args>
            </productmeasure>
        </routers>
        <layout>
            <updates>
                <csharls_productmeasure>
                    <file>csharls_productmeasure.xml</file>
                </csharls_productmeasure>
            </updates>
        </layout>
    </frontend>
</config>


问:
How to get system date and time instead of internet's PHP
I am working on a website which reserves lot for clients. Lot reserved has expiration date. In localhost, everything works fine. The system date and time is what my website is getting. But when I tested it online (I uploaded my website) it's not getting the system date and time. </p>

```<code>$d = date('d M Y h:i A'); //TODAYS DATE---> this doesnt change when I change my PC's date and time

$curdate = strtotime($d)*1000;
echo $d;

$sql = "SELECT * FROM reservation";
$res = $conn->query($sql);

foreach ($res as $row) {
    $exp = strtotime($row['expiration'])*1000;
    $lot = $row['lot'];
    $sqli = "SELECT * FROM reservation WHERE ".$curdate." >= ".$exp." AND status='reserved'";
    $resu = $conn->query($sqli);
    foreach ($resu as $ro) {
        $id = $ro['reserve_id'];
        $sl = "DELETE FROM reservation WHERE reserve_id='$id'";
        $conn->query($sl);
        $l = substr($ro['lot'], 1);
        echo "<script>$(document).find('#_".$l."').css({'fill':'#848484'});</script>";
    }

}
</code>```

答:
PHP uses the time for the machine it's running on "Server", still you can get the time from the client machine using javascript/jquery -ajax call like :</p>

```<code>var TimeNow = new Date();
$.ajax({
    url : url,
    data : {date : TimeNow}
});
</code>```

Body:
I am working on a website which reserves lot for clients. Lot reserved has expiration date. In localhost, everything works fine. The system date and time is what my website is getting. But when I tested it online (I uploaded my website) it's not getting the system date and time.

$d = date('d M Y h:i A'); //TODAYS DATE---> this doesnt change when I change my PC's date and time

$curdate = strtotime($d)*1000;
echo $d;

$sql = "SELECT * FROM reservation";
$res = $conn->query($sql);

foreach ($res as $row) {
    $exp = strtotime($row['expiration'])*1000;
    $lot = $row['lot'];
    $sqli = "SELECT * FROM reservation WHERE ".$curdate." >= ".$exp." AND status='reserved'";
    $resu = $conn->query($sqli);
    foreach ($resu as $ro) {
        $id = $ro['reserve_id'];
        $sl = "DELETE FROM reservation WHERE reserve_id='$id'";
        $conn->query($sl);
        $l = substr($ro['lot'], 1);
        echo "";
    }

}

Body:
PHP uses the time for the machine it's running on "Server", still you can get the time from the client machine using javascript/jquery -ajax call like :

var TimeNow = new Date();
$.ajax({
    url : url,
    data : {date : TimeNow}
});


问:
What system resources are used when a web part is closed instead of deleted?
I'm trying to figure out what exactly the difference is between a web part that is open on the page versus a web part that has been closed instead of deleted.

I can only find this article on technet which has this interesting quote:

Note that in SharePoint Server 2010, a
  closed Web part no longer consumes the
  same system resources as open Web
  parts.

My question has two parts:

What is the difference between an open web part and a closed one? (Besides the contents being visible of course)

In a custom web part, is there a best practice for preventing the web part from executing in the event that a user closes it?

I am looking for answers regarding SharePoint 2007 MOSS or WSS.

答:
in SharePoint 2007 Open web part and close web parts differ only by the contents is not visible in case of closed web part

i don't think you can do any thing in case of MOSS 2007

ContentLicense: CC BY-SA 2.5


问:
How to scrape a Table with Selenium and Python 3.6 on windows 10
I am trying my hard to scrape data from a website and write data to CSV file.
then after writing to file change page to continue the process till last page.
i am getting data from first row only. I am doing something wrong .
Kindly correct me.

```<code>import re
import os
import csv
import sys
import time
from selenium import webdriver
from selenium.webdriver.support.ui import Select
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.common.exceptions import TimeoutException
from selenium.webdriver.common.action_chains import ActionChains
driver =webdriver.PhantomJS()
driver.get('http://www.census2011.co.in/district.php')
driver.maximize_window()

select = Select(driver.find_element_by_xpath(".//div[@id='DataTables_Table_0_length']/label/div/select") )
select.select_by_visible_text("100")

for i in range(1,101,1) :
    sNo = driver.find_element_by_xpath("//table[@id='DataTables_Table_0']/tbody/tr['+str(i)+']/td[1]")
    district = driver.find_element_by_xpath("//table[@id='DataTables_Table_0']/tbody/tr['+str(i)+']/td[2]/a")
    districtName = driver.find_element_by_xpath("//table[@id='DataTables_Table_0']/tbody/tr['+str(i)+']/td[2]").text
    state= driver.find_element_by_xpath("//table[@id='DataTables_Table_0']/tbody/tr['+str(i)+']/td[3]").text
    population= driver.find_element_by_xpath("//table[@id='DataTables_Table_0']/tbody/tr['+str(i)+']/td[4]").text
    growth= driver.find_element_by_xpath("//table[@id='DataTables_Table_0']/tbody/tr['+str(i)+']/td[5]").text
    sexRatio= driver.find_element_by_xpath("//table[@id='DataTables_Table_0']/tbody/tr['+str(i)+']/td[6]").text
    districtLink = district.get_attribute("href")
    print(districtName,state,population,growth,sexRatio,districtLink)

with open(r"D:\python36_files\censusDistrictData.csv",'a',newline = "\n", encoding='utf-8') as csvfile:
    fieldnames = ["DistrictName", "State", "Population",  "Growth","SexRatio","DistrictLink"]
    writer = csv.DictWriter(csvfile, fieldnames = ["DistrictName", "State", "Population",  "Growth","SexRatio", "DistrictLink"],restval='none',delimiter = ';')
    writer.writerow({'DistrictName': districtName, 'State': state, 'Population':population,  'Growth':growth, 'SexRatio':sexRatio, 'DistrictLink': districtLink})

print ("OK")
driver.quit()
</code>```

and another question:
I have tried by scraping CSS Selector but not able to put a separator after col.

```<code>import re
import os
import csv
import sys
import time
from selenium import webdriver
from selenium.webdriver.support.ui import Select
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.common.exceptions import TimeoutException
from selenium.webdriver.common.action_chains import ActionChains

driver =webdriver.PhantomJS()
driver.get('http://www.census2011.co.in/district.php')
driver.maximize_window()

select = Select(driver.find_element_by_xpath(".//div[@id='DataTables_Table_0_length']/label/div/select") )
select.select_by_visible_text("100")
districtTable = driver.find_elements_by_css_selector("#DataTables_Table_0")
for row in districtTable:
    print(row.text)
with open(r"D:\python36_files\censusDistrictData1.csv",'a',newline = "\n", encoding='utf-8') as csvfile:
    writer = csv.DictWriter(csvfile, fieldnames = ["Row"],restval='none',delimiter = ';')
    writer.writerow({"Row":row.text}) #pl.let me know how to insert ; after a data to a csvfile

print ("OK")
driver.quit()
</code>```

答:
This question was solved by me but not the right way in Python, Kindly guide me in details.</p>

```<code>import re
import os
import csv
import sys
import time
from selenium import webdriver
from selenium.webdriver.support.ui import Select
from  selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.common.exceptions import TimeoutException
from selenium.webdriver.common.action_chains import ActionChains
driver = webdriver.PhantomJS()
driver.get('http://www.census2011.co.in/district.php')
driver.maximize_window()
select =     Select(driver.find_element_by_xpath(".//div[@id='DataTables_Table_0_length']/label/div/select") )
select.select_by_visible_text("100")
i = 0
for i in range(0, 100):
    i += 1
    baseXpath = "//table[@id='DataTables_Table_0']/tbody/tr["
    row = str(i)
    trXpath = baseXpath + row + ']'
    sNo = driver.find_element_by_xpath(trXpath + "/td[1]")
    districtLink = driver.find_element_by_xpath(trXpath + "/td[2]/a").get_attribute("href")
    districtName = driver.find_element_by_xpath(trXpath + "/td[2]").text
    state = driver.find_element_by_xpath(trXpath + "/td[3]").text
    population = driver.find_element_by_xpath(trXpath + "/td[4]").text
    growth = driver.find_element_by_xpath(trXpath + "/td[5]").text
    sexRatio = driver.find_element_by_xpath(trXpath + "/td[6]").text
    print(districtName,';', state,';', population,';', growth,';', sexRatio)
    with open(r"D:\python36_files\censusDistrictData.csv",'a',newline = "\n", encoding='utf-8') as csvfile:
        fieldnames = ["DistrictName", "State", "Population",  "Growth","SexRatio","DistrictLink"]
        writer = csv.DictWriter(csvfile, fieldnames = ["DistrictName", "State", "Population",  "Growth","SexRatio", "DistrictLink"],restval='none',delimiter = ';')
        writer.writerow({'DistrictName': districtName, 'State': state, 'Population':population,  'Growth':growth, 'SexRatio':sexRatio, 'DistrictLink': districtLink})

print ("OK")
driver.quit()
</code>```

Body:
I am trying my hard to scrape data from a website and write data to CSV file.
then after writing to file change page to continue the process till last page.
i am getting data from first row only. I am doing something wrong .
Kindly correct me.

import re
import os
import csv
import sys
import time
from selenium import webdriver
from selenium.webdriver.support.ui import Select
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.common.exceptions import TimeoutException
from selenium.webdriver.common.action_chains import ActionChains
driver =webdriver.PhantomJS()
driver.get('http://www.census2011.co.in/district.php')
driver.maximize_window()

select = Select(driver.find_element_by_xpath(".//div[@id='DataTables_Table_0_length']/label/div/select") )
select.select_by_visible_text("100")

for i in range(1,101,1) :
    sNo = driver.find_element_by_xpath("//table[@id='DataTables_Table_0']/tbody/tr['+str(i)+']/td[1]")
    district = driver.find_element_by_xpath("//table[@id='DataTables_Table_0']/tbody/tr['+str(i)+']/td[2]/a")
    districtName = driver.find_element_by_xpath("//table[@id='DataTables_Table_0']/tbody/tr['+str(i)+']/td[2]").text
    state= driver.find_element_by_xpath("//table[@id='DataTables_Table_0']/tbody/tr['+str(i)+']/td[3]").text
    population= driver.find_element_by_xpath("//table[@id='DataTables_Table_0']/tbody/tr['+str(i)+']/td[4]").text
    growth= driver.find_element_by_xpath("//table[@id='DataTables_Table_0']/tbody/tr['+str(i)+']/td[5]").text
    sexRatio= driver.find_element_by_xpath("//table[@id='DataTables_Table_0']/tbody/tr['+str(i)+']/td[6]").text
    districtLink = district.get_attribute("href")
    print(districtName,state,population,growth,sexRatio,districtLink)

with open(r"D:\python36_files\censusDistrictData.csv",'a',newline = "\n", encoding='utf-8') as csvfile:
    fieldnames = ["DistrictName", "State", "Population",  "Growth","SexRatio","DistrictLink"]
    writer = csv.DictWriter(csvfile, fieldnames = ["DistrictName", "State", "Population",  "Growth","SexRatio", "DistrictLink"],restval='none',delimiter = ';')
    writer.writerow({'DistrictName': districtName, 'State': state, 'Population':population,  'Growth':growth, 'SexRatio':sexRatio, 'DistrictLink': districtLink})

print ("OK")
driver.quit()

and another question:
I have tried by scraping CSS Selector but not able to put a separator after col.

import re
import os
import csv
import sys
import time
from selenium import webdriver
from selenium.webdriver.support.ui import Select
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.common.exceptions import TimeoutException
from selenium.webdriver.common.action_chains import ActionChains

driver =webdriver.PhantomJS()
driver.get('http://www.census2011.co.in/district.php')
driver.maximize_window()

select = Select(driver.find_element_by_xpath(".//div[@id='DataTables_Table_0_length']/label/div/select") )
select.select_by_visible_text("100")
districtTable = driver.find_elements_by_css_selector("#DataTables_Table_0")
for row in districtTable:
    print(row.text)
with open(r"D:\python36_files\censusDistrictData1.csv",'a',newline = "\n", encoding='utf-8') as csvfile:
    writer = csv.DictWriter(csvfile, fieldnames = ["Row"],restval='none',delimiter = ';')
    writer.writerow({"Row":row.text}) #pl.let me know how to insert ; after a data to a csvfile

print ("OK")
driver.quit()

Body:
This question was solved by me but not the right way in Python, Kindly guide me in details.

import re
import os
import csv
import sys
import time
from selenium import webdriver
from selenium.webdriver.support.ui import Select
from  selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.common.exceptions import TimeoutException
from selenium.webdriver.common.action_chains import ActionChains
driver = webdriver.PhantomJS()
driver.get('http://www.census2011.co.in/district.php')
driver.maximize_window()
select =     Select(driver.find_element_by_xpath(".//div[@id='DataTables_Table_0_length']/label/div/select") )
select.select_by_visible_text("100")
i = 0
for i in range(0, 100):
    i += 1
    baseXpath = "//table[@id='DataTables_Table_0']/tbody/tr["
    row = str(i)
    trXpath = baseXpath + row + ']'
    sNo = driver.find_element_by_xpath(trXpath + "/td[1]")
    districtLink = driver.find_element_by_xpath(trXpath + "/td[2]/a").get_attribute("href")
    districtName = driver.find_element_by_xpath(trXpath + "/td[2]").text
    state = driver.find_element_by_xpath(trXpath + "/td[3]").text
    population = driver.find_element_by_xpath(trXpath + "/td[4]").text
    growth = driver.find_element_by_xpath(trXpath + "/td[5]").text
    sexRatio = driver.find_element_by_xpath(trXpath + "/td[6]").text
    print(districtName,';', state,';', population,';', growth,';', sexRatio)
    with open(r"D:\python36_files\censusDistrictData.csv",'a',newline = "\n", encoding='utf-8') as csvfile:
        fieldnames = ["DistrictName", "State", "Population",  "Growth","SexRatio","DistrictLink"]
        writer = csv.DictWriter(csvfile, fieldnames = ["DistrictName", "State", "Population",  "Growth","SexRatio", "DistrictLink"],restval='none',delimiter = ';')
        writer.writerow({'DistrictName': districtName, 'State': state, 'Population':population,  'Growth':growth, 'SexRatio':sexRatio, 'DistrictLink': districtLink})

print ("OK")
driver.quit()


问:
Find UTF-16 code for a character in python3
I have a file with data in Chinese language for instance i have a character 攻 and I want to find the utf-16 code of this character. how can i find it in python 3?</p>

答:
Use the ord function.

```<code>print(hex(ord(u'攻')))
</code>```

prints 0x653b

Body:
Use the ord function.

print(hex(ord(u'攻')))

prints 0x653b


问:
unable to create express-generator project using webstorm
I am new to nodejs. while creating nodejs express-generator form webstorm getting following error:</p>

```<code>Error creating Node.js Express App. Cannot find /tmp/intellij-express-generator253/node_modules/express-generator/bin/express
</code>```

答:
```<code>  npm install -g express-generator
</code>```

Then, the webstorm will work!

Body:
I am new to nodejs. while creating nodejs express-generator form webstorm getting following error:

Error creating Node.js Express App. Cannot find /tmp/intellij-express-generator253/node_modules/express-generator/bin/express

Body:
  npm install -g express-generator

Then, the webstorm will work!


问:
How to use curry function
I have a curried function on the object:

```<code>sealed trait Sum[A, B]

final case class Left[A, B](value: A) extends Sum[A, B]

final case class Right[A, B](value: B) extends Sum[A, B]

object Sum {

  def fold[A, B, C](s: Sum[A, B])(left: A => C)(right: B => C): C =
    s match {
      case Left(v) => left(v)
      case Right(v) => right(v)
    }

}
</code>```

How to use the fold function? I tried as follow:

```<code>object Main {
  def main(args: Array[String]): Unit = {

    val l = Sum.fold(Left(5))(l => l * l)

  }
}
</code>```

But I do not know, how to pass the third argument.

答:
You an do it like:

```<code>  val a: Sum[Int, Int] = Left(5)
  val l = Sum.fold(a)(l => l * l)(l => l * l)
</code>```

OR

```<code>  val l = Sum.fold(Left[Int, Int](5))(l => l * l)(l => l * l)
</code>```

You need to both specify Sum's A and B type for compiler can infer Left and Right A and B type.

As your code snippet, you only has specify the Left A type to Int without B type, the compiler can't infer B type, so for your third high-order function parameter, In compile time, the compiler will fail in here.

Title: How to use curry function

Body:
I have a curried function on the object:

sealed trait Sum[A, B]

final case class Left[A, B](value: A) extends Sum[A, B]

final case class Right[A, B](value: B) extends Sum[A, B]

object Sum {

  def fold[A, B, C](s: Sum[A, B])(left: A => C)(right: B => C): C =
    s match {
      case Left(v) => left(v)
      case Right(v) => right(v)
    }

}

How to use the fold function? I tried as follow:

object Main {
  def main(args: Array[String]): Unit = {

    val l = Sum.fold(Left(5))(l => l * l)

  }
}

But I do not know, how to pass the third argument.

Body:
You an do it like:

  val a: Sum[Int, Int] = Left(5)
  val l = Sum.fold(a)(l => l * l)(l => l * l)

OR

  val l = Sum.fold(Left[Int, Int](5))(l => l * l)(l => l * l)

You need to both specify Sum's A and B type for compiler can infer Left and Right A and B type.

As your code snippet, you only has specify the Left A type to Int without B type, the compiler can't infer B type, so for your third high-order function parameter, In compile time, the compiler will fail in here.


问:
Can't Install Mysql 5.6 on Ubuntu 14.04
I'm trying to upgrade from Mysql 5.5 to Mysql 5.6 on Ubuntu 14.04

I've tried:

Installing directly with sudo apt-get install mysql-server-5.6 - no success

Removing Mysql 5.5 fully first, according to this thread: Removing MySQL 5.5 Completely then installing with sudo apt-get install mysql-server-5.6 - no success

Creating 4g swap like explained here: https://askubuntu.com/questions/457923/why-did-installation-of-mysql-5-6-on-ubuntu-14-04-fail - no success

None of these options worked.. the error I get is this:

```<code>2015-07-06 02:32:33 12412 [Note] Plugin 'FEDERATED' is disabled.
2015-07-06 02:32:33 12412 [Note] InnoDB: Using atomics to ref count buffer pool pages
2015-07-06 02:32:33 12412 [Note] InnoDB: The InnoDB memory heap is disabled
2015-07-06 02:32:33 12412 [Note] InnoDB: Mutexes and rw_locks use GCC atomic builtins
2015-07-06 02:32:33 12412 [Note] InnoDB: Compressed tables use zlib 1.2.8
2015-07-06 02:32:33 12412 [Note] InnoDB: Using Linux native AIO
2015-07-06 02:32:33 12412 [Note] InnoDB: Not using CPU crc32 instructions
2015-07-06 02:32:33 12412 [Note] InnoDB: Initializing buffer pool, size = 128.0M
2015-07-06 02:32:33 12412 [Note] InnoDB: Completed initialization of buffer pool
2015-07-06 02:32:33 12412 [Note] InnoDB: Highest supported file format is Barracuda.
2015-07-06 02:32:33 12412 [Note] InnoDB: 128 rollback segment(s) are active.
2015-07-06 02:32:33 12412 [Note] InnoDB: Waiting for purge to start
2015-07-06 02:32:33 12412 [Note] InnoDB: 5.6.19 started; log sequence number 1626183
2015-07-06 02:32:33 12412 [Note] Binlog end
2015-07-06 02:32:33 12412 [Note] InnoDB: FTS optimize thread exiting.
2015-07-06 02:32:33 12412 [Note] InnoDB: Starting shutdown...
2015-07-06 02:32:35 12412 [Note] InnoDB: Shutdown completed; log sequence number 1626193
start: Job failed to start
invoke-rc.d: initscript mysql, action "start" failed.
dpkg: error processing package mysql-server-5.6 (--configure):
 subprocess installed post-installation script returned error exit status 1
Setting up mysql-common-5.6 (5.6.19-0ubuntu0.14.04.1) ...
</code>```

I can't set it up, getting really really frustrated

Running on Digital Ocean VPS, please enlighten me masters :(

答:
I meet this problem before, in my situation, it happens because i use vagrant vpc server.

```<code>1.remove all Local MySQL
$ sudo apt-get autoremove –purge mysql*
$ sudo rm -rf /var/lib/mysql/
$ sudo rm -rf /etc/mysql/

2.install mysql
$ sudo apt-get update
$ sudo apt-get build-dep mysql-server-5.6
$ sudo apt-get install mysql-server-5.6
</code>```

If you still have problem, check the following info:

Increase the amount of memory in your EC2

Set a smaller value for MySQL’s max_connections variable

Title: Can't Install Mysql 5.6 on Ubuntu 14.04

Body:
I'm trying to upgrade from Mysql 5.5 to Mysql 5.6 on Ubuntu 14.04

I've tried:

Installing directly with sudo apt-get install mysql-server-5.6 - no success

Removing Mysql 5.5 fully first, according to this thread: Removing MySQL 5.5 Completely then installing with sudo apt-get install mysql-server-5.6 - no success

Creating 4g swap like explained here: https://askubuntu.com/questions/457923/why-did-installation-of-mysql-5-6-on-ubuntu-14-04-fail - no success

None of these options worked.. the error I get is this:

2015-07-06 02:32:33 12412 [Note] Plugin 'FEDERATED' is disabled.
2015-07-06 02:32:33 12412 [Note] InnoDB: Using atomics to ref count buffer pool pages
2015-07-06 02:32:33 12412 [Note] InnoDB: The InnoDB memory heap is disabled
2015-07-06 02:32:33 12412 [Note] InnoDB: Mutexes and rw_locks use GCC atomic builtins
2015-07-06 02:32:33 12412 [Note] InnoDB: Compressed tables use zlib 1.2.8
2015-07-06 02:32:33 12412 [Note] InnoDB: Using Linux native AIO
2015-07-06 02:32:33 12412 [Note] InnoDB: Not using CPU crc32 instructions
2015-07-06 02:32:33 12412 [Note] InnoDB: Initializing buffer pool, size = 128.0M
2015-07-06 02:32:33 12412 [Note] InnoDB: Completed initialization of buffer pool
2015-07-06 02:32:33 12412 [Note] InnoDB: Highest supported file format is Barracuda.
2015-07-06 02:32:33 12412 [Note] InnoDB: 128 rollback segment(s) are active.
2015-07-06 02:32:33 12412 [Note] InnoDB: Waiting for purge to start
2015-07-06 02:32:33 12412 [Note] InnoDB: 5.6.19 started; log sequence number 1626183
2015-07-06 02:32:33 12412 [Note] Binlog end
2015-07-06 02:32:33 12412 [Note] InnoDB: FTS optimize thread exiting.
2015-07-06 02:32:33 12412 [Note] InnoDB: Starting shutdown...
2015-07-06 02:32:35 12412 [Note] InnoDB: Shutdown completed; log sequence number 1626193
start: Job failed to start
invoke-rc.d: initscript mysql, action "start" failed.
dpkg: error processing package mysql-server-5.6 (--configure):
 subprocess installed post-installation script returned error exit status 1
Setting up mysql-common-5.6 (5.6.19-0ubuntu0.14.04.1) ...

I can't set it up, getting really really frustrated

Running on Digital Ocean VPS, please enlighten me masters :(

Body:
I meet this problem before, in my situation, it happens because i use vagrant vpc server.

1.remove all Local MySQL
$ sudo apt-get autoremove –purge mysql*
$ sudo rm -rf /var/lib/mysql/
$ sudo rm -rf /etc/mysql/

2.install mysql
$ sudo apt-get update
$ sudo apt-get build-dep mysql-server-5.6
$ sudo apt-get install mysql-server-5.6

If you still have problem, check the following info:

Increase the amount of memory in your EC2

Set a smaller value for MySQL’s max_connections variable


问:
Use PHP to submit HTTP POST request containing image
So I've seen many examples of uploading an image via PHP using move_uploaded_file, but from the way that sounds, that would be a PHP script that resides on the server. In my case, I'm not trying to handle an uploaded file. I'm trying to submit a POST request and actually have the binary content of the file inserted with the HTTP POST request.

For example, my PHP script should be able to submit a form and include an image in its HTTP POST data, but I can't seem to figure this out or find valid examples specifically for doing this.

To further clarify, I am using CURL within PHP to submit this multipart/form-data.

Here's an example of what I have now:

```<code>function GetPostData($filename) {
    if(!$filename) {
        echo "The image doesn't exist ".$filename;
    } else {
        $data = [
            'device_timestamp' => time(),
            'photo' => '@'.$filename
        ];
        return $data;
    }
}
function SendRequest($url, $post, $data, $userAgent, $cookies) {
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, 'https://i.example.com/api/v1/'.$url);
    curl_setopt($ch, CURLOPT_USERAGENT, $userAgent);
    curl_setopt($ch, CURLOPT_PROXY, 'http://192.168.1.21:8080');
    curl_setopt($ch, CURLOPT_HTTPPROXYTUNNEL, 1);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);

    if($post) {
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
    }

    if($cookies) {
        curl_setopt($ch, CURLOPT_COOKIEFILE, 'cookies.txt');
    } else {
        curl_setopt($ch, CURLOPT_COOKIEJAR, 'cookies.txt');
    }

    $response = curl_exec($ch);
    $http = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);

    return [
        'code' => $http,
        'response' => $response,
    ];
}
</code>```

.

```<code> $data = GetPostData($filename);
        $post = SendRequest('media/upload/', true, $data, $agent, true);
</code>```

But when I submit the image via the PHP script, this is what it looks like when I inspect the network traffic.

```<code>Content-Type: multipart/form-data; boundary=------------------------eee3f953c516cc55
Connection: close

--------------------------eee3f953c516cc55
Content-Disposition: form-data; name="device_timestamp"

1491023582
--------------------------eee3f953c516cc55
Content-Disposition: form-data; name="photo"

@/home/user/Desktop/square.jpeg
--------------------------eee3f953c516cc55--
</code>```

Isn't the POST data supposed to contain the binary output of the image? How would the server save the image otherwise if just the path of the file is submitted in the form and not the actual image?

In other words, just like you would go to the terminal and type cat image.jpg, that's what I need PHP to submit in its form.

答:
Solved my own problem by changing

```<code> function GetPostData($filename) {
        if(!$filename) {
            echo "The image doesn't exist ".$filename;
        } else {
            $data = [
                'device_timestamp' => time(),
                'photo' => '@'.$filename
            ];
            return $data;
        }
    }
</code>```

to this:

```<code> function GetPostData($filename) {
        if(!$filename) {
            echo "The image doesn't exist ".$filename;
        } else {
            $data = [
                'device_timestamp' => time(),
                'photo' => file_get_contents($filename)
            ];
            return $data;
        }
    }
</code>```

Body:
So I've seen many examples of uploading an image via PHP using move_uploaded_file, but from the way that sounds, that would be a PHP script that resides on the server. In my case, I'm not trying to handle an uploaded file. I'm trying to submit a POST request and actually have the binary content of the file inserted with the HTTP POST request.

For example, my PHP script should be able to submit a form and include an image in its HTTP POST data, but I can't seem to figure this out or find valid examples specifically for doing this.

To further clarify, I am using CURL within PHP to submit this multipart/form-data.

Here's an example of what I have now:

function GetPostData($filename) {
    if(!$filename) {
        echo "The image doesn't exist ".$filename;
    } else {
        $data = [
            'device_timestamp' => time(),
            'photo' => '@'.$filename
        ];
        return $data;
    }
}
function SendRequest($url, $post, $data, $userAgent, $cookies) {
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, 'https://i.example.com/api/v1/'.$url);
    curl_setopt($ch, CURLOPT_USERAGENT, $userAgent);
    curl_setopt($ch, CURLOPT_PROXY, 'http://192.168.1.21:8080');
    curl_setopt($ch, CURLOPT_HTTPPROXYTUNNEL, 1);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);

    if($post) {
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
    }

    if($cookies) {
        curl_setopt($ch, CURLOPT_COOKIEFILE, 'cookies.txt');
    } else {
        curl_setopt($ch, CURLOPT_COOKIEJAR, 'cookies.txt');
    }

    $response = curl_exec($ch);
    $http = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);

    return [
        'code' => $http,
        'response' => $response,
    ];
}

.

 $data = GetPostData($filename);
        $post = SendRequest('media/upload/', true, $data, $agent, true);

But when I submit the image via the PHP script, this is what it looks like when I inspect the network traffic.

Content-Type: multipart/form-data; boundary=------------------------eee3f953c516cc55
Connection: close

--------------------------eee3f953c516cc55
Content-Disposition: form-data; name="device_timestamp"

1491023582
--------------------------eee3f953c516cc55
Content-Disposition: form-data; name="photo"

@/home/user/Desktop/square.jpeg
--------------------------eee3f953c516cc55--

Isn't the POST data supposed to contain the binary output of the image? How would the server save the image otherwise if just the path of the file is submitted in the form and not the actual image?

In other words, just like you would go to the terminal and type cat image.jpg, that's what I need PHP to submit in its form.

Body:
Solved my own problem by changing

 function GetPostData($filename) {
        if(!$filename) {
            echo "The image doesn't exist ".$filename;
        } else {
            $data = [
                'device_timestamp' => time(),
                'photo' => '@'.$filename
            ];
            return $data;
        }
    }

to this:

 function GetPostData($filename) {
        if(!$filename) {
            echo "The image doesn't exist ".$filename;
        } else {
            $data = [
                'device_timestamp' => time(),
                'photo' => file_get_contents($filename)
            ];
            return $data;
        }
    }


问:
How to edit and update table row dynamically in jquery and HTML
I am adding rows to table dynamically,now i am trying to edit table rows.

I click on edit, values are getting in text boxes after edit values i am clicking the add button but i created like new row not updated.

Any mistakes in my code

```<code><form class="form-horizontal" role="form" id="chargesForm">
            <div class="col-md-6">
                 <div class="form-group ">
                    <label for="minAmt" class="col-lg-4 control-label">MinAmmount</label>
                    <div class="col-lg-6">
                       <input type="text" class="form-control" id="minAmt" name="minAmt" />
                    </div>
                 </div>
                 <div class="form-group ">
                    <label for="maxAmt" class="col-lg-4 control-label">MaxAmmount</label>
                    <div class="col-lg-6">
                       <input type="text" class="form-control" id="maxAmt" name="maxAmt"/>
                    </div>
                 </div>

              </div>
              <div class="col-md-6">
                 <div class="form-group ">
                    <label for="type" class="col-lg-4 control-label">Type</label>
                    <select size="1" id="type" name="type">
                       <option value="Flat" selected="selected">
                          Flat
                       </option>
                       <option value="Percentage">
                          Percentage
                       </option>
                    </select>
                 </div>

              </div>

              <div class="col-md-12">
                 <div class="form-actions btnzone">
                    <button type="button" class="btn btn-success savebtn" style="padding: 6px 12px;margin-left: 40%;" id="savebutton" ><i class="icon-check-sign" aria-hidden="false"></i>Add</button>
                    <a class="btn btn-danger" ><i class=""></i>Back</a>

                 </div>
              </div>
           </form>
           <form  class="form-horizontal" role="form" id="chargestableForm">
              <div class="col-md-12" style="height:150px;overflow:auto;margin-top:5px;">
                 <table id="charges" class="table table-hover" width="100%" cellspacing="0" style="border: 1px; height:10px;" >
                    <thead style="background-color:#CCE5FF">
                       <tr>
                          <th>MinAmmount</th>
                          <th>MaxAmmount</th>
                          <th>Type</th>
                          <th></th>
                          <th></th>
                       </tr>
                    </thead>
                    <tbody>
                    </tbody>
                 </table>
              </div>
           </form>
</code>```

i added rows with the help of jquery

```<code>var i=0;
                            $("button#savebutton").click(function(){
                                var minAmt=$("#minAmt").val();
                                var maxAmt=$("#maxAmt").val();
                                var type=$("#type").val();
                                i++;
                                var new_row = "<tr id='row"+i+"' class='info'><td class='minAmt'>" + minAmt + "</td><td class='maxAmt'>" + maxAmt + "</td><td class='type'>" + type + "</td><td><span class='editrow'><a class='fa fa-edit' href='javascript: void(0);'></a></span></td><td><span class='deleterow'><a class='glyphicon glyphicon-trash' href=''></a></span></tr>";
                                 $("table tbody").append(new_row);
                                 $("#minAmt").val($('td.maxAmt').last().text()).prop("disabled","disabled");
                                 $("#maxAmt").val('');
                                 //$("#type").val('');
                            });

                        $(document).on('click', 'span.deleterow', function () {
                                $(this).parents('tr').remove();
                               return false;
                        });
                        $(document).on('click', 'span.editrow', function () {
                        $("#minAmt").val($(this).closest('tr').find('td.minAmt').text()).prop("disabled","disabled");
                        $("#maxAmt").val($(this).closest('tr').find('td.maxAmt').text()).prop("disabled","disabled");
                        $("#type").val($(this).closest('tr').find('td.type').text());
                        });
</code>```

答:
Use replaceWith()

Add a hidden field to denote which row is being edited.

```<code><input type="hidden" id="currentRow"/>
</code>```

On Edit

```<code>$(document).on('click', 'span.editrow', function () {
  $("#currentRow").val($(this).closest("tr").attr("id"));
}):
</code>```

On the click of Save in Edit mode create a new row template with the updated values and replace the existing row with the new one.

```<code>  $("button#savebutton").click(function(){
     if($("#currentRow").val()){
       var row = $("table tbody").find('#'+$("#currentRow").val());
       // var updated_row = //Updated template of the existing row
       row.replaceWith (updated_row);
       $("#currentRow").val("");
     }
  });
</code>```

Body:
I am adding rows to table dynamically,now i am trying to edit table rows.

I click on edit, values are getting in text boxes after edit values i am clicking the add button but i created like new row not updated.

Any mistakes in my code

<form class="form-horizontal" role="form" id="chargesForm">

                    MinAmmount

                       <input type="text" class="form-control" id="minAmt" name="minAmt" />

                    MaxAmmount

                       <input type="text" class="form-control" id="maxAmt" name="maxAmt"/>

                    Type
                    <select size="1" id="type" name="type">
                       <option value="Flat" selected="selected">
                          Flat
                       </option>
                       <option value="Percentage">
                          Percentage
                       </option>
                    </select>

                    <button type="button" class="btn btn-success savebtn" style="padding: 6px 12px;margin-left: 40%;" id="savebutton" >Add</button>
                    Back

           </form>
           <form  class="form-horizontal" role="form" id="chargestableForm">

                          MinAmmount
                          MaxAmmount
                          Type

           </form>

i added rows with the help of jquery

var i=0;
                            $("button#savebutton").click(function(){
                                var minAmt=$("#minAmt").val();
                                var maxAmt=$("#maxAmt").val();
                                var type=$("#type").val();
                                i++;
                                var new_row = "
" + minAmt + "	" + maxAmt + "	" + type + "
";
                                 $("table tbody").append(new_row);
                                 $("#minAmt").val($('td.maxAmt').last().text()).prop("disabled","disabled");
                                 $("#maxAmt").val('');
                                 //$("#type").val('');
                            });

                        $(document).on('click', 'span.deleterow', function () {
                                $(this).parents('tr').remove();
                               return false;
                        });
                        $(document).on('click', 'span.editrow', function () {
                        $("#minAmt").val($(this).closest('tr').find('td.minAmt').text()).prop("disabled","disabled");
                        $("#maxAmt").val($(this).closest('tr').find('td.maxAmt').text()).prop("disabled","disabled");
                        $("#type").val($(this).closest('tr').find('td.type').text());
                        });

Body:
Use replaceWith()

Add a hidden field to denote which row is being edited.

<input type="hidden" id="currentRow"/>

On Edit

$(document).on('click', 'span.editrow', function () {
  $("#currentRow").val($(this).closest("tr").attr("id"));
}):

On the click of Save in Edit mode create a new row template with the updated values and replace the existing row with the new one.

  $("button#savebutton").click(function(){
     if($("#currentRow").val()){
       var row = $("table tbody").find('#'+$("#currentRow").val());
       // var updated_row = //Updated template of the existing row
       row.replaceWith (updated_row);
       $("#currentRow").val("");
     }
  });


问:
how to implement modal by using bootstrap?
I am using modal concept of bootstrap in my html file. In modal i am entering data after clicking on save this data should be displayed in  html page where modal is called. By using which function i can include or display this data in html page.

答:
I assume bootstrap "modal" style class used in the code to show popup from parent page. Here, JavaScript /jquery would help to update the content from modal div to other div in the same page.

Ex: https://jsfiddle.net/AMVijay/f46qLn8L/1/

HTML Content with Bootstrap and JQuery:

```<code><form>
  <div class="form-group">
    <label for="inputName" class="col-sm-2 control-label">Name</label>
    <div class="col-sm-10">
      <input type="text" class="form-control" id="inputName" placeholder="Name" disabled>
    </div>
  </div>
  <div class="form-group">
    <div class="col-sm-offset-2 col-sm-10">
      <!-- Button trigger modal -->
      <button type="button" class="btn btn-primary btn-lg" data-toggle="modal" data-target="#myModal">Launch demo modal</button>
    </div>
  </div>
</form>
<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="gridSystemModalLabel">
  <div class="modal-dialog" role="document">
    <div class="modal-content">
      <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
        <h4 class="modal-title" id="gridSystemModalLabel">Modal Title</h4>
      </div>
      <div class="modal-body">
        <div class="row">
          <div class="col-md-4">
            <input type="text" class="form-control" id="inputFirstName" placeholder="First Name" />
          </div>
        </div>
        <div class="row">
          <div class="col-md-4">
            <input type="text" class="form-control" id="inputLastName" placeholder="Last Name" />
          </div>
        </div>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
        <button id="modalSaveButton" type="button" class="btn btn-primary">Save changes</button>
      </div>
    </div>
    <!-- /.modal-content -->
  </div>
  <!-- /.modal-dialog -->
</div>
<!-- /.modal -->
</code>```

Java Script:

```<code>$(document).ready(function() {
  $("#modalSaveButton").click(function() {
    var fullName = $("#inputFirstName").val() + " " + $("#inputLastName").val();
    console.log("Full Name :: " + fullName);
    $("#inputName").val(fullName);
    $('#myModal').modal('toggle');
  });
});
</code>```

Body:
I assume bootstrap "modal" style class used in the code to show popup from parent page. Here, JavaScript /jquery would help to update the content from modal div to other div in the same page.

Ex: https://jsfiddle.net/AMVijay/f46qLn8L/1/

HTML Content with Bootstrap and JQuery:

<form>
  <div class="form-group">
    <label for="inputName" class="col-sm-2 control-label">Name</label>
    <div class="col-sm-10">
      <input type="text" class="form-control" id="inputName" placeholder="Name" disabled>
    </div>
  </div>
  <div class="form-group">
    <div class="col-sm-offset-2 col-sm-10">
      <!-- Button trigger modal -->
      <button type="button" class="btn btn-primary btn-lg" data-toggle="modal" data-target="#myModal">Launch demo modal</button>
    </div>
  </div>
</form>
<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="gridSystemModalLabel">
  <div class="modal-dialog" role="document">
    <div class="modal-content">
      <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
        <h4 class="modal-title" id="gridSystemModalLabel">Modal Title</h4>
      </div>
      <div class="modal-body">
        <div class="row">
          <div class="col-md-4">
            <input type="text" class="form-control" id="inputFirstName" placeholder="First Name" />
          </div>
        </div>
        <div class="row">
          <div class="col-md-4">
            <input type="text" class="form-control" id="inputLastName" placeholder="Last Name" />
          </div>
        </div>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
        <button id="modalSaveButton" type="button" class="btn btn-primary">Save changes</button>
      </div>
    </div>
    <!-- /.modal-content -->
  </div>
  <!-- /.modal-dialog -->
</div>
<!-- /.modal -->

Java Script:

$(document).ready(function() {
  $("#modalSaveButton").click(function() {
    var fullName = $("#inputFirstName").val() + " " + $("#inputLastName").val();
    console.log("Full Name :: " + fullName);
    $("#inputName").val(fullName);
    $('#myModal').modal('toggle');
  });
});


问:
setAlpha for RemoteViews problem
I'm making an appwidget, and there's a bitmap on the widget of which I want to change it's transparency.

In the service I have:

```<code>RemoteViews remoteView = new RemoteViews(getApplicationContext().getPackageName(), R.layout.myWidget);

remoteView.setInt(R.id.widgetPNG, "setAlpha", 50);
</code>```

But it doesn't work. The emulator shows "Problem loading widget" on the home screen.
I'm pretty sure everything else is fine cos when i changed the line to change it's imageResource it runs perfectly: remoteView.setInt(R.id.widgetPNG, "setImageResource", R.drawable.anotherPNG).

Can anyone help me? I've been stuck with this for a week...

答:
Am fraid you can only call setInt() and friends on APIs which are marked with the @RemotableViewMethod annotation in the Android source code (example). Afraid setAlpha() is not one of them.

Maybe you could have two background images, a transparent one and a non-transparent one...

Title: setAlpha for RemoteViews problem

Body:
I'm making an appwidget, and there's a bitmap on the widget of which I want to change it's transparency.

In the service I have:

RemoteViews remoteView = new RemoteViews(getApplicationContext().getPackageName(), R.layout.myWidget);

remoteView.setInt(R.id.widgetPNG, "setAlpha", 50);

But it doesn't work. The emulator shows "Problem loading widget" on the home screen.
I'm pretty sure everything else is fine cos when i changed the line to change it's imageResource it runs perfectly: remoteView.setInt(R.id.widgetPNG, "setImageResource", R.drawable.anotherPNG).

Can anyone help me? I've been stuck with this for a week...


问:
JavaScript tag with rocket property
In the site: pro emoji keyboard online at http://www.emojiselector.com, I saw in source code, something as follows:

```<code><script data-rocketsrc="assets/web/assets/jquery/jquery.min.js" type="text/rocketscript"></script>
<script data-rocketsrc="assets/tether/tether.min.js" type="text/rocketscript"></script>
</code>```

What does this mean? data-rocketsrc, text/rocketscript??? I know for traditional tag in html is src and text/javascript. Is this another languages or another standards? I saw in code of JS, nothing is different!

答: Your website seems to be powered by CloudFlare. CloudFlare uses Rocket Loader to speed up the website loading speed. Read more here.</p>

Title: JavaScript tag with rocket property

Body:
In the site: pro emoji keyboard online at http://www.emojiselector.com, I saw in source code, something as follows:

What does this mean? data-rocketsrc, text/rocketscript??? I know for traditional tag in html is src and text/javascript. Is this another languages or another standards? I saw in code of JS, nothing is different!


问:
Disable and enable link using PHP when admin click button
I have a problem with my website project using PHP. How can I disable link (ex : register.php and login.php) when admin click button for disable link in admin panel, and enable that again when it clicked for the second time..

Anyone can help ? thanks

答:
Store the admin selection in a database and set that property when the user loads that page.Assuming you are using raw PHP,just add disabled when admin is disabled and romove the disabled property when it is enabled</p>

```<code><a href="" <?php echo $status?'disabled':''>/>
</code>```

Body:
Store the admin selection in a database and set that property when the user loads that page.Assuming you are using raw PHP,just add disabled when admin is disabled and romove the disabled property when it is enabled

<a href="" <?php echo $status?'disabled':''>/>