问:
Remote login from an unnamed fields using Guzzle PHP
There is a specific site that I would like to connect to remotely through Guzzle. The problem whose fields of username and password are without a name.

My question is:

Can I use POST method without knowing the names of the fields?

Can I use the name of the class instead?

My code:

Login.php

```<code><?php
require("master/guzzle/vendor/autoload.php");

$username = "abc";
$password = "123456";

$client = new \GuzzleHttp\Client();

$response = $client->post('https://www.exmaple.com/login', [
    'body' => [
        'username' => $username,
        'password' => $password,
        'action' => 'login'
    ],
    'cookies' => true
]
);

echo $response;
?>
</code>```

example.com/login

```<code><form>
    <div class="login-name">
        <div data-nep="Label" class="name-font default neptune_block_15yk4 neptune_LABEL-STANDARD_1h3i4">Username
            <div class="neptune_fade-after_15yk4"></div>
        </div>
        <div data-nep="TextBox">
            <input type="text" placeholder="" value="" class="neptune_default_1jbvk" style="height:30px">
            </div>
        </div>
        <div class="login-name">
            <div data-nep="Label" class="name-font default neptune_block_15yk4 neptune_LABEL-STANDARD_1h3i4">Password
                <div class="neptune_fade-after_15yk4"></div>
            </div>
            <div data-nep="TextBox">
                <input type="password" placeholder="" value="" class="neptune_default_1jbvk" style="height:30px">
                </div>
            </div>
        </form>
</code>```

答:
Is it a ajax login form? if so, I think after entering data in fileds, the form will call a Ajax call of original login controller. so you must find that request and post parameters name

Use Firefox or chrome press F12 to show the Web Developer toos, go to the Network panel and select XHR to filter ajax request.

In your case when submitting the form there is a callback to another page
click on params tab on the right will show you what post data your looking for.

```<code>$response = $client->request('POST', 'https://api.moodys.com/rest/mobile/oauth/token?client=0', [
    'form_params' => [
        'username' => 'test@gmail.com',
        'grant_type' => 'password',
        'password' => 'testpassword',
    ]
])
</code>```

Body:
There is a specific site that I would like to connect to remotely through Guzzle. The problem whose fields of username and password are without a name.

My question is:

Can I use POST method without knowing the names of the fields?

Can I use the name of the class instead?

My code:

Login.php

<?php
require("master/guzzle/vendor/autoload.php");

$username = "abc";
$password = "123456";

$client = new \GuzzleHttp\Client();

$response = $client->post('https://www.exmaple.com/login', [
    'body' => [
        'username' => $username,
        'password' => $password,
        'action' => 'login'
    ],
    'cookies' => true
]
);

echo $response;
?>

example.com/login

<form>

Username

            <input type="text" placeholder="" value="" class="neptune_default_1jbvk" style="height:30px">

Password

                <input type="password" placeholder="" value="" class="neptune_default_1jbvk" style="height:30px">

        </form>

Body:
Is it a ajax login form? if so, I think after entering data in fileds, the form will call a Ajax call of original login controller. so you must find that request and post parameters name

Use Firefox or chrome press F12 to show the Web Developer toos, go to the Network panel and select XHR to filter ajax request.

In your case when submitting the form there is a callback to another page
click on params tab on the right will show you what post data your looking for.

$response = $client->request('POST', 'https://api.moodys.com/rest/mobile/oauth/token?client=0', [
    'form_params' => [
        'username' => 'test@gmail.com',
        'grant_type' => 'password',
        'password' => 'testpassword',
    ]
])


来源: stackexchange

问:
Unable to understand lambdas AND longstream methods
I have such code example.

```<code>import java.util.LinkedList;
import java.util.List;
import java.util.stream.LongStream;

public class RemovedNumbers {

    public static List<long[]> removNb(long n) {
        System.out.println(n);
        long sum = ((n + 1) * n / 2);
        long minMultiplication = sum - 2 * n + 1;
        long minCandidate = (long) Math.sqrt(minMultiplication);

        LinkedList<long[]> list = new LinkedList<>();

        LongStream.rangeClosed(minCandidate, n)
                  .mapToObj(a -> new long[]{a, calculateB(a, sum)})
                  .filter(longs -> longs[0] > longs[1])
                  .filter(longs -> longs[1] <= n)
                  .filter(longs -> longs[0] * longs[1] == sum - longs[0] - longs[1])
                  .forEach(longs -> addArrays(list, longs));

        return list;
    }

    private static long calculateB(long a, long sum) {
        return (sum - a) / (a + 1);
    }

    private static void addArrays(final LinkedList<long[]> list, final long[] longs) {
        list.addFirst(new long[]{longs[1], longs[0]});
        list.add(longs);
    }
}
</code>```

This code is complicated for me in LongStream part.
I don't get some points, so I need a help:

I examine LongStream class.

This class uses four methods: rangeClosed, mapToObj, filter, forEach (their description I found on Java docs). Unfortunately, now I am starting to examine java 1.8 version,  so I can't understand how it works and what's happens.

Where is appeared "a" in mapToObj? What is it? I don't see var "a" declaration in previous part of code.

As I've got lambda is made by such scheme: (arguments) -> (body). So the "a" is an argument, "new long[]..." - is a body. This part isn't causes any question for me. But the next one, whereis "longs" - argument, "longs[0] > longs[1]" - body, causes some questions. What is the var "longs"? It hasn't declaration in the past! HOW it appears? How it works?

Am I right that LongStream class can be writes in one line? Like: LongStream.rangeClosed().filter().filter().filter().forEach(); ?

Am I right that all methods execute consequently? By each other? The first rangeClosed, then mapToObj, then filter... or is there another order?

Thanks a lot!

答:
3 and 4:

you are tryng to understand how lambda work so I'll break it down your code for you:

```<code>// this return a LongStream obj
LongStream.rangeClosed(minCandidate, n)
// so with point notation you can access to one of the method in LongStream
// matToObj in this case.
.mapToObj(a -> new long[]{a, calculateB(a, sum)})
</code>```

what is a? What ->? what the other stuff?

MapToObj takes a IntFunction mapper argument and a is a declaration of that type on the fly this is why you didin't see it before in the code.
the arrow indicates that the right site is the lamba expression, if you have a inline operation you can omit the return statement and you can not include {} brackets so imagine that statement like a return statement.
With lamba functions you can easily create chains of operation this is why you have many functions called one after another. You have to keep in mind that the next function takes as argument an object type that is of the same type of the return type of the previous function.

ContentLicense: CC BY-SA 4.0

Body:
I have such code example.

import java.util.LinkedList;
import java.util.List;
import java.util.stream.LongStream;

public class RemovedNumbers {

    public static List<long[]> removNb(long n) {
        System.out.println(n);
        long sum = ((n + 1) * n / 2);
        long minMultiplication = sum - 2 * n + 1;
        long minCandidate = (long) Math.sqrt(minMultiplication);

        LinkedList<long[]> list = new LinkedList<>();

        LongStream.rangeClosed(minCandidate, n)
                  .mapToObj(a -> new long[]{a, calculateB(a, sum)})
                  .filter(longs -> longs[0] > longs[1])
                  .filter(longs -> longs[1] <= n)
                  .filter(longs -> longs[0] * longs[1] == sum - longs[0] - longs[1])
                  .forEach(longs -> addArrays(list, longs));

        return list;
    }

    private static long calculateB(long a, long sum) {
        return (sum - a) / (a + 1);
    }

    private static void addArrays(final LinkedList<long[]> list, final long[] longs) {
        list.addFirst(new long[]{longs[1], longs[0]});
        list.add(longs);
    }
}

This code is complicated for me in LongStream part.
I don't get some points, so I need a help:

I examine LongStream class.

This class uses four methods: rangeClosed, mapToObj, filter, forEach (their description I found on Java docs). Unfortunately, now I am starting to examine java 1.8 version,  so I can't understand how it works and what's happens.

Where is appeared "a" in mapToObj? What is it? I don't see var "a" declaration in previous part of code.

As I've got lambda is made by such scheme: (arguments) -> (body). So the "a" is an argument, "new long[]..." - is a body. This part isn't causes any question for me. But the next one, whereis "longs" - argument, "longs[0] > longs[1]" - body, causes some questions. What is the var "longs"? It hasn't declaration in the past! HOW it appears? How it works?

Am I right that LongStream class can be writes in one line? Like: LongStream.rangeClosed().filter().filter().filter().forEach(); ?

Am I right that all methods execute consequently? By each other? The first rangeClosed, then mapToObj, then filter... or is there another order?

Thanks a lot!

Body:
3 and 4:

you are tryng to understand how lambda work so I'll break it down your code for you:

// this return a LongStream obj
LongStream.rangeClosed(minCandidate, n)
// so with point notation you can access to one of the method in LongStream
// matToObj in this case.
.mapToObj(a -> new long[]{a, calculateB(a, sum)})

what is a? What ->? what the other stuff?

MapToObj takes a IntFunction mapper argument and a is a declaration of that type on the fly this is why you didin't see it before in the code.
the arrow indicates that the right site is the lamba expression, if you have a inline operation you can omit the return statement and you can not include {} brackets so imagine that statement like a return statement.
With lamba functions you can easily create chains of operation this is why you have many functions called one after another. You have to keep in mind that the next function takes as argument an object type that is of the same type of the return type of the previous function.


问:
makeObjectsPerformSelector:
I want to make all objects in an array perform a selector. I've discovered the appropriately named makeObjectsPerformSelector: method, but I have a question with it. If I use it on an array, will it change the existing array or return a new one? If it modifies the existing object, what be the easiest way to return a new array with the selector applied?

答:
I hope I'm interpreting this correctly...

If you do [myArray makeObjectsPerformSelector:someSelector], you're effectively just iterating through myArray and sending the selector message to each object. The array is unchanged because makeObjectsPerformSelector isn't allowed to change its contents.

So in the end, you've got the same array with the same objects.

OwnerDisplayName: Allyn

ContentLicense: CC BY-SA 3.0

Title: makeObjectsPerformSelector:

OwnerDisplayName: Terry Wilcox

ContentLicense: CC BY-SA 2.5


问:
Pusher App Client Events
I'm writing a multiplayer chess game, and using Pusher for the websocket server part.

Anyways, if I have a list of users, and I select any one of them and challenge them, how do I send challenge to just that one user? I know I would use the client event like:

```<code>channel.trigger("client-challenge_member1", {some : "data"});
</code>```

But this event would have to have already been created I think. So do I create this event dynamically after each member subscribes? as possibly in:

```<code>channel.bind("pusher:subscribed_completed", function(member) // not sure of correct syntax but...
{
   channel.bind("client-challenge_" + member.memberID, function(data)
   {
      alert(data.Name + " is challenging you.");
   });
});
</code>```

I would think there'd be a overloaded method for trigger, like:

```<code>channel.trigger(eventName, data, memberID)
</code>```

But I cannot see anything like this. Any ideas? Thanks.

答:
If you're able to consider another service, Beaconpush has the ability to send messages to a specific user.

From their site:

POST /1.0.0/[API key]/users/[user]

Title: Pusher App Client Events

Body:
I'm writing a multiplayer chess game, and using Pusher for the websocket server part.

Anyways, if I have a list of users, and I select any one of them and challenge them, how do I send challenge to just that one user? I know I would use the client event like:

channel.trigger("client-challenge_member1", {some : "data"});

But this event would have to have already been created I think. So do I create this event dynamically after each member subscribes? as possibly in:

channel.bind("pusher:subscribed_completed", function(member) // not sure of correct syntax but...
{
   channel.bind("client-challenge_" + member.memberID, function(data)
   {
      alert(data.Name + " is challenging you.");
   });
});

I would think there'd be a overloaded method for trigger, like:

channel.trigger(eventName, data, memberID)

But I cannot see anything like this. Any ideas? Thanks.


问:
JPOS Restful API send and receive data
I configure the RESTFul API in JPOS from jpos-rest.pdf.

The problem is I couldn't receive data from the client, but I can send data to the client.

In Echo.java class by below code I can send data:

```<code>package org.jpos.rest;

import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import java.util.HashMap;
import java.util.Map;

@Path("/echo")
public class Echo {
    @GET
    @Produces({MediaType.APPLICATION_JSON})
    public Response echoGet() {
        Map<String, Object> resp = new HashMap<>();
        resp.put("success", "true");
        resp.put("Name", "Hamid");
        resp.put("Family", "Mohammadi");
        Response.ResponseBuilder rb = Response.ok(resp, MediaType.APPLICATION_JSON).status(Response.Status.OK);
        return rb.build();
    }
}
</code>```

How can I receive data from the client? There is no request parameter to find what is the request and its data;

答:
Thanks to @Sabir Khan
I changed the code to:

```<code>    @Path("/echo")
    public class Echo {
        @PUT
        @Produces({MediaType.APPLICATION_JSON})
        @Consumes(MediaType.TEXT_PLAIN)
        @Path("/{name}/{family}")
        public Response echoGet(
                @PathParam("name") String name,
                @PathParam("family") String family,
                String Desc
        ) {
            Map<String, Object> resp = new HashMap<>();
            resp.put("success", "true");
            resp.put("Name", name);
            resp.put("Family", family);
            resp.put("Desc", Desc);
            Response.ResponseBuilder rb = Response.ok(resp,
MediaType.APPLICATION_JSON).status(Response.Status.OK);
            return rb.build();
        }
    }
</code>```

and send data to RESTFul API like this:

Title: JPOS Restful API send and receive data

Body:
I configure the RESTFul API in JPOS from jpos-rest.pdf.

The problem is I couldn't receive data from the client, but I can send data to the client.

In Echo.java class by below code I can send data:

package org.jpos.rest;

import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import java.util.HashMap;
import java.util.Map;

@Path("/echo")
public class Echo {
    @GET
    @Produces({MediaType.APPLICATION_JSON})
    public Response echoGet() {
        Map<String, Object> resp = new HashMap<>();
        resp.put("success", "true");
        resp.put("Name", "Hamid");
        resp.put("Family", "Mohammadi");
        Response.ResponseBuilder rb = Response.ok(resp, MediaType.APPLICATION_JSON).status(Response.Status.OK);
        return rb.build();
    }
}

How can I receive data from the client? There is no request parameter to find what is the request and its data;

Body:
Thanks to @Sabir Khan
I changed the code to:

    @Path("/echo")
    public class Echo {
        @PUT
        @Produces({MediaType.APPLICATION_JSON})
        @Consumes(MediaType.TEXT_PLAIN)
        @Path("/{name}/{family}")
        public Response echoGet(
                @PathParam("name") String name,
                @PathParam("family") String family,
                String Desc
        ) {
            Map<String, Object> resp = new HashMap<>();
            resp.put("success", "true");
            resp.put("Name", name);
            resp.put("Family", family);
            resp.put("Desc", Desc);
            Response.ResponseBuilder rb = Response.ok(resp,
MediaType.APPLICATION_JSON).status(Response.Status.OK);
            return rb.build();
        }
    }

and send data to RESTFul API like this:


问:
I cannot parse multi-row json array and put it into the html elements

var dataJSON = '[{"FeeType":"Domestic POS Declined Fee","FeeDescription":"per declined transaction","FeeAmount":"0.50"},{"FeeType":"Domestic PIN Declined Fee","FeeDescription":"per declined transaction","FeeAmount":"0.50"},{"FeeType":"International POS Declined Fee","FeeDescription":"per declined transaction","FeeAmount":"0.95"},{"FeeType":"International PIN Declined Fee ","FeeDescription":"per declined transaction","FeeAmount":"0.95"},{"FeeType":"ATM Domestic Fee 1","FeeDescription":"One (1) no cost ATM withdrawal per deposit1, then $1.75 per transaction thereafter","FeeAmount":"1.75"},{"FeeType":"Domestic ATM Balance Inquiry Fee 1","FeeDescription":"per ATM Balance Inquiry","FeeAmount":"0.50"},{"FeeType":"Domestic ATM Declined Fee 1","FeeDescription":"per declined transaction","FeeAmount":"0.50"},{"FeeType":"International ATM Withdrawal Fee 1","FeeDescription":"per transaction","FeeAmount":"3.00"},{"FeeType":"International ATM Balance Fee ","FeeDescription":"per ATM Balance Inquiry","FeeAmount":"0.95"},{"FeeType":"International ATM Declined Fee","FeeDescription":"per declined transaction","FeeAmount":"0.95"},{"FeeType":"OTC Withdrawal Fee","FeeDescription":"per transaction","FeeAmount":"4.00"},{"FeeType":"International OTC Withdrawal Fee","FeeDescription":"per transaction","FeeAmount":"4.00"},{"FeeType":"Currency Conversion Fee","FeeDescription":"3% of transaction amount","FeeAmount":"3.00%"},{"FeeType":"Card Replacement Fee","FeeDescription":"One (1) no cost replacement per calendar year or upon expiration; $5.00 per request thereafter for lost, stolen, and damaged cards.","FeeAmount":"5.00"},{"FeeType":" Expedited Card Replacement Fee ","FeeDescription":"$20.00 (per Card; an additional fee when a Card is reissued or replaced for any reason with requested expedited delivery)","FeeAmount":"20.00"},{"FeeType":"Check Refund Fee","FeeDescription":"$12.50 per refund check (When a refund check is issued for the remaining Card balance.","FeeAmount":"12.5"}]';

var dataObject = JSON.parse(dataJSON);
var listItemString = $('#listItem').html();

dataObject.forEach(buildNewList);

function buildNewList(item, index) {
  var listItem = $('
' + listItemString + '
');
  var listItemTitle = $('.title', listItem);
  listItemTitle.html(item.FeeType);
  var listItemDesc = $('.description', listItem);
  listItemDesc.html(item.FeeDescription);
  $('#myUL').append(listItem);
}

var myObj2 = {
 "kelimeler": [
 {
   "title": "",
   "description": "T�rkiyenin en b�y�k do_rudan sat�_ _irketi"
 },
 {
   "title": "Aktif Temsilci",
   "description": "Bir kampanyada sipari_ veren ve �d�l sat�_ tutar� s�f�rdan b�y�k olan temsilci"
 },

] }```

I found some code on the internet.
var dataObject = JSON.parse(dataJSON);
this works perfectly but it is really hard for me to manage a single line json array. I just want to use myObj2 and access the title and desciption.

How can I access the elements inside myObj2 > 'keliemeler' . I tried item.kelimeler.title something but it didn't work.

Thanks.

答: item.kelimeler will never shown since it's only in myObj2, and item is taken from dataJSON that doesn't have kelimeler.</p>

Body:
var dataJSON = '[{"FeeType":"Domestic POS Declined Fee","FeeDescription":"per declined transaction","FeeAmount":"0.50"},{"FeeType":"Domestic PIN Declined Fee","FeeDescription":"per declined transaction","FeeAmount":"0.50"},{"FeeType":"International POS Declined Fee","FeeDescription":"per declined transaction","FeeAmount":"0.95"},{"FeeType":"International PIN Declined Fee ","FeeDescription":"per declined transaction","FeeAmount":"0.95"},{"FeeType":"ATM Domestic Fee 1","FeeDescription":"One (1) no cost ATM withdrawal per deposit1, then $1.75 per transaction thereafter","FeeAmount":"1.75"},{"FeeType":"Domestic ATM Balance Inquiry Fee 1","FeeDescription":"per ATM Balance Inquiry","FeeAmount":"0.50"},{"FeeType":"Domestic ATM Declined Fee 1","FeeDescription":"per declined transaction","FeeAmount":"0.50"},{"FeeType":"International ATM Withdrawal Fee 1","FeeDescription":"per transaction","FeeAmount":"3.00"},{"FeeType":"International ATM Balance Fee ","FeeDescription":"per ATM Balance Inquiry","FeeAmount":"0.95"},{"FeeType":"International ATM Declined Fee","FeeDescription":"per declined transaction","FeeAmount":"0.95"},{"FeeType":"OTC Withdrawal Fee","FeeDescription":"per transaction","FeeAmount":"4.00"},{"FeeType":"International OTC Withdrawal Fee","FeeDescription":"per transaction","FeeAmount":"4.00"},{"FeeType":"Currency Conversion Fee","FeeDescription":"3% of transaction amount","FeeAmount":"3.00%"},{"FeeType":"Card Replacement Fee","FeeDescription":"One (1) no cost replacement per calendar year or upon expiration; $5.00 per request thereafter for lost, stolen, and damaged cards.","FeeAmount":"5.00"},{"FeeType":" Expedited Card Replacement Fee ","FeeDescription":"$20.00 (per Card; an additional fee when a Card is reissued or replaced for any reason with requested expedited delivery)","FeeAmount":"20.00"},{"FeeType":"Check Refund Fee","FeeDescription":"$12.50 per refund check (When a refund check is issued for the remaining Card balance.","FeeAmount":"12.5"}]';

var dataObject = JSON.parse(dataJSON);
var listItemString = $('#listItem').html();

dataObject.forEach(buildNewList);

function buildNewList(item, index) {
  var listItem = $('
' + listItemString + '
');
  var listItemTitle = $('.title', listItem);
  listItemTitle.html(item.FeeType);
  var listItemDesc = $('.description', listItem);
  listItemDesc.html(item.FeeDescription);
  $('#myUL').append(listItem);
}

var myObj2 = {
 "kelimeler": [
 {
   "title": "",
   "description": "T�rkiyenin en b�y�k do_rudan sat�_ _irketi"
 },
 {
   "title": "Aktif Temsilci",
   "description": "Bir kampanyada sipari_ veren ve �d�l sat�_ tutar� s�f�rdan b�y�k olan temsilci"
 },

] }

I found some code on the internet.
var dataObject = JSON.parse(dataJSON);
this works perfectly but it is really hard for me to manage a single line json array. I just want to use myObj2 and access the title and desciption.

How can I access the elements inside myObj2 > 'keliemeler' . I tried item.kelimeler.title something but it didn't work.

Thanks.


问:
Show Result of Query in JSON format in MVC Model
I wanna fetch some data from a database and show them in JSON format. Im using MVC model. I don't know how to do that.

This is my DAO:

```<code>public static List<NewsModel> getAll() {

        Connection con = ConnectionManagment.CreateConnection();
        List<NewsModel> newsList = new ArrayList<>();

        try {

            java.sql.PreparedStatement ps = con
                    .prepareStatement("select j.title,
               j.content, j.displayDate from JournalArticle  j LIMIT 5");

            ResultSet rs = ps.executeQuery();
            while (rs.next()) {
                NewsModel news = new NewsModel();
                news.setTitle(rs.getString("title"));
                String date = rs.getString("displayDate");
                SimpleDateFormat smpl = new
                               SimpleDateFormat("yyyy-MM-dd");
                news.setDisplayDate(smpl.parse(date));
                news.setContent(rs.getString("content"));

                newsList.add(news);

            }

        } catch (Exception e) {

            e.printStackTrace();
        }

        return newsList;
}

</code>```

This is my servlet :

```<code>List<NewsModel> news = (List<NewsModel>) new NewsModel();
news = SaipaDAO.getAll();

JSONArray newsArr = new JSONArray();
for (Object n : news) {
    JSONObject newsObj = new JSONObject();
}
</code>```

答:
Simple choice is to use Gson library.

Then:

```<code>NewsModel obj = new NewsModel ();
Gson gson = new Gson();
String json = gson.toJson(obj); //convert
System.out.println(json);
</code>```

This question is interesting too. Check it if you want.

Body:
I wanna fetch some data from a database and show them in JSON format. Im using MVC model. I don't know how to do that.

This is my DAO:

public static List<NewsModel> getAll() {

        Connection con = ConnectionManagment.CreateConnection();
        List<NewsModel> newsList = new ArrayList<>();

        try {

            java.sql.PreparedStatement ps = con
                    .prepareStatement("select j.title,
               j.content, j.displayDate from JournalArticle  j LIMIT 5");

            ResultSet rs = ps.executeQuery();
            while (rs.next()) {
                NewsModel news = new NewsModel();
                news.setTitle(rs.getString("title"));
                String date = rs.getString("displayDate");
                SimpleDateFormat smpl = new
                               SimpleDateFormat("yyyy-MM-dd");
                news.setDisplayDate(smpl.parse(date));
                news.setContent(rs.getString("content"));

                newsList.add(news);

            }

        } catch (Exception e) {

            e.printStackTrace();
        }

        return newsList;
}

This is my servlet :

List<NewsModel> news = (List<NewsModel>) new NewsModel();
news = SaipaDAO.getAll();

JSONArray newsArr = new JSONArray();
for (Object n : news) {
    JSONObject newsObj = new JSONObject();
}

Body:
Simple choice is to use Gson library.

Then:

NewsModel obj = new NewsModel ();
Gson gson = new Gson();
String json = gson.toJson(obj); //convert
System.out.println(json);

This question is interesting too. Check it if you want.


问:
How to load and draw emojis on canvas efficiently?
I would like to print an emoji on html canvas.

It can be done using images, but it is cumbersome. Is there a better way?

const canvas = document.querySelector("#canvas");
const contex = canvas.getContext("2d");

var img = new Image();
img.src = "emoji.jpg";
img.addEventListener(
  "load",
  () => {
    context.drawImage(img, 0, 0, 200, 200);
  }
);
img.src = "img.jpg";```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#canvas {
  background: red;
}</code>```

<canvas id="canvas"></canvas>```

Edit:

Okey, I think my question is misunderstood. I am able to draw emoji as an image on canvas. I don't want to do that. Because I have to screenshot all the emojis and crop them before printing them on canvas, which is cumbersome. I am looking for a more efficient way.

答:
If you don't want to use images then I have an example here that is pure coding. As you can see it requires way more coding tho.

index.html

```<code><!doctype html>
<html lang="en">
<head>
<title>Smiley Face</title>
<meta charset="utf-8" />

   <link rel="stylesheet" href="css/smiley.css" >

</head>
<body>
    <canvas width="600" height="600" id="smiley">
        <p>You need canvas!</p>
        <p>This example requires a browser that supports the
        <a href="http://www.w3.org/html/wg/html5/">HTML5</a>
        <canvas> feature.</p>
    </canvas>
    <script src="js/smiley.js"></script>
</body>
</html>
</code>```

smiley.js

```<code>//smileyView Object literal
class smileyComponent {
  constructor() {
    //initialise window, cv & ctx, drawSmiley & call drawsmiley
    this._window = this;
    this._cv = document.getElementById('smiley');
    this._ctx = this._cv.getContext('2d');
    this.drawSmiley();
  }
  //getters
  get window() {
    return this._window;
  }
  get cv() {
    return this._cv;
  }
  get ctx() {
    return this._ctx;
  }

  drawArc(x, y, radius, startAngle, endAngle, clockwise) {
    this._ctx.arc(x, y, radius, startAngle, endAngle, clockwise);
  }
  drawLine(xs, ys, xe, ye) {
    this._ctx.moveTo(xs, ys);
    this._ctx.lineTo(xe, ye);
  }
  drawSmiley() {
    //initialise lineWidth & fillStyle
    this._ctx.fillStyle = "yellow";
    this._ctx.strokeStyle = "black";
    this._ctx.lineWidth = 5;

    //head
    this._ctx.beginPath();
    this.drawArc(300,300,200,smileyComponent.degreesToRadians(0),smileyComponent.degreesToRadians(360),true);
    this._ctx.fill();

    //left eye
    this._ctx.beginPath();
    this.drawArc(200,200,50,smileyComponent.degreesToRadians(0),smileyComponent.degreesToRadians(360),true);
    this._ctx.fillStyle = "black";
    this._ctx.fill();
    this._ctx.beginPath();
    this.drawArc(220,220,25,smileyComponent.degreesToRadians(0),smileyComponent.degreesToRadians(360),true);
    this._ctx.fillStyle = "white";
    this._ctx.fill();

    //right eye
    this._ctx.beginPath();
    this.drawArc(400,200,50,smileyComponent.degreesToRadians(0),smileyComponent.degreesToRadians(360),true);
    this._ctx.fillStyle = "black";
    this._ctx.fill();
    this._ctx.beginPath();
    this.drawArc(420,220,25,smileyComponent.degreesToRadians(0),smileyComponent.degreesToRadians(360),true);
    this._ctx.fillStyle = "white";
    this._ctx.fill();

    //nose
    this._ctx.beginPath();
    this.drawLine(300,350,300,250);
    this._ctx.stroke();

    //smile
    this._ctx.beginPath();
    this.drawArc(300,300,150,smileyComponent.degreesToRadians(160),smileyComponent.degreesToRadians(380),true);
    this._ctx.stroke();
  }

  static degreesToRadians(degrees) {
    return degrees * Math.PI / 180;
  }
}
window.onload = () => new smileyComponent();

</code>```

You can check the result here.

Body:
I would like to print an emoji on html canvas.

It can be done using images, but it is cumbersome. Is there a better way?

const canvas = document.querySelector("#canvas");
const contex = canvas.getContext("2d");

var img = new Image();
img.src = "emoji.jpg";
img.addEventListener(
  "load",
  () => {
    context.drawImage(img, 0, 0, 200, 200);
  }
);
img.src = "img.jpg";

#canvas {
  background: red;
}

<canvas id="canvas"></canvas>

Edit:

Okey, I think my question is misunderstood. I am able to draw emoji as an image on canvas. I don't want to do that. Because I have to screenshot all the emojis and crop them before printing them on canvas, which is cumbersome. I am looking for a more efficient way.

Body:
If you don't want to use images then I have an example here that is pure coding. As you can see it requires way more coding tho.

index.html

<!doctype html>
<html lang="en">
<head>
<title>Smiley Face</title>
<meta charset="utf-8" />

   <link rel="stylesheet" href="css/smiley.css" >

</head>
<body>
    <canvas width="600" height="600" id="smiley">
        <p>You need canvas!</p>
        <p>This example requires a browser that supports the
        <a href="http://www.w3.org/html/wg/html5/">HTML5</a>
        &lt;canvas&gt; feature.</p>
    </canvas>
    <script src="js/smiley.js"></script>
</body>
</html>

smiley.js

//smileyView Object literal
class smileyComponent {
  constructor() {
    //initialise window, cv & ctx, drawSmiley & call drawsmiley
    this._window = this;
    this._cv = document.getElementById('smiley');
    this._ctx = this._cv.getContext('2d');
    this.drawSmiley();
  }
  //getters
  get window() {
    return this._window;
  }
  get cv() {
    return this._cv;
  }
  get ctx() {
    return this._ctx;
  }

  drawArc(x, y, radius, startAngle, endAngle, clockwise) {
    this._ctx.arc(x, y, radius, startAngle, endAngle, clockwise);
  }
  drawLine(xs, ys, xe, ye) {
    this._ctx.moveTo(xs, ys);
    this._ctx.lineTo(xe, ye);
  }
  drawSmiley() {
    //initialise lineWidth & fillStyle
    this._ctx.fillStyle = "yellow";
    this._ctx.strokeStyle = "black";
    this._ctx.lineWidth = 5;

    //head
    this._ctx.beginPath();
    this.drawArc(300,300,200,smileyComponent.degreesToRadians(0),smileyComponent.degreesToRadians(360),true);
    this._ctx.fill();

    //left eye
    this._ctx.beginPath();
    this.drawArc(200,200,50,smileyComponent.degreesToRadians(0),smileyComponent.degreesToRadians(360),true);
    this._ctx.fillStyle = "black";
    this._ctx.fill();
    this._ctx.beginPath();
    this.drawArc(220,220,25,smileyComponent.degreesToRadians(0),smileyComponent.degreesToRadians(360),true);
    this._ctx.fillStyle = "white";
    this._ctx.fill();

    //right eye
    this._ctx.beginPath();
    this.drawArc(400,200,50,smileyComponent.degreesToRadians(0),smileyComponent.degreesToRadians(360),true);
    this._ctx.fillStyle = "black";
    this._ctx.fill();
    this._ctx.beginPath();
    this.drawArc(420,220,25,smileyComponent.degreesToRadians(0),smileyComponent.degreesToRadians(360),true);
    this._ctx.fillStyle = "white";
    this._ctx.fill();

    //nose
    this._ctx.beginPath();
    this.drawLine(300,350,300,250);
    this._ctx.stroke();

    //smile
    this._ctx.beginPath();
    this.drawArc(300,300,150,smileyComponent.degreesToRadians(160),smileyComponent.degreesToRadians(380),true);
    this._ctx.stroke();
  }

  static degreesToRadians(degrees) {
    return degrees * Math.PI / 180;
  }
}
window.onload = () => new smileyComponent();

You can check the result here.


问:
How to fix : expected at most 1 argument, got 3
I am trying to ask the user about their favorite subject, but I get the following error message:

Traceback (most recent call last):

File "C:\Users\BillyG\Documents\Revision\ICT\Challenge 5.py", line 2, in
  module

favesub = input("Hello what is your favourite subject", firstname, "?")

TypeError: input expected at most 1 arguments, got 3

The code is:

```<code>firstname=input("What is your name: ")
favesub = input("Hello what is your favorite subject", firstname, "?")
print ("I love ", favesub, "aswell")
</code>```

答:
input() only takes one argument, but you're providing 3.

Try

```<code>input(f"Hello what is your favourite subject {firstname}?")
</code>```

Body:
I am trying to ask the user about their favorite subject, but I get the following error message:

Traceback (most recent call last):

File "C:\Users\BillyG\Documents\Revision\ICT\Challenge 5.py", line 2, in
  module

favesub = input("Hello what is your favourite subject", firstname, "?")

TypeError: input expected at most 1 arguments, got 3

The code is:

firstname=input("What is your name: ")
favesub = input("Hello what is your favorite subject", firstname, "?")
print ("I love ", favesub, "aswell")

Body:
input() only takes one argument, but you're providing 3.

Try

input(f"Hello what is your favourite subject {firstname}?")


问:
Correct way to write copy constructor and assignment operator
I have a data structure, where I have function Ins(key, value) that insert them into the data structure. I am trying to write copy constructor and assignment operator. I don't know if only this part of code will be enough I can also add the rest. Somehow there is a mistake in this code.

The problem is with Ins(temp -> m_Key, temp -> m_Val); both times.

```<code>CHash(const CHash & src)
{
  m_Table = new TItem * [src.m_Size];
  TItem * temp = src.m_FirstOrder;
  while (temp != NULL)
  {
    Ins(temp -> m_Key, temp -> m_Val);
    temp = temp -> m_NextOrder;
  }
}

CHash & operator = (const CHash & src)
{
  TItem * temp = m_FirstOrder;
  while (temp != NULL)
  {
    TItem * tmp = temp;
    temp = temp -> m_NextOrder;
    delete tmp;
  }
  delete [] m_Table;

  m_Table = new TItem * [src.m_Size];
  TItem * tmp1 = src.m_FirstOrder;
  while (tmp1 != NULL)
  {
    Ins(tmp1 -> m_Key, tmp1 -> m_Val);
    tmp1 = tmp1 -> m_NextOrder;
  }
}
</code>```

I try this in main and get segfault.

```<code>CHash hashtable(100);
CHash hash2(50);
hash2 = hashtable;
hashtable.printAll();
hash2.printAll();
CHash b(hash2);
b.printAll();
</code>```

This is the complete code:

```<code>#include <string>
#include <iostream>
#include <bits/stdc++.h>
using namespace std;

struct TItem {
    TItem(string key, string val, TItem* nextHash,TItem* nextOrd, TItem * prevOrd)
    :m_Key(key),m_Val(val),m_NextHash(nextHash),m_NextOrder(nextOrd),m_PrevOrder(prevOrd){}

    string m_Key,m_Val;
    TItem * m_NextHash, * m_NextOrder, * m_PrevOrder;
};

class CHash{
public:
    CHash (int m) : m_Table(NULL),m_Size(m),m_FirstOrder(NULL),m_LastOrder(NULL)
    {
      m_Table = new TItem * [m];
      for (int i = 0; i < m; i++)
        m_Table[i] = NULL;
    }

    ~CHash()
    {
      TItem * temp = m_FirstOrder;
      while (temp != NULL)
      {
        TItem * tmp = temp;
        temp = temp -> m_NextOrder;
        delete tmp;
      }
      delete [] m_Table;
    }

    bool IsSet(string key)
    {
      TItem * temp = m_Table[hashFn(key)];
      if (temp == NULL)
      {
        return false;
      }
      while (temp != NULL)
      {
        if (temp -> m_Key == key)
        {
          return true;
        }
        temp = temp -> m_NextHash;
      }
      return false;
    }

    CHash(const CHash & src)
    {
      m_Size = src.m_Size;
      m_Table = new TItem * [src.m_Size];
      for (int i = 0; i < src.m_Size; i++)
        m_Table[i] = NULL;
      TItem * temp = src.m_FirstOrder;
      while (temp != NULL)
      {
        Ins(temp -> m_Key, temp -> m_Val);
        temp = temp -> m_NextOrder;
      }
    }

    CHash & operator = (const CHash & src)
    {
      m_Size = src.m_Size;
      TItem * temp = m_FirstOrder;
      while (temp != NULL)
      {
        TItem * tmp = temp;
        temp = temp -> m_NextOrder;
        delete tmp;
      }
      delete [] m_Table;

      m_Table = new TItem * [src.m_Size];
      for (int i = 0; i < src.m_Size; i++)
        m_Table[i] = NULL;
      TItem * tmp1 = src.m_FirstOrder;
      while (tmp1 != NULL)
      {
        Ins(tmp1 -> m_Key, tmp1 -> m_Val);
        tmp1 = tmp1 -> m_NextOrder;
      }
    }

    bool Ins(const string & key, const string & val)
    {
      string help = key;
      if (IsSet(help))
        return false;
      //first element added ever
      if (m_FirstOrder == NULL)
      {
        TItem * tmp01 = new TItem(key, val, NULL, NULL, NULL);
        m_Table[hashFn(help)] = tmp01;
        m_FirstOrder = m_LastOrder = tmp01;
      }
      else
      {
        TItem * temp = m_Table[hashFn(help)];
        //first added to that hash
        if (temp == NULL)
        {
          TItem * tmp02 = new TItem(key, val, NULL, NULL, m_LastOrder);
          m_Table[hashFn(help)] = tmp02;
          m_LastOrder -> m_NextOrder = tmp02;
          m_LastOrder = tmp02;
        }
        else
        {
          while (temp -> m_NextHash != NULL)
          {
            temp = temp -> m_NextHash;
          }
          TItem * tmp03 = new TItem(key, val, NULL, NULL, m_LastOrder);
          temp -> m_NextHash = tmp03;
          m_LastOrder -> m_NextOrder = tmp03;
          m_LastOrder = tmp03;
        }
      }
      return true;
    }

    bool Del (const string & key)
    {
      string help = key;
      if (!IsSet(help))
        return false;

      TItem * temp = m_Table[hashFn(help)];

      if (temp == NULL)
        return false;

      while (temp != NULL)
      {
        if (temp -> m_Key == key)
          break;
        temp = temp -> m_NextHash;
      }

      if (temp == NULL)
        return false;

      if (m_FirstOrder == temp)
        m_FirstOrder = m_FirstOrder -> m_NextOrder;
      else
        temp -> m_PrevOrder -> m_NextOrder = temp -> m_NextOrder;
      if (m_LastOrder == temp)
        m_LastOrder = m_LastOrder -> m_PrevOrder;

      m_Table[hashFn(help)] = temp -> m_NextHash;
      delete temp;
      return true;
    }

    template <typename func>
    void ForEach(func f)
    {

    }
    void printAll()
    {
      cout << "PRINTING" << endl;
      TItem * temp = m_FirstOrder;
      while (temp != NULL)
      {
        cout << "  :  " << temp -> m_Val << " : ";
        temp = temp -> m_NextOrder;
      }
      cout << endl;
    }

private:
    TItem **        m_Table;
    unsigned int    m_Size;
    TItem *         m_FirstOrder, * m_LastOrder;
    unsigned int hashFn(string & str){
        std::hash<std::string> hash_fn;
        return hash_fn(str)%m_Size;
    }
};

int main(int argc, char** argv) {

    CHash hashtable(100);
    CHash hash2(50);
    hashtable.Ins("h1","car");
    assert ( !hashtable.Ins("h1","phone"));
    hashtable.Ins("h2","field");
    hashtable.Ins("h3","house");
    hashtable.Ins("h4","tree");
    hashtable.printAll();
    assert ( hashtable.Del("h3") );
    assert ( !hashtable.Ins("h4","tree") );
    assert(!hashtable.Del("h4d"));
    assert(hashtable.Del("h1"));
    assert(!hashtable.Del("h3"));
    assert(!hashtable.Del("h1"));
    hash2 = hashtable;
    hashtable.printAll();
    hash2.printAll();
    CHash b(hash2);
    b.printAll();

    hashtable.ForEach([](TItem * it ){
        cout<<it->m_Key<<" - "<<it->m_Val<<endl;
    });

    return 0;
}
</code>```

I run it like this:  g++ -std=c++11 -g filename.cpp

答:
I see several problems in your code.

The assignment operator doesn't return *this.

The copy constructor doesn't initialize m_FirstOrder and m_LastOrder.

Lots of copypaste making the code hard to read and error-prone.

If we fix the problems we get:

```<code>class CHash{
public:
    CHash (int m)
    {
      initialize(m);
    }

    ~CHash()
    {
      finalize();
    }

    CHash(const CHash & src)
    {
      initialize(src.m_Size);
      copy(src.m_FirstOrder);
    }

    CHash & operator = (const CHash & src)
    {
      if (&src == this)
        return;
      finalize();
      initialize(src.m_Size);
      copy(src.m_FirstOrder);
      return *this;
    }

    ...

private:
    ...

    void initialize(int m)
    {
      m_Size = m;
      m_Table = new TItem * [m];
      for (int i = 0; i < m; i++)
        m_Table[i] = NULL;
      m_FirstOrder = NULL;
      m_LastOrder  = NULL;
    }

    void finalize()
    {
      TItem * temp = m_FirstOrder;
      while (temp != NULL)
      {
        TItem * tmp = temp;
        temp = temp -> m_NextOrder;
        delete tmp;
      }
      delete [] m_Table;
    }

    void copy(TItem *src)
    {
      while (src != NULL)
      {
        Ins(src -> m_Key, src -> m_Val);
        src = src -> m_NextOrder;
      }
    }
};
</code>```

I wonder though, why you don't use nullptr instead of NULL and std::vector<TItem*> instead of TItem**...

Body:
I have a data structure, where I have function Ins(key, value) that insert them into the data structure. I am trying to write copy constructor and assignment operator. I don't know if only this part of code will be enough I can also add the rest. Somehow there is a mistake in this code.

The problem is with Ins(temp -> m_Key, temp -> m_Val); both times.

CHash(const CHash & src)
{
  m_Table = new TItem * [src.m_Size];
  TItem * temp = src.m_FirstOrder;
  while (temp != NULL)
  {
    Ins(temp -> m_Key, temp -> m_Val);
    temp = temp -> m_NextOrder;
  }
}

CHash & operator = (const CHash & src)
{
  TItem * temp = m_FirstOrder;
  while (temp != NULL)
  {
    TItem * tmp = temp;
    temp = temp -> m_NextOrder;
    delete tmp;
  }
  delete [] m_Table;

  m_Table = new TItem * [src.m_Size];
  TItem * tmp1 = src.m_FirstOrder;
  while (tmp1 != NULL)
  {
    Ins(tmp1 -> m_Key, tmp1 -> m_Val);
    tmp1 = tmp1 -> m_NextOrder;
  }
}

I try this in main and get segfault.

CHash hashtable(100);
CHash hash2(50);
hash2 = hashtable;
hashtable.printAll();
hash2.printAll();
CHash b(hash2);
b.printAll();

This is the complete code:

#include <string>
#include <iostream>
#include <bits/stdc++.h>
using namespace std;

struct TItem {
    TItem(string key, string val, TItem* nextHash,TItem* nextOrd, TItem * prevOrd)
    :m_Key(key),m_Val(val),m_NextHash(nextHash),m_NextOrder(nextOrd),m_PrevOrder(prevOrd){}

    string m_Key,m_Val;
    TItem * m_NextHash, * m_NextOrder, * m_PrevOrder;
};

class CHash{
public:
    CHash (int m) : m_Table(NULL),m_Size(m),m_FirstOrder(NULL),m_LastOrder(NULL)
    {
      m_Table = new TItem * [m];
      for (int i = 0; i < m; i++)
        m_Table[i] = NULL;
    }

    ~CHash()
    {
      TItem * temp = m_FirstOrder;
      while (temp != NULL)
      {
        TItem * tmp = temp;
        temp = temp -> m_NextOrder;
        delete tmp;
      }
      delete [] m_Table;
    }

    bool IsSet(string key)
    {
      TItem * temp = m_Table[hashFn(key)];
      if (temp == NULL)
      {
        return false;
      }
      while (temp != NULL)
      {
        if (temp -> m_Key == key)
        {
          return true;
        }
        temp = temp -> m_NextHash;
      }
      return false;
    }

    CHash(const CHash & src)
    {
      m_Size = src.m_Size;
      m_Table = new TItem * [src.m_Size];
      for (int i = 0; i < src.m_Size; i++)
        m_Table[i] = NULL;
      TItem * temp = src.m_FirstOrder;
      while (temp != NULL)
      {
        Ins(temp -> m_Key, temp -> m_Val);
        temp = temp -> m_NextOrder;
      }
    }

    CHash & operator = (const CHash & src)
    {
      m_Size = src.m_Size;
      TItem * temp = m_FirstOrder;
      while (temp != NULL)
      {
        TItem * tmp = temp;
        temp = temp -> m_NextOrder;
        delete tmp;
      }
      delete [] m_Table;

      m_Table = new TItem * [src.m_Size];
      for (int i = 0; i < src.m_Size; i++)
        m_Table[i] = NULL;
      TItem * tmp1 = src.m_FirstOrder;
      while (tmp1 != NULL)
      {
        Ins(tmp1 -> m_Key, tmp1 -> m_Val);
        tmp1 = tmp1 -> m_NextOrder;
      }
    }

    bool Ins(const string & key, const string & val)
    {
      string help = key;
      if (IsSet(help))
        return false;
      //first element added ever
      if (m_FirstOrder == NULL)
      {
        TItem * tmp01 = new TItem(key, val, NULL, NULL, NULL);
        m_Table[hashFn(help)] = tmp01;
        m_FirstOrder = m_LastOrder = tmp01;
      }
      else
      {
        TItem * temp = m_Table[hashFn(help)];
        //first added to that hash
        if (temp == NULL)
        {
          TItem * tmp02 = new TItem(key, val, NULL, NULL, m_LastOrder);
          m_Table[hashFn(help)] = tmp02;
          m_LastOrder -> m_NextOrder = tmp02;
          m_LastOrder = tmp02;
        }
        else
        {
          while (temp -> m_NextHash != NULL)
          {
            temp = temp -> m_NextHash;
          }
          TItem * tmp03 = new TItem(key, val, NULL, NULL, m_LastOrder);
          temp -> m_NextHash = tmp03;
          m_LastOrder -> m_NextOrder = tmp03;
          m_LastOrder = tmp03;
        }
      }
      return true;
    }

    bool Del (const string & key)
    {
      string help = key;
      if (!IsSet(help))
        return false;

      TItem * temp = m_Table[hashFn(help)];

      if (temp == NULL)
        return false;

      while (temp != NULL)
      {
        if (temp -> m_Key == key)
          break;
        temp = temp -> m_NextHash;
      }

      if (temp == NULL)
        return false;

      if (m_FirstOrder == temp)
        m_FirstOrder = m_FirstOrder -> m_NextOrder;
      else
        temp -> m_PrevOrder -> m_NextOrder = temp -> m_NextOrder;
      if (m_LastOrder == temp)
        m_LastOrder = m_LastOrder -> m_PrevOrder;

      m_Table[hashFn(help)] = temp -> m_NextHash;
      delete temp;
      return true;
    }

    template <typename func>
    void ForEach(func f)
    {

    }
    void printAll()
    {
      cout << "PRINTING" << endl;
      TItem * temp = m_FirstOrder;
      while (temp != NULL)
      {
        cout << "  :  " << temp -> m_Val << " : ";
        temp = temp -> m_NextOrder;
      }
      cout << endl;
    }

private:
    TItem **        m_Table;
    unsigned int    m_Size;
    TItem *         m_FirstOrder, * m_LastOrder;
    unsigned int hashFn(string & str){
        std::hash<std::string> hash_fn;
        return hash_fn(str)%m_Size;
    }
};

int main(int argc, char** argv) {

    CHash hashtable(100);
    CHash hash2(50);
    hashtable.Ins("h1","car");
    assert ( !hashtable.Ins("h1","phone"));
    hashtable.Ins("h2","field");
    hashtable.Ins("h3","house");
    hashtable.Ins("h4","tree");
    hashtable.printAll();
    assert ( hashtable.Del("h3") );
    assert ( !hashtable.Ins("h4","tree") );
    assert(!hashtable.Del("h4d"));
    assert(hashtable.Del("h1"));
    assert(!hashtable.Del("h3"));
    assert(!hashtable.Del("h1"));
    hash2 = hashtable;
    hashtable.printAll();
    hash2.printAll();
    CHash b(hash2);
    b.printAll();

    hashtable.ForEach([](TItem * it ){
        cout<<it->m_Key<<" - "<<it->m_Val<<endl;
    });

    return 0;
}

I run it like this:  g++ -std=c++11 -g filename.cpp

Body:
I see several problems in your code.

The assignment operator doesn't return *this.

The copy constructor doesn't initialize m_FirstOrder and m_LastOrder.

Lots of copypaste making the code hard to read and error-prone.

If we fix the problems we get:

class CHash{
public:
    CHash (int m)
    {
      initialize(m);
    }

    ~CHash()
    {
      finalize();
    }

    CHash(const CHash & src)
    {
      initialize(src.m_Size);
      copy(src.m_FirstOrder);
    }

    CHash & operator = (const CHash & src)
    {
      if (&src == this)
        return;
      finalize();
      initialize(src.m_Size);
      copy(src.m_FirstOrder);
      return *this;
    }

    ...

private:
    ...

    void initialize(int m)
    {
      m_Size = m;
      m_Table = new TItem * [m];
      for (int i = 0; i < m; i++)
        m_Table[i] = NULL;
      m_FirstOrder = NULL;
      m_LastOrder  = NULL;
    }

    void finalize()
    {
      TItem * temp = m_FirstOrder;
      while (temp != NULL)
      {
        TItem * tmp = temp;
        temp = temp -> m_NextOrder;
        delete tmp;
      }
      delete [] m_Table;
    }

    void copy(TItem *src)
    {
      while (src != NULL)
      {
        Ins(src -> m_Key, src -> m_Val);
        src = src -> m_NextOrder;
      }
    }
};

I wonder though, why you don't use nullptr instead of NULL and std::vector<TItem*> instead of TItem**...


问:
Sanitizing JSON Strings without \
Given successful query from SQL SELECT result, there are json output with \n and \ . That makes me confusions and obstacles to deserialise the json string into array of objects. Would you please tell me the way to replace all those json strings without newlines , spaces, and also blackslashes \ ?

```<code>  dicts = [dict(row) for row in result]
  j = json.dumps(dicts ,  sort_keys=True,
  indent=None,
  default=default , separators=(',', ':'))

  return {
    'result':  j
  }
</code>```

Here is my output json with many back slashes \

```<code>{"result": "[{\"_access\":[{\"level\":\"read\",\"public\":true}],\"_created_at\":\"2019-05-26T09:57:10.494525\",\"_created_by\":\"473ee711-19a0-4309-8cb2-7f672fd93224\",\"_database_id\":\"\",\"_id\":\"3f674e29-29ba-4dcf-b9d9-f99a3c35866e\",\"_owner_id\":\"473ee711-19a0-4309-8cb2-7f672fd93224\",\"_updated_at\":\"2019-05-26T10:01:14.691527\",\"_updated_by\":\"473ee711-19a0-4309-8cb2-7f672fd93224\",\"book_label\":\"B198\",\"deleted_at\":null,\"deleted_by\":null,\"free_assign_date\":null,\"free_assign_end_date\":null,\"is_completed\":false,\"is_free_assigned\":true,\"progress_chapter\":1,\"total_chapters\":2,\"user_label\":\"user10\"}]"}
</code>```

Title: Sanitizing JSON Strings without \

Body:
Given successful query from SQL SELECT result, there are json output with \n and \ . That makes me confusions and obstacles to deserialise the json string into array of objects. Would you please tell me the way to replace all those json strings without newlines , spaces, and also blackslashes \ ?

  dicts = [dict(row) for row in result]
  j = json.dumps(dicts ,  sort_keys=True,
  indent=None,
  default=default , separators=(',', ':'))

  return {
    'result':  j
  }

Here is my output json with many back slashes \

{"result": "[{\"_access\":[{\"level\":\"read\",\"public\":true}],\"_created_at\":\"2019-05-26T09:57:10.494525\",\"_created_by\":\"473ee711-19a0-4309-8cb2-7f672fd93224\",\"_database_id\":\"\",\"_id\":\"3f674e29-29ba-4dcf-b9d9-f99a3c35866e\",\"_owner_id\":\"473ee711-19a0-4309-8cb2-7f672fd93224\",\"_updated_at\":\"2019-05-26T10:01:14.691527\",\"_updated_by\":\"473ee711-19a0-4309-8cb2-7f672fd93224\",\"book_label\":\"B198\",\"deleted_at\":null,\"deleted_by\":null,\"free_assign_date\":null,\"free_assign_end_date\":null,\"is_completed\":false,\"is_free_assigned\":true,\"progress_chapter\":1,\"total_chapters\":2,\"user_label\":\"user10\"}]"}

Body:
import json
result_str = "[{\"_access\":[{\"level\":\"read\",\"public\":true}],\"_created_at\":\"2019-05-26T09:57:10.494525\",\"_created_by\":\"473ee711-19a0-4309-8cb2-7f672fd93224\",\"_database_id\":\"\",\"_id\":\"3f674e29-29ba-4dcf-b9d9-f99a3c35866e\",\"_owner_id\":\"473ee711-19a0-4309-8cb2-7f672fd93224\",\"_updated_at\":\"2019-05-26T10:01:14.691527\",\"_updated_by\":\"473ee711-19a0-4309-8cb2-7f672fd93224\",\"book_label\":\"B198\",\"deleted_at\":null,\"deleted_by\":null,\"free_assign_date\":null,\"free_assign_end_date\":null,\"is_completed\":false,\"is_free_assigned\":true,\"progress_chapter\":1,\"total_chapters\":2,\"user_label\":\"user10\"}]"

js_obj = json.loads(result_str)

print json.dumps(js_obj)

have a try


答: input expects a single string, so unlike print, where you can append multiple arguments and the string will be parsed as is, you have to format the string yourself. For Python 3.6 and higher, user input(f"Hello what is your favourite subject {firstname}?") or input("Hello what is your favourite subject {}?".format(firstname)) if you're using an older version of Python 3.

Title: How to fix : expected at most 1 argument, got 3


问:
How do I include muliple figures on a PowerPoint slide in RMarkdown?
I am generating a PowerPoint presentation with R-markdown. How do I include multiple figures or "contents" on a slide?

I have tried modifying the PowerPoint template to include three content blocks as following:

But I am unable to add content to the object on the bottom right.

```<code>---
title: "pp_test"
output:
  powerpoint_presentation:
    reference_doc: pp_template3.pptx
---

```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = FALSE)
```

# Slide with 3 contents

:::::::::::::: {.columns}
::: {.column}
Text
:::
::: {.column}
```{r pressure, echo=FALSE, fig.cap="Caption"}
plot(pressure)
```
:::
::: {.column}
```{r cars, echo = TRUE}
summary(cars)
```
:::
::::::::::::::
</code>```

I expected the "summary(cars)" section to be added beneath the plot on the slide, but it is simply excluded.

答:
I was unable to succeed using r-markdown, so I researched other packages and found "officer", which was able to produce the results I wanted.

It does not support tables that are not dataframes, so I was unable to add the "summary(cars)" part. But with two plots as examples, I was able to produce the result

Using the following code

```<code>library(officer)
library(magrittr)
library(ggplot2)
setwd(mydir)

my_plot <- ggplot(data=pressure) +
  geom_point(aes(temperature, pressure))
my_summary <- as.str(summary(cars))

my_pres <-
  read_pptx("pp_template3.pptx") %>%
  add_slide(layout = "Two Content", master = "Office Theme") %>%
  ph_with_text(type = "title", index = 1, str = "The title") %>%
  ph_with_gg(type = "body", index = 1, value = my_plot) %>%
  ph_with_text(type = "body", index = 2, str = "Some text") %>%
  ph_with_gg(type = "body", index = 3, value = my_plot) %>%
  print(target = "test_pp_officer.pptx") %>%
  invisible()
</code>```

Body:
I am generating a PowerPoint presentation with R-markdown. How do I include multiple figures or "contents" on a slide?

I have tried modifying the PowerPoint template to include three content blocks as following:

But I am unable to add content to the object on the bottom right.

---
title: "pp_test"
output:
  powerpoint_presentation:
    reference_doc: pp_template3.pptx
---

```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = FALSE)
```

# Slide with 3 contents

:::::::::::::: {.columns}
::: {.column}
Text
:::
::: {.column}
```{r pressure, echo=FALSE, fig.cap="Caption"}
plot(pressure)
```
:::
::: {.column}
```{r cars, echo = TRUE}
summary(cars)
```
:::
::::::::::::::

I expected the "summary(cars)" section to be added beneath the plot on the slide, but it is simply excluded.

Body:
I was unable to succeed using r-markdown, so I researched other packages and found "officer", which was able to produce the results I wanted.

It does not support tables that are not dataframes, so I was unable to add the "summary(cars)" part. But with two plots as examples, I was able to produce the result

Using the following code

library(officer)
library(magrittr)
library(ggplot2)
setwd(mydir)

my_plot <- ggplot(data=pressure) +
  geom_point(aes(temperature, pressure))
my_summary <- as.str(summary(cars))

my_pres <-
  read_pptx("pp_template3.pptx") %>%
  add_slide(layout = "Two Content", master = "Office Theme") %>%
  ph_with_text(type = "title", index = 1, str = "The title") %>%
  ph_with_gg(type = "body", index = 1, value = my_plot) %>%
  ph_with_text(type = "body", index = 2, str = "Some text") %>%
  ph_with_gg(type = "body", index = 3, value = my_plot) %>%
  print(target = "test_pp_officer.pptx") %>%
  invisible()


问:
Binding with UpdateSourceTrigger==LostFocus do not fire for Menu or Toolbar interaction
I noticed that bindings with UpdateSourceTrigger==LostFocus do not get updated when the user activates the menu or the toolbar.

This leads to the unfortunate situation that the last change that the user made gets lost when the user selects "Save File" from the menu or toolbar.

Is there an easy way around this or do I have to change all my bindings to UpdateSourceTrigger=PropertyChanged.

答:
The problem is that the TextBox does, in fact, not lose focus when the menu item is activated. Thus, the UpdateSourceTrigger LostFocus does not fire. Depending on your (view)model, UpdateSourceTrigger PropertyChanged might or might not be a feasible workaround.

For me, PropertyChanged was not an option (I need to validate the data after the user finished entering it, not in between), so I used a workaround by calling this method before "Save File" (or any other menu/toolbar entry that requires an up-to-date model):

```<code>Public Shared Sub SaveFocusedTextBox()
    Dim focusedTextBox = TryCast(Keyboard.FocusedElement, TextBox)
    If focusedTextBox IsNot Nothing Then
        Dim be = focusedTextBox.GetBindingExpression(TextBox.TextProperty)
        If be IsNot Nothing Then be.UpdateSource()
    End If
End Sub
</code>```

A few other approaches for this problem can be found in this related question:

WPF Databind Before Saving

(In fact, credit for this method goes to rudigrobler's answer in that question.)

Body:
The problem is that the TextBox does, in fact, not lose focus when the menu item is activated. Thus, the UpdateSourceTrigger LostFocus does not fire. Depending on your (view)model, UpdateSourceTrigger PropertyChanged might or might not be a feasible workaround.

For me, PropertyChanged was not an option (I need to validate the data after the user finished entering it, not in between), so I used a workaround by calling this method before "Save File" (or any other menu/toolbar entry that requires an up-to-date model):

Public Shared Sub SaveFocusedTextBox()
    Dim focusedTextBox = TryCast(Keyboard.FocusedElement, TextBox)
    If focusedTextBox IsNot Nothing Then
        Dim be = focusedTextBox.GetBindingExpression(TextBox.TextProperty)
        If be IsNot Nothing Then be.UpdateSource()
    End If
End Sub

A few other approaches for this problem can be found in this related question:

WPF Databind Before Saving

(In fact, credit for this method goes to rudigrobler's answer in that question.)


问:
How do I allow pointer-events on an HTML5 canvas background while allowing links and buttons to receive pointer-events, too?
I set an HTML5 canvas to a background that looks like interlinked nodes (link). The canvas element works as expected but when I set it to be the background of the page, I couldn't click on links or buttons on the page.

When I set the canvas background to the back of all elements by either declaring a z-index value or editing the HTML so that it's the first element, I can normally click on links, but every time a pointer-event is active on a button (such as a hover) it stops the canvas background from getting the mouse pointer's location.

I expect it's got something to do with the pointer-events, but I can't move past this because I'm unsure as to what to do.

答:
Supposing that you put the content of your document in a div #wrap with a position absolute over the canvas, in order to interact with the particles on canvas you may use the mouse position over the #wrap. In your example I'm using wrap.addEventListener('mousemove', mousemoveHandler, false); instead of canvas.addEventListener('mousemove', mousemoveHandler, false);

(function() {

  var canvas, ctx, circ, nodes, mouse, SENSITIVITY, SIBLINGS_LIMIT, DENSITY, NODES_QTY, ANCHOR_LENGTH, MOUSE_RADIUS;

  // how close next node must be to activate connection (in px)
  // shorter distance == better connection (line width)
  SENSITIVITY = 100;
  // note that siblings limit is not 'accurate' as the node can actually have more connections than this value that's because the node accepts sibling nodes with no regard to their current connections this is acceptable because potential fix would not result in significant visual difference
  // more siblings == bigger node
  SIBLINGS_LIMIT = 10;
  // default node margin
  DENSITY = 50;
  // total number of nodes used (incremented after creation)
  NODES_QTY = 0;
  // avoid nodes spreading
  ANCHOR_LENGTH = 20;
  // highlight radius
  MOUSE_RADIUS = 200;

  circ = 2 * Math.PI;
  nodes = [];

  canvas = document.querySelector('canvas');
  resizeWindow();
  mouse = {
    x: canvas.width / 2,
    y: canvas.height / 2
  };
  ctx = canvas.getContext('2d');
  if (!ctx) {
    alert("Ooops! Your browser does not support canvas :'(");
  }

  function Node(x, y) {
    this.anchorX = x;
    this.anchorY = y;
    this.x = Math.random() * (x - (x - ANCHOR_LENGTH)) + (x - ANCHOR_LENGTH);
    this.y = Math.random() * (y - (y - ANCHOR_LENGTH)) + (y - ANCHOR_LENGTH);
    this.vx = Math.random() * 2 - 1;
    this.vy = Math.random() * 2 - 1;
    this.energy = Math.random() * 100;
    this.radius = Math.random();
    this.siblings = [];
    this.brightness = 0;
  }

  Node.prototype.drawNode = function() {
    var color = "rgba(255, 0, 0, " + this.brightness + ")";
    ctx.beginPath();
    ctx.arc(this.x, this.y, 2 * this.radius + 2 * this.siblings.length / SIBLINGS_LIMIT, 0, circ);
    ctx.fillStyle = color;
    ctx.fill();
  };

  Node.prototype.drawConnections = function() {
    for (var i = 0; i < this.siblings.length; i++) {
      var color = "rgba(255, 0, 0, " + this.brightness + ")";
      ctx.beginPath();
      ctx.moveTo(this.x, this.y);
      ctx.lineTo(this.siblings[i].x, this.siblings[i].y);
      ctx.lineWidth = 1 - calcDistance(this, this.siblings[i]) / SENSITIVITY;
      ctx.strokeStyle = color;
      ctx.stroke();
    }
  };

  Node.prototype.moveNode = function() {
    this.energy -= 2;
    if (this.energy < 1) {
      this.energy = Math.random() * 100;
      if (this.x - this.anchorX < -ANCHOR_LENGTH) {
        this.vx = Math.random() * 2;
      } else if (this.x - this.anchorX > ANCHOR_LENGTH) {
        this.vx = Math.random() * -2;
      } else {
        this.vx = Math.random() * 4 - 2;
      }
      if (this.y - this.anchorY < -ANCHOR_LENGTH) {
        this.vy = Math.random() * 2;
      } else if (this.y - this.anchorY > ANCHOR_LENGTH) {
        this.vy = Math.random() * -2;
      } else {
        this.vy = Math.random() * 4 - 2;
      }
    }
    this.x += this.vx * this.energy / 100;
    this.y += this.vy * this.energy / 100;
  };

  function initNodes() {
    ctx.clearRect(0, 0, canvas.width, canvas.height);
    nodes = [];
    for (var i = DENSITY; i < canvas.width; i += DENSITY) {
      for (var j = DENSITY; j < canvas.height; j += DENSITY) {
        nodes.push(new Node(i, j));
        NODES_QTY++;
      }
    }
  }

  function calcDistance(node1, node2) {
    return Math.sqrt(Math.pow(node1.x - node2.x, 2) + (Math.pow(node1.y - node2.y, 2)));
  }

  function findSiblings() {
    var node1, node2, distance;
    for (var i = 0; i < NODES_QTY; i++) {
      node1 = nodes[i];
      node1.siblings = [];
      for (var j = 0; j < NODES_QTY; j++) {
        node2 = nodes[j];
        if (node1 !== node2) {
          distance = calcDistance(node1, node2);
          if (distance < SENSITIVITY) {
            if (node1.siblings.length < SIBLINGS_LIMIT) {
              node1.siblings.push(node2);
            } else {
              var node_sibling_distance = 0;
              var max_distance = 0;
              var s;
              for (var k = 0; k < SIBLINGS_LIMIT; k++) {
                node_sibling_distance = calcDistance(node1, node1.siblings[k]);
                if (node_sibling_distance > max_distance) {
                  max_distance = node_sibling_distance;
                  s = k;
                }
              }
              if (distance < max_distance) {
                node1.siblings.splice(s, 1);
                node1.siblings.push(node2);
              }
            }
          }
        }
      }
    }
  }

  function redrawScene() {
    resizeWindow();
    ctx.clearRect(0, 0, canvas.width, canvas.height);
    findSiblings();
    var i, node, distance;
    for (i = 0; i < NODES_QTY; i++) {
      node = nodes[i];
      distance = calcDistance({
        x: mouse.x,
        y: mouse.y
      }, node);
      if (distance < MOUSE_RADIUS) {
        node.brightness = 1 - distance / MOUSE_RADIUS;
      } else {
        node.brightness = 0;
      }
    }
    for (i = 0; i < NODES_QTY; i++) {
      node = nodes[i];
      if (node.brightness) {
        node.drawNode();
        node.drawConnections();
      }
      node.moveNode();
    }
    requestAnimationFrame(redrawScene);
  }

  function initHandlers() {
    document.addEventListener('resize', resizeWindow, false);
    ///////////////////////////////////
    wrap.addEventListener('mousemove', mousemoveHandler, false);
    ///////////////////////////////////
  }

  function resizeWindow() {
    canvas.width = window.innerWidth;
    canvas.height = window.innerHeight;
  }

  function mousemoveHandler(e) {
    mouse.x = e.clientX;
    mouse.y = e.clientY;
  }

  initHandlers();
  initNodes();
  redrawScene();

})();```
<pre class="snippet-code-css lang-css prettyprint-override"><code>html,
body {
  margin: 0;
  background-color: #25003a;
  overflow: hidden;
}

canvas {
  position: relative;
  top: 0;
  bottom: 0;
  width: 100%;
  height: 100%;
  background-color: #25003a;
  overflow: hidden;
}

#wrap {
  position: absolute;
  top: 0;
  left: 0;
  height: 100vh;
  width: 100vw;
  line-height: 100vh;
}

#wrap p {
  text-align: center;
  border: 1px solid;
}

#wrap p a {
  color: white;
  font-size: 70px;
  text-decoration: none;
}

#wrap p a:hover {
  text-decoration: underline;
}</code>```

<canvas></canvas>

this is a link

```

Body:
Supposing that you put the content of your document in a div #wrap with a position absolute over the canvas, in order to interact with the particles on canvas you may use the mouse position over the #wrap. In your example I'm using wrap.addEventListener('mousemove', mousemoveHandler, false); instead of canvas.addEventListener('mousemove', mousemoveHandler, false);

(function() {

  var canvas, ctx, circ, nodes, mouse, SENSITIVITY, SIBLINGS_LIMIT, DENSITY, NODES_QTY, ANCHOR_LENGTH, MOUSE_RADIUS;

  // how close next node must be to activate connection (in px)
  // shorter distance == better connection (line width)
  SENSITIVITY = 100;
  // note that siblings limit is not 'accurate' as the node can actually have more connections than this value that's because the node accepts sibling nodes with no regard to their current connections this is acceptable because potential fix would not result in significant visual difference
  // more siblings == bigger node
  SIBLINGS_LIMIT = 10;
  // default node margin
  DENSITY = 50;
  // total number of nodes used (incremented after creation)
  NODES_QTY = 0;
  // avoid nodes spreading
  ANCHOR_LENGTH = 20;
  // highlight radius
  MOUSE_RADIUS = 200;

  circ = 2 * Math.PI;
  nodes = [];

  canvas = document.querySelector('canvas');
  resizeWindow();
  mouse = {
    x: canvas.width / 2,
    y: canvas.height / 2
  };
  ctx = canvas.getContext('2d');
  if (!ctx) {
    alert("Ooops! Your browser does not support canvas :'(");
  }

  function Node(x, y) {
    this.anchorX = x;
    this.anchorY = y;
    this.x = Math.random() * (x - (x - ANCHOR_LENGTH)) + (x - ANCHOR_LENGTH);
    this.y = Math.random() * (y - (y - ANCHOR_LENGTH)) + (y - ANCHOR_LENGTH);
    this.vx = Math.random() * 2 - 1;
    this.vy = Math.random() * 2 - 1;
    this.energy = Math.random() * 100;
    this.radius = Math.random();
    this.siblings = [];
    this.brightness = 0;
  }

  Node.prototype.drawNode = function() {
    var color = "rgba(255, 0, 0, " + this.brightness + ")";
    ctx.beginPath();
    ctx.arc(this.x, this.y, 2 * this.radius + 2 * this.siblings.length / SIBLINGS_LIMIT, 0, circ);
    ctx.fillStyle = color;
    ctx.fill();
  };

  Node.prototype.drawConnections = function() {
    for (var i = 0; i < this.siblings.length; i++) {
      var color = "rgba(255, 0, 0, " + this.brightness + ")";
      ctx.beginPath();
      ctx.moveTo(this.x, this.y);
      ctx.lineTo(this.siblings[i].x, this.siblings[i].y);
      ctx.lineWidth = 1 - calcDistance(this, this.siblings[i]) / SENSITIVITY;
      ctx.strokeStyle = color;
      ctx.stroke();
    }
  };

  Node.prototype.moveNode = function() {
    this.energy -= 2;
    if (this.energy < 1) {
      this.energy = Math.random() * 100;
      if (this.x - this.anchorX < -ANCHOR_LENGTH) {
        this.vx = Math.random() * 2;
      } else if (this.x - this.anchorX > ANCHOR_LENGTH) {
        this.vx = Math.random() * -2;
      } else {
        this.vx = Math.random() * 4 - 2;
      }
      if (this.y - this.anchorY < -ANCHOR_LENGTH) {
        this.vy = Math.random() * 2;
      } else if (this.y - this.anchorY > ANCHOR_LENGTH) {
        this.vy = Math.random() * -2;
      } else {
        this.vy = Math.random() * 4 - 2;
      }
    }
    this.x += this.vx * this.energy / 100;
    this.y += this.vy * this.energy / 100;
  };

  function initNodes() {
    ctx.clearRect(0, 0, canvas.width, canvas.height);
    nodes = [];
    for (var i = DENSITY; i < canvas.width; i += DENSITY) {
      for (var j = DENSITY; j < canvas.height; j += DENSITY) {
        nodes.push(new Node(i, j));
        NODES_QTY++;
      }
    }
  }

  function calcDistance(node1, node2) {
    return Math.sqrt(Math.pow(node1.x - node2.x, 2) + (Math.pow(node1.y - node2.y, 2)));
  }

  function findSiblings() {
    var node1, node2, distance;
    for (var i = 0; i < NODES_QTY; i++) {
      node1 = nodes[i];
      node1.siblings = [];
      for (var j = 0; j < NODES_QTY; j++) {
        node2 = nodes[j];
        if (node1 !== node2) {
          distance = calcDistance(node1, node2);
          if (distance < SENSITIVITY) {
            if (node1.siblings.length < SIBLINGS_LIMIT) {
              node1.siblings.push(node2);
            } else {
              var node_sibling_distance = 0;
              var max_distance = 0;
              var s;
              for (var k = 0; k < SIBLINGS_LIMIT; k++) {
                node_sibling_distance = calcDistance(node1, node1.siblings[k]);
                if (node_sibling_distance > max_distance) {
                  max_distance = node_sibling_distance;
                  s = k;
                }
              }
              if (distance < max_distance) {
                node1.siblings.splice(s, 1);
                node1.siblings.push(node2);
              }
            }
          }
        }
      }
    }
  }

  function redrawScene() {
    resizeWindow();
    ctx.clearRect(0, 0, canvas.width, canvas.height);
    findSiblings();
    var i, node, distance;
    for (i = 0; i < NODES_QTY; i++) {
      node = nodes[i];
      distance = calcDistance({
        x: mouse.x,
        y: mouse.y
      }, node);
      if (distance < MOUSE_RADIUS) {
        node.brightness = 1 - distance / MOUSE_RADIUS;
      } else {
        node.brightness = 0;
      }
    }
    for (i = 0; i < NODES_QTY; i++) {
      node = nodes[i];
      if (node.brightness) {
        node.drawNode();
        node.drawConnections();
      }
      node.moveNode();
    }
    requestAnimationFrame(redrawScene);
  }

  function initHandlers() {
    document.addEventListener('resize', resizeWindow, false);
    ///////////////////////////////////
    wrap.addEventListener('mousemove', mousemoveHandler, false);
    ///////////////////////////////////
  }

  function resizeWindow() {
    canvas.width = window.innerWidth;
    canvas.height = window.innerHeight;
  }

  function mousemoveHandler(e) {
    mouse.x = e.clientX;
    mouse.y = e.clientY;
  }

  initHandlers();
  initNodes();
  redrawScene();

})();

html,
body {
  margin: 0;
  background-color: #25003a;
  overflow: hidden;
}

canvas {
  position: relative;
  top: 0;
  bottom: 0;
  width: 100%;
  height: 100%;
  background-color: #25003a;
  overflow: hidden;
}

#wrap {
  position: absolute;
  top: 0;
  left: 0;
  height: 100vh;
  width: 100vw;
  line-height: 100vh;
}

#wrap p {
  text-align: center;
  border: 1px solid;
}

#wrap p a {
  color: white;
  font-size: 70px;
  text-decoration: none;
}

#wrap p a:hover {
  text-decoration: underline;
}

<canvas></canvas>
<div id="wrap">
<p>
<a href = "https://stackoverflow.com/">this is a link</a></p>
</div>


答:
You can concatenate the strings simply using + while asking for user input in the second line. Currently you are passing it three arguments separated by a comma.

```<code>firstname=input("What is your name: ")
favesub = input("Hello what is your favourite subject " + firstname + "?")
print ("I love ", favesub," aswell")

# What is your name: Donald
# Hello what is your favourite subject Donald?Politics
# I love  Politics  aswell
</code>```

Body:
You can concatenate the strings simply using + while asking for user input in the second line. Currently you are passing it three arguments separated by a comma.

firstname=input("What is your name: ")
favesub = input("Hello what is your favourite subject " + firstname + "?")
print ("I love ", favesub," aswell")

# What is your name: Donald
# Hello what is your favourite subject Donald?Politics
# I love  Politics  aswell


问:
What is the difference between Child_process and Worker Threads?
I am trying to understand Threading in NodeJS and how it works.

Currently what i understand:

Cluster: -

Built on top of Child_process, but with TCP distributed between clusters.

Best for distributing/balancing incoming http requests, while bad for cpu intensive tasks.

Works by taking advantage of available cores in cpu, by cloning nodeJS webserver instances on other cores.

Child_process:

Make use also of different cores available, but its bad since it costs huge amount of resources to fork a child process since it creates virtual memory.

Forked processes could communicate with the master thread through events and vice versa, but there is no communication between forked processes.

Worker threads:

Same as child process, but forked processes can communicate with each other using bufferArray

1) Why worker threads is better than child process and when we should use each of them?

2) What would happen if we have 4 cores and clustered/forked nodeJS webserver 4 times(1 process for each core), then we used worker threads (There is no available cores) ?

答:
You mentioned point under worker-threads that they are same in nature to child-process. But in reality they are not.

Process has its own memory space on other hand, threads use the shared memory space.

Thread is part of process. Process can start multiple threads. Which means that multiple threads started under process share the memory space allocated for that process.

I guess above point answers your 1st question why thread model is preferred over the process.

2nd point: Lets say processor can handle load of 4 threads at a time. But we have 16 threads. Then all of them will start sharing the CPU time.

Considering 4 core CPU, 4 processes with limited threads can utilize it in better way but when thread count is high, then all threads will start sharing the CPU time. (When I say all threads will start sharing CPU time I'm not considering the priority and niceness of the process, and not even considering the other processes running on the same machine.)

My Quick search about time-slicing and CPU load sharing:

https://en.wikipedia.org/wiki/Time-sharing

https://www.tutorialspoint.com/operating_system/os_process_scheduling_qa2.htm

This article even answers how switching between processes can slow down the overall performance.

Worker threads are are similar in nature to threads in any other programming language.

You can have a look at this thread to understand in overall about
difference between thread and process:
What is the difference between a process and a thread?


答:
Try this,

favesub = input("Hello what is your favourite subject"+firstname+"?")


问:
How can I specify an icon with a RELATIVE path for a Linux desktop entry file?
For one of my Linux applications, I have the application binary, a launcher.sh script (for the LD_LIBRARY_PATH) and a .desktop file, all in the same folder.

I'd like to use a relative path rather than an absolute path for the icon.

I've tried:

```<code>Icon=app.svg
Icon=./app.svg
Icon=$PWD/app.svg
Icon=$(dirname %k)/app.svg
</code>```

but none of these work (only Icon=/path/to/app.svg). If it's not possible to specify a relative path and I must use a workaround, I was thinking I could regenerate the icon path in the .desktop file every time the launcher.sh script is run.

What would be the best way to do that? Using sed or some other replacement utility with a pseudo-regex like Icon=([valid path chars]+)\n perhaps?

答:
You can use echo $(echo ~) to use command output or echo $(echo $var) for variables

For example:

echo "Icon=$(echo ~)/Pictures/Icons/whatsapp-webapp.svg" > path/to/file.desktop
```

If you are interested in multi line echo command check out this link

Body:
For one of my Linux applications, I have the application binary, a launcher.sh script (for the LD_LIBRARY_PATH) and a .desktop file, all in the same folder.

I'd like to use a relative path rather than an absolute path for the icon.

I've tried:

Icon=app.svg
Icon=./app.svg
Icon=$PWD/app.svg
Icon=$(dirname %k)/app.svg

but none of these work (only Icon=/path/to/app.svg). If it's not possible to specify a relative path and I must use a workaround, I was thinking I could regenerate the icon path in the .desktop file every time the launcher.sh script is run.

What would be the best way to do that? Using sed or some other replacement utility with a pseudo-regex like Icon=([valid path chars]+)\n perhaps?

Body:
You can use echo $(echo ~) to use command output or echo $(echo $var) for variables

For example:

echo "Icon=$(echo ~)/Pictures/Icons/whatsapp-webapp.svg" > path/to/file.desktop

If you are interested in multi line echo command check out this link


问:
Linux driver writing, file_operations incompatible pointer type errror
I am writing a simple linux driver which would accept messages piped thru CLI and I am getting an incompatible pointer type error.

My read function and file_operations struct:

```<code>ssize_t driver_read(struct file *filep, char *buffer, ssize_t len, loff_t *offset) {
    printk(KERN_INFO "Write: %s\n", message);
    return 0;
}

struct file_operations fops = {
    write: driver_write,
    read: driver_read
};
</code>```

When I try to compile the code I get the following error:

```<code>error: initialization from incompatible pointer type [-Werror=incompatible-pointer-types]
 read: driver_read
</code>```

According to another post here, the return type of the read function should be ssize_t, which I have, but I am still getting this error.

答:
Try changing the prototype's parameter to this:

```<code>ssize_t len
</code>```

to this:

```<code>size_t len
</code>```

Source

Body:
I am writing a simple linux driver which would accept messages piped thru CLI and I am getting an incompatible pointer type error.

My read function and file_operations struct:

ssize_t driver_read(struct file *filep, char *buffer, ssize_t len, loff_t *offset) {
    printk(KERN_INFO "Write: %s\n", message);
    return 0;
}

struct file_operations fops = {
    write: driver_write,
    read: driver_read
};

When I try to compile the code I get the following error:

error: initialization from incompatible pointer type [-Werror=incompatible-pointer-types]
 read: driver_read

According to another post here, the return type of the read function should be ssize_t, which I have, but I am still getting this error.

Body:
Try changing the prototype's parameter to this:

ssize_t len

to this:

size_t len

Source


问:
How to get Discord.js bot to log variable for every user
I am creating a discord bot similar to Pokecord and would like to log 1 or more variables for every user. I am using Discord.js, JavaScript, and Node.js.
Is this possible?</p>

答:
This may or may not work, I don't have time or resources to test but its code salvaged from a previous project</p>

```<code>var money = new Map();
const mems = client.guilds.get("serverid");

mems.members.forEach(member => () {
     money.set(member.user.username, 1);
     console.log(money.get(member.user.username));
});

</code>```

Body:
This may or may not work, I don't have time or resources to test but its code salvaged from a previous project

var money = new Map();
const mems = client.guilds.get("serverid");

mems.members.forEach(member => () {
     money.set(member.user.username, 1);
     console.log(money.get(member.user.username));
});


问:
'<...> is not a valid NSFetchRequest.'
I am using a custom source expression

```<code>NSExpression(format: "FETCH(FUNCTION($manager, \"customFetchRequestForSourceEntityNamed:predicateString:\" , \"\(mapping.sourceEntityName!)\", \"TRUEPREDICATE\"), $manager.sourceContext, NO)")
</code>```

for mapping model.

The fetch is being executed normally within the custom method, but exception '<...> is not a valid NSFetchRequest.' is thrown somewhere later inside the NSMigrationManager.migrateStore() method.

Any clues?

答:
The expected result type of this method is NSFetchRequest, not what the fetch returns.

The signature would be -

extension NSMigrationManager {

    @objc func customFetchRequest(forSourceEntityNamed entityName: String, predicateString: String) -> NSFetchRequest<NSFetchRequestResult> {
```

Title: '<...> is not a valid NSFetchRequest.'

Body:
I am using a custom source expression

NSExpression(format: "FETCH(FUNCTION($manager, \"customFetchRequestForSourceEntityNamed:predicateString:\" , \"\(mapping.sourceEntityName!)\", \"TRUEPREDICATE\"), $manager.sourceContext, NO)")

for mapping model.

The fetch is being executed normally within the custom method, but exception '<...> is not a valid NSFetchRequest.' is thrown somewhere later inside the NSMigrationManager.migrateStore() method.

Any clues?


问:
How to select the first element of a column of type array column using knex.select()?
We are able to select the first element of a column of type array in Postgres SQL database. But I'm not able to query the same using knex.

I have tried this.

```<code>database('items')
    .select({icon: 'images[0]})
    .then(data => {
    res.send(data)
}
</code>```

Expecting the first element of images column of items table.

答:
Try using the first() function. It returns the first row in your table (in whatever order the table is sorted).  The .select('images') will limit the columns returned to just images.

```<code>knex
  .select('images')
  .table('items')
  .first()
  .then((data) => {
    // first row of 'images' is an array.
    // return only the first item in array.
    res.send(data[0]);
})
</code>```

Body:
We are able to select the first element of a column of type array in Postgres SQL database. But I'm not able to query the same using knex.

I have tried this.

database('items')
    .select({icon: 'images[0]})
    .then(data => {
    res.send(data)
}

Expecting the first element of images column of items table.

Body:
Try using the first() function. It returns the first row in your table (in whatever order the table is sorted).  The .select('images') will limit the columns returned to just images.

knex
  .select('images')
  .table('items')
  .first()
  .then((data) => {
    // first row of 'images' is an array.
    // return only the first item in array.
    res.send(data[0]);
})