问:
custom marker icon with react-leaflet
I tried everything I found on the web, Stackoverflow and Github, and I still can't make it.

I want to make a custom marker with a custom icon, but with my code below I always got an error : 'TypeError: options.icon.createIcon is not a function'

Here is my code (no error on the paths to folders, everything is in src/js or src/img)

Icon.js

```<code>import L from 'leaflet';

const iconPerson = L.Icon.extend({
  options: {
    iconUrl: require('../img/marker-pin-person.svg'),
    iconRetinaUrl: require('../img/marker-pin-person.svg'),
    iconAnchor: null,
    popupAnchor: null,
    shadowUrl: null,
    shadowSize: null,
    shadowAnchor: null,
    iconSize: new L.Point(60, 75),
    className: 'leaflet-div-icon'
  }
});

export { iconPerson };
</code>```

MarkerPinPerson

```<code>import React from 'react';
import { Marker } from 'react-leaflet';
import {  iconPerson  } from './Icons';

export default class MarkerPinPerson extends React.Component {

  render() {

    return (
      <Marker
        position={this.props.markerPosition}
        icon={ iconPerson }
        >
      </Marker>
      );
  }
}
</code>```

Really looking for your help !

答:
I finally found the correct code for the Icon.js file :

```<code>import L from 'leaflet';

const iconPerson = new L.Icon({
    iconUrl: require('../img/marker-pin-person.svg'),
    iconRetinaUrl: require('../img/marker-pin-person.svg'),
    iconAnchor: null,
    popupAnchor: null,
    shadowUrl: null,
    shadowSize: null,
    shadowAnchor: null,
    iconSize: new L.Point(60, 75),
    className: 'leaflet-div-icon'
});

export { iconPerson };
</code>```

Title: custom marker icon with react-leaflet

Body:
I tried everything I found on the web, Stackoverflow and Github, and I still can't make it.

I want to make a custom marker with a custom icon, but with my code below I always got an error : 'TypeError: options.icon.createIcon is not a function'

Here is my code (no error on the paths to folders, everything is in src/js or src/img)

Icon.js

import L from 'leaflet';

const iconPerson = L.Icon.extend({
  options: {
    iconUrl: require('../img/marker-pin-person.svg'),
    iconRetinaUrl: require('../img/marker-pin-person.svg'),
    iconAnchor: null,
    popupAnchor: null,
    shadowUrl: null,
    shadowSize: null,
    shadowAnchor: null,
    iconSize: new L.Point(60, 75),
    className: 'leaflet-div-icon'
  }
});

export { iconPerson };

MarkerPinPerson

import React from 'react';
import { Marker } from 'react-leaflet';
import {  iconPerson  } from './Icons';

export default class MarkerPinPerson extends React.Component {

  render() {

    return (
      <Marker
        position={this.props.markerPosition}
        icon={ iconPerson }
        >
      </Marker>
      );
  }
}

Really looking for your help !

Body:
I finally found the correct code for the Icon.js file :

import L from 'leaflet';

const iconPerson = new L.Icon({
    iconUrl: require('../img/marker-pin-person.svg'),
    iconRetinaUrl: require('../img/marker-pin-person.svg'),
    iconAnchor: null,
    popupAnchor: null,
    shadowUrl: null,
    shadowSize: null,
    shadowAnchor: null,
    iconSize: new L.Point(60, 75),
    className: 'leaflet-div-icon'
});

export { iconPerson };


来源: stackexchange

问:
Class 'Painting' not found in web.php Laravel 5
Hi all I'm a newbie for Laravel when I try to insert data to the table paintings which worked fine up-to this point now the browser throwing (1/1) FatalErrorException Class 'Painting' not found in web.php (line 15)
Hoping kind help from you . Thanks!

Here is web.php

```<code>Route::get('/', function () {
    $painting = new Painting; //line 15
    $painting->title = 'Do No Wronge';
    $painting->artist = 'D. DoRight';
    $painting->year = 2017;
    $painting->save();
    return view('welcome');
});
</code>```

Here is Painting.php in app folder

```<code><?php

namespace App;

class Painting extends Eloquent
{

}
?>
</code>```

Even the FatalErrorException in routes.php line 22: Class 'Painting' not found doesn't provided the correct answer for the version i'm using

答:
Modified files [Working solution]

Here is web.php

```<code><?php
use App\Painting;

Route::get('/', function () {
  $painting = new Painting; //line 15
  $painting->title = 'Do No Wronge';
  $painting->artist = 'D. DoRight';
  $painting->year = 2017;
  $painting->save();
  return view('welcome');
});
</code>```

Here is Painting.php in app folder

```<code><?php
namespace App;

use Illuminate\Database\Eloquent\Model;

class Painting extends Model
{

}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Hi all I'm a newbie for Laravel when I try to insert data to the table paintings which worked fine up-to this point now the browser throwing (1/1) FatalErrorException Class 'Painting' not found in web.php (line 15)
Hoping kind help from you . Thanks!

Here is web.php

Route::get('/', function () {
    $painting = new Painting; //line 15
    $painting->title = 'Do No Wronge';
    $painting->artist = 'D. DoRight';
    $painting->year = 2017;
    $painting->save();
    return view('welcome');
});

Here is Painting.php in app folder

<?php

namespace App;

class Painting extends Eloquent
{

}
?>

Even the FatalErrorException in routes.php line 22: Class 'Painting' not found doesn't provided the correct answer for the version i'm using

Body:
Modified files [Working solution]

Here is web.php

<?php
use App\Painting;

Route::get('/', function () {
  $painting = new Painting; //line 15
  $painting->title = 'Do No Wronge';
  $painting->artist = 'D. DoRight';
  $painting->year = 2017;
  $painting->save();
  return view('welcome');
});

Here is Painting.php in app folder

<?php
namespace App;

use Illuminate\Database\Eloquent\Model;

class Painting extends Model
{

}


问:
BitmapFactory works perfectly on .png image but returns null when i load jpeg image from url
BitmapFactory works perfectly on .png image but  returns null when I load jpeg image from url.

```<code>BitmapFactory.decodeStream( (InputStream) new URL(URL).getContent(), null, options);
</code>```

I use this code but when I provide a jpeg image url it returns null.

What should I do?

答: A URL uniquely identifies a resource on the web. A good way to test a url is with a browser. I have no idea what new URL(URL) is supposed to do. URL takes a string argument but other constructors are available see https://docs.oracle.com/javase/7/docs/api/java/net/URL.html If you pass a string to a constructor you probably want to assign a value to the string or just use a literal string example new URL("google.com") at least you will get something other than null pointer. I have no way of knowing what url your image is because the web is a big place.   </p>

Body:
BitmapFactory works perfectly on .png image but  returns null when I load jpeg image from url.

BitmapFactory.decodeStream( (InputStream) new URL(URL).getContent(), null, options);

I use this code but when I provide a jpeg image url it returns null.

What should I do?


问:
string: replace "(" with "\("
i have to send a string to the bash, which contains an escape sequence. For example, i have to replace special characters like "(" with "(", because the bash else throws errors. I trtied like

```<code>public class escape {
    public static void main(String args[]) {
        System.out.println("\\");
        String s = "(foo)";
        System.out.println(s);
        s = s.replaceAll("(", "\\(");
        System.out.println(s);
    }
}
</code>```

with no luck. Please help!!

thanks

ContentLicense: CC BY-SA 2.5

Title: string: replace "(" with "\("

Body:
i have to send a string to the bash, which contains an escape sequence. For example, i have to replace special characters like "(" with "(", because the bash else throws errors. I trtied like

public class escape {
    public static void main(String args[]) {
        System.out.println("\\");
        String s = "(foo)";
        System.out.println(s);
        s = s.replaceAll("(", "\\(");
        System.out.println(s);
    }
}

with no luck. Please help!!

thanks

Body: s = s.replaceAll("\\(", "\\\\(");


问:
JBoss EAP 6.1 Error : This runtime type requires a JDK. The current default VM for this server's execution environment is not recognized as a JDK
You can check this warning here when I'm adding the server I'm getting like this. Please help me out. Thanks</p>

答:
Go to

window -> preferances -> java -> installed jres

Click "Add" and add the JDK path.

ContentLicense: CC BY-SA 4.0


问:
How to get ArrayList of POJO's from Amazon Lambda (getting only LinkedTreeMap)
I try to call my AWS Lambda function (serverless backend) with my Android mobile app client. The AWS lambda function returns an ArrayList of POJO objects (as JSON).

The problem is that the android client AWS Lambda(JSON)DataBinder does not deserialize to my ArrayList of POJOs. I get an ArrayList of LinkedTreeMap (see code at onPostExecute() below).

At the android client side I'm using Android AWS SDK: com.amazonaws:aws-android-sdk-core:2.6

Here is some code:

```<code>public void readSurveyList(String strUuid, int intLanguageID) {

    // Create an instance of CognitoCachingCredentialsProvider
    // You have to configure at least an AWS identity pool to get access to your lambda function
    CognitoCachingCredentialsProvider credentialsProvider = new CognitoCachingCredentialsProvider(
            this.getApplicationContext(),
            IDENTITY_POOL_ID,
            Regions.EU_CENTRAL_1);

    LambdaInvokerFactory factory = LambdaInvokerFactory.builder()
            .context(this.getApplicationContext())
            .region(Regions.EU_CENTRAL_1)
            .credentialsProvider(credentialsProvider)
            .build();

    // Create the Lambda proxy object with default Json data binder.
    myInterface = factory.build(MyInterface.class);

    //create a request object (depends on your lambda function)
    SurveyListRequest surveyListRequest = new SurveyListRequest(strUuid, intLanguageID);

    // Lambda function in async task with definiton of
    //      request object (-> SurveyListRequest)
    //      response object (-> ArrayList<SurveyListItem>>)
    new AsyncTask<SurveyListRequest, Void, ArrayList<SurveyListItem>>() {
        @Override
        protected ArrayList<SurveyListItem> doInBackground(SurveyListRequest... params) {

            try {
                return myInterface.ReadSurveyList(params[0]);
            } catch (LambdaFunctionException lfe) {
                Log.e("TAG", String.format("echo method failed: error [%s], details [%s].", lfe.getMessage(), lfe.getDetails()));
                return null;
            }
        }

        @Override
        protected void onPostExecute(ArrayList<SurveyListItem> surveyList) {

            // PROBLEM: here i get a ArrayList of LinkedTreeMap

        }
    }.execute(surveyListRequest);
}
</code>```

Here is the code of my lambda function Interface:

```<code>public interface MyInterface {

    @LambdaFunction
    ArrayList<SurveyListItem> ReadSurveyList (SurveyListRequest surveyListRequest);
}
</code>```

I would expect to get a list of my POJO objects. I found a lot of discussions about Gson and ArrayList type and solutions based on TypeToken (e.g. Gson TypeToken with dynamic ArrayList item type). Maybe same problem ...

答:
I found a solution using a custom LambdaDataBinder. I have specified the type of my POJO-class "SurveyListItem" in deserialize function. The Gson uses the TypeToken definition and converts the JSON string correct to the list of POJOs (in my case "SurveyListItem" objects).

Here is the sourcecode of MyLambdaDataBinder:

```<code>public class MyLambdaDataBinder implements LambdaDataBinder {

    private final Gson gson;
    Type mType;

    //CUSTOMIZATION: pass typetoken via class constructor
    public MyLambdaDataBinder(Type type) {
        this.gson = new Gson();
        mType = type;
    }

    @Override
    public <T> T deserialize(byte[] content, Class<T> clazz) {
        if (content == null) {
            return null;
        }
        Reader reader = new BufferedReader(new InputStreamReader(new ByteArrayInputStream(content)));

        //CUSTOMIZATION: Original line of code: return gson.fromJson (reader, clazz);
        return gson.fromJson(reader, mType);
    }

    @Override
    public byte[] serialize(Object object) {
        return gson.toJson(object).getBytes(StringUtils.UTF8);
    }
}
</code>```

Here is how to use the custom MyLambdaDataBinder. Use your POJO instead of "SurveyListItem":

```<code>myInterface = factory.build(LambdaInterface.class, new MyLambdaDataBinder(new TypeToken<ArrayList<SurveyListItem>>() {}.getType()));
</code>```

Body:
I try to call my AWS Lambda function (serverless backend) with my Android mobile app client. The AWS lambda function returns an ArrayList of POJO objects (as JSON).

The problem is that the android client AWS Lambda(JSON)DataBinder does not deserialize to my ArrayList of POJOs. I get an ArrayList of LinkedTreeMap (see code at onPostExecute() below).

At the android client side I'm using Android AWS SDK: com.amazonaws:aws-android-sdk-core:2.6

Here is some code:

public void readSurveyList(String strUuid, int intLanguageID) {

    // Create an instance of CognitoCachingCredentialsProvider
    // You have to configure at least an AWS identity pool to get access to your lambda function
    CognitoCachingCredentialsProvider credentialsProvider = new CognitoCachingCredentialsProvider(
            this.getApplicationContext(),
            IDENTITY_POOL_ID,
            Regions.EU_CENTRAL_1);

    LambdaInvokerFactory factory = LambdaInvokerFactory.builder()
            .context(this.getApplicationContext())
            .region(Regions.EU_CENTRAL_1)
            .credentialsProvider(credentialsProvider)
            .build();

    // Create the Lambda proxy object with default Json data binder.
    myInterface = factory.build(MyInterface.class);

    //create a request object (depends on your lambda function)
    SurveyListRequest surveyListRequest = new SurveyListRequest(strUuid, intLanguageID);

    // Lambda function in async task with definiton of
    //      request object (-> SurveyListRequest)
    //      response object (-> ArrayList<SurveyListItem>>)
    new AsyncTask<SurveyListRequest, Void, ArrayList<SurveyListItem>>() {
        @Override
        protected ArrayList<SurveyListItem> doInBackground(SurveyListRequest... params) {

            try {
                return myInterface.ReadSurveyList(params[0]);
            } catch (LambdaFunctionException lfe) {
                Log.e("TAG", String.format("echo method failed: error [%s], details [%s].", lfe.getMessage(), lfe.getDetails()));
                return null;
            }
        }

        @Override
        protected void onPostExecute(ArrayList<SurveyListItem> surveyList) {

            // PROBLEM: here i get a ArrayList of LinkedTreeMap

        }
    }.execute(surveyListRequest);
}

Here is the code of my lambda function Interface:

public interface MyInterface {

    @LambdaFunction
    ArrayList<SurveyListItem> ReadSurveyList (SurveyListRequest surveyListRequest);
}

I would expect to get a list of my POJO objects. I found a lot of discussions about Gson and ArrayList type and solutions based on TypeToken (e.g. Gson TypeToken with dynamic ArrayList item type). Maybe same problem ...

Body:
I found a solution using a custom LambdaDataBinder. I have specified the type of my POJO-class "SurveyListItem" in deserialize function. The Gson uses the TypeToken definition and converts the JSON string correct to the list of POJOs (in my case "SurveyListItem" objects).

Here is the sourcecode of MyLambdaDataBinder:

public class MyLambdaDataBinder implements LambdaDataBinder {

    private final Gson gson;
    Type mType;

    //CUSTOMIZATION: pass typetoken via class constructor
    public MyLambdaDataBinder(Type type) {
        this.gson = new Gson();
        mType = type;
    }

    @Override
    public <T> T deserialize(byte[] content, Class<T> clazz) {
        if (content == null) {
            return null;
        }
        Reader reader = new BufferedReader(new InputStreamReader(new ByteArrayInputStream(content)));

        //CUSTOMIZATION: Original line of code: return gson.fromJson (reader, clazz);
        return gson.fromJson(reader, mType);
    }

    @Override
    public byte[] serialize(Object object) {
        return gson.toJson(object).getBytes(StringUtils.UTF8);
    }
}

Here is how to use the custom MyLambdaDataBinder. Use your POJO instead of "SurveyListItem":

myInterface = factory.build(LambdaInterface.class, new MyLambdaDataBinder(new TypeToken<ArrayList<SurveyListItem>>() {}.getType()));


问:
How to make Wordpress custom field input text translatable with qTranslate X?
I have some wordpress custom fields (I'm not using ACF or any other plugin for this) and need to translate them using qTranslate X in wp-admin.

The fields that I created with wp_editor are working, but I don't know how to make it work with default <input type="text"> for other custom fields that I have.

Below, a piece of code that I'm using to set variable and show my field:

```<code>    $services = isset( $values['services'] ) ? esc_attr( $values['services'][0] ) : '';
    wp_nonce_field( 'my_meta_box_nonce', 'meta_box_nonce' );
?>
<table>
    <tr>
        <td>
            <input type="text" name="services_title" value="<?php echo !empty($services_title) ? $services_title : ''; ?>" style="width: 100%" />
        </td>
    </tr>
</table>
</code>```

then, I'm saving it with:

```<code>add_action( 'save_post', 'hotelSaveData' );
function hotelSaveData( $post_id )
{
    // Bail if we're doing an auto save
    if( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) return;

    if (isset($_POST['services_title']))
        update_post_meta($post_id, 'services_title', wp_kses($_POST['services_title'], true));

}
</code>```

Does anyone knows how to make it work, without using ACF or any other plugin ? (My fallback solution is to create another custom fields just to save other language data, but solve it with qTranslate would be great)

thanks =D

答:
Just use the inline syntax when adding the value on your input field
e.g.

```<code>you can use this on input field value
[:en]Text Here for English Translation
[:de]Text Here for German Translation
[:es]Text Here for Spanish Translation[:]

other inline syntax though I bet the input validator won't accept this tags
<!--:en-->English Text<!--:-->
<!--:de-->Deutsch<!--:-->
</code>```

You can read more info from here https://qtranslatexteam.wordpress.com/faq/#CustomFields

Body:
I have some wordpress custom fields (I'm not using ACF or any other plugin for this) and need to translate them using qTranslate X in wp-admin.

The fields that I created with wp_editor are working, but I don't know how to make it work with default <input type="text"> for other custom fields that I have.

Below, a piece of code that I'm using to set variable and show my field:

    $services = isset( $values['services'] ) ? esc_attr( $values['services'][0] ) : '';
    wp_nonce_field( 'my_meta_box_nonce', 'meta_box_nonce' );
?>

            <input type="text" name="services_title" value="<?php echo !empty($services_title) ? $services_title : ''; ?>" style="width: 100%" />

then, I'm saving it with:

add_action( 'save_post', 'hotelSaveData' );
function hotelSaveData( $post_id )
{
    // Bail if we're doing an auto save
    if( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) return;

    if (isset($_POST['services_title']))
        update_post_meta($post_id, 'services_title', wp_kses($_POST['services_title'], true));

}

Does anyone knows how to make it work, without using ACF or any other plugin ? (My fallback solution is to create another custom fields just to save other language data, but solve it with qTranslate would be great)

thanks =D

Body:
Just use the inline syntax when adding the value on your input field
e.g.

you can use this on input field value
[:en]Text Here for English Translation
[:de]Text Here for German Translation
[:es]Text Here for Spanish Translation[:]

other inline syntax though I bet the input validator won't accept this tags
<!--:en-->English Text<!--:-->
<!--:de-->Deutsch<!--:-->

You can read more info from here https://qtranslatexteam.wordpress.com/faq/#CustomFields


问:
Run docker swarm mode on windows 10 using multiple hosts
I'm running Windows 10 with the latest updates installed. I'm trying to set up a swarm using multiple physical hosts running docker Linux containers on windows host.
When I'm running

```docker swarm init --advertise-addr 10.154.26.150 --listen-addr 10.154.26.150:2377```

Where

```10.154.26.150```

stands for physical address of my current machine (future swarm manager)
I obviously receive

```Error response from daemon:
manager stopped:
failed to listen on remote API address: listen tcp 10.154.26.150:2377
bind: cannot assign requested address```

because docker for Windows running Linux containers uses hyper-v vm and doesn't know anything about address I'm trying to specify.
So here is a question if there is any small possibility to run swarm mode in this situation so that my other hosts will be able to join new swarm over physical network.

答:
If you're using "Docker for Windows", which runs a Moby VM in Hyper-V and simulates localhost, then it's easy for a single node Swarm setup. It's not yet designed to easily join outside machines.

If you want to have a 3-node swarm to spread out your testing, where they all have easy direct access to each other, then I recommend using docker-machine to create 3 more VM's in Hyper-V running boot2docker, like so:

```<code>docker-machine create --driver hyperv --hyperv-virtual-switch "Primary Virtual Switch" node1
docker-machine create --driver hyperv --hyperv-virtual-switch "Primary Virtual Switch" node2
docker-machine create --driver hyperv --hyperv-virtual-switch "Primary Virtual Switch" node3
</code>```

NOTE: For this to work, 1. Be sure you're in PowerShell admin mode so docker-machine can control Hyper-V and 2. You'll need to create an "external" Hyper-V Switch and use its name in creating the VM's.

Details on the switch setup, and other options like changing CPU and memory are in the docker-machine docs.

Then you can change your docker CLI to control each one directly with & docker-machine env nodeX | Invoke-Expression and ssh into them with docker-machine ssh nodeX etc.

I use this setup and it works great!

Body:
I'm running Windows 10 with the latest updates installed. I'm trying to set up a swarm using multiple physical hosts running docker Linux containers on windows host.
When I'm running

docker swarm init --advertise-addr 10.154.26.150 --listen-addr 10.154.26.150:2377

Where

10.154.26.150

stands for physical address of my current machine (future swarm manager)
I obviously receive

Error response from daemon:
manager stopped:
failed to listen on remote API address: listen tcp 10.154.26.150:2377
bind: cannot assign requested address

because docker for Windows running Linux containers uses hyper-v vm and doesn't know anything about address I'm trying to specify.
So here is a question if there is any small possibility to run swarm mode in this situation so that my other hosts will be able to join new swarm over physical network.

Body:
If you're using "Docker for Windows", which runs a Moby VM in Hyper-V and simulates localhost, then it's easy for a single node Swarm setup. It's not yet designed to easily join outside machines.

If you want to have a 3-node swarm to spread out your testing, where they all have easy direct access to each other, then I recommend using docker-machine to create 3 more VM's in Hyper-V running boot2docker, like so:

docker-machine create --driver hyperv --hyperv-virtual-switch "Primary Virtual Switch" node1
docker-machine create --driver hyperv --hyperv-virtual-switch "Primary Virtual Switch" node2
docker-machine create --driver hyperv --hyperv-virtual-switch "Primary Virtual Switch" node3

NOTE: For this to work, 1. Be sure you're in PowerShell admin mode so docker-machine can control Hyper-V and 2. You'll need to create an "external" Hyper-V Switch and use its name in creating the VM's.

Details on the switch setup, and other options like changing CPU and memory are in the docker-machine docs.

Then you can change your docker CLI to control each one directly with & docker-machine env nodeX | Invoke-Expression and ssh into them with docker-machine ssh nodeX etc.

I use this setup and it works great!


问:
Convert unirest to curl
I want to use jsonWhois api but it makes the server request using Unirest, which looks like it's no longer maintained and I would prefer to use curl anyway.

How can I convert this code to use Curl instead??

```<code>$response = Unirest\Request::get("https://jsonwhois.com/api/v1/whois",

   array(
    "Accept" => "application/json",
    "Authorization" => "Token token=<Api Key>"
   ),

   array(
       "domain" => "google.com"
   )

);

$data = $response->body; // Parsed body
</code>```

I've tried curl_setopt($ch, CURLOPT_URL, 'https://jsonwhois.com/api/v1/whois?token=123456&domain=google.com');, but it says HTTP Token: access denied.

答:
You can actually use Postman app for something like this. I use it all the time and it works great.

You can simply enter the request into it:

And then simply click on "Code" (top right corner) and go to "PHP" -> "cURL". It will show you the exact code that you have to write to make that request using cURL:

I have no idea what jsonwhois is but, if everything is set up correctly, it should work.

Title: Convert unirest to curl

Body:
I want to use jsonWhois api but it makes the server request using Unirest, which looks like it's no longer maintained and I would prefer to use curl anyway.

How can I convert this code to use Curl instead??

$response = Unirest\Request::get("https://jsonwhois.com/api/v1/whois",

   array(
    "Accept" => "application/json",
    "Authorization" => "Token token=<Api Key>"
   ),

   array(
       "domain" => "google.com"
   )

);

$data = $response->body; // Parsed body

I've tried curl_setopt($ch, CURLOPT_URL, 'https://jsonwhois.com/api/v1/whois?token=123456&domain=google.com');, but it says HTTP Token: access denied.


问:
iPhone Cocos2d game change to iPad game
I have spent 1000's of hours into one of my games and just started looking at iPad stuff. Yeah... didn't realize what the whole CGSize size = [[CCDirector sharedDirector] winSize]; thing was until now.

So I'm pretty much screwed right? There's no sense in changing literally 10,000 ccp coordinates?

Is there a way:

if iPad
add or subtract to the ccp to position to put everything in the center

I could add it to every scene.

答: I hope your app is using version 0.99.5. 0.99.5 is using by pixels or something.. So you wont b screwed. It will auto scale by ratio.. No worries..</p>

Title: iPhone Cocos2d game change to iPad game


问:
Error while trying to assign user to app
As the title indicates, I'm getting an error while trying to assign a user to an AAD application.
Here is the request and the error I'm getting

Obviously it's related to the version of the API but I can't get it to work even with changing the api-version parameter.

Update :
When I modify the request url to https://graph.microsoft.com/v1.0/..., I get the following error : Unsupported segment type. ODataQuery: users/{userid}/appRoleAssignments

Update 2 :
Even with beta version, this seems not to be working :

Update 3 :
Is this still available in beta version of MS Graph? otherwise is there any alternatives (other than powershell and graph api) to achieve what I want programatically
    https://graph.microsoft.com/beta/users/{userId}/appRoleAssignments/{appRoleId}

Still getting Unsupported segment type error

答:
Marc's answer is correct - with a couple of caveats:
 1. This is only available in /beta, and not recommended for production.
 2. There's a bug that is preventing this from working.

To do this in production, the only current option for you is to use Azure AD Graph API.  You'll see that our docs recommend the use of Microsoft Graph everywhere, but there are a few places where there are some gaps with Azure AD Graph.

More info on what's supported in Microsoft Graph vs Azure AD Graph look at this topic https://dev.office.com/blogs/microsoft-graph-or-azure-ad-graph

The API calls are the same as Marc has above, but with a different root URL and versioning scheme. So it looks something like this:

POST https://graph.windows.net/{tenantId}/users/{userId}/appRoleAssignments?api-version=1.6
{
  "id": "31952ade-a03c-414c-8340-2f11e9099106",
  "principalId":  "84b80893-8749-40a3-97b7-68513b600544",
  "principalType": "User",
  "resourceId":  "29c7ed43-a9a1-4b31-8a64-fc90c3ca4e73"
}

See either this older blog or the AAD Graph reference docs

Hope this helps,


问:
How to convert similarity matrix into dissimilarity matrix?
How to convert similarity matrix into dissimilarity matrix?
Example:

```<code>Point P1    P2   P3    P4
P1    1    0.8  0.65  0.55
P2    0.8   1    0.7   0.6
P3    0.65 0.7   1    0.9
P4    0.55 0.6   0.9    1
</code>```

P1 and P2 are in cluster1 and P3 and P4 are in cluster2

答:
If your maximum similarity is 1, you can simply use

dissim(x,y) = 1 - sim(x,y)

Using "maxsim - sim" works very often.

But did you know many clustering algorithms (e.g., HAC, GDBSCAN) can be implemented with a similarity function, too? It's just that the typical library only implement one version.

Body:
How to convert similarity matrix into dissimilarity matrix?
Example:

Point P1    P2   P3    P4
P1    1    0.8  0.65  0.55
P2    0.8   1    0.7   0.6
P3    0.65 0.7   1    0.9
P4    0.55 0.6   0.9    1

P1 and P2 are in cluster1 and P3 and P4 are in cluster2


问:
UIAlertView hidden behind View
I presented a view controller with the presentModalViewController:animated: method. Let's call this view myView. On myView, I have a button and when tapped, it is supposed to create a UIAlertView and show it.

However, when I tap this button, the alertView is created but doesn't appear on top of myView.  Instead, it is hidden behind myView.

Note: To verify that the alertView is hidden behind myView, I added a second button on myView and when it is tapped, the myView view controller dismisses itself (i.e. [self dismissModalViewControllerAnimated:YES]). When myView is dismissed, the alertView appears.

Any idea why the alertView is hidden behind myView?

答:
I was having this problem, also. It was intermittent, but I believe it related to displaying the alert on a background thread.

As of Xcode 9, Swift 4:

To test if function is running on main thread, use: Thread.current.isMainThread

```<code>print("On main thread: \(Thread.current.isMainThread)")
</code>```

To display alert, or perform any operation on main thread, use OperationQueue.main:

```<code>OperationQueue.main.addOperation {
    // code to perform on main thread
}
</code>```

Title: UIAlertView hidden behind View

Body:
I was having this problem, also. It was intermittent, but I believe it related to displaying the alert on a background thread.

As of Xcode 9, Swift 4:

To test if function is running on main thread, use: Thread.current.isMainThread

print("On main thread: \(Thread.current.isMainThread)")

To display alert, or perform any operation on main thread, use OperationQueue.main:

OperationQueue.main.addOperation {
    // code to perform on main thread
}


问:
Angular 5 with es5
Angular 4 supports below syntax

```<code>var HelloComponent = ng.core
 Component({
    selector: 'hello-cmp',
    template: 'Hello World!',
    viewProviders: [Service]
  .Class({
   constructor: [Service, function (service) {
   },`
  });
</code>```

In Angular 5 , Class is missing anyone can provide Angular 5 with ES5 syntax currently
i am not able to switch ES6 so please avoid that suggestion.
if switching to ES6 is the only way then i will stick to angular 4 as of now

答:
You need to use static properties annotations and parameters on your component class function something like this:

```<code>function Service() {}

function AppComponent(service) {
  console.log(service);
}

AppComponent.prototype.ngOnInit = function() {
  console.log('test ngOnInit');
};

AppComponent.annotations = [
  new Component({
    selector: 'my-app',
    template: '<h1>Example of Angular  5.0.5 in ES5</h1>',
    viewProviders: [Service]
  })
];

AppComponent.parameters = [ Service ];
</code>```

Plunker Example

Title: Angular 5 with es5

Body:
Angular 4 supports below syntax

var HelloComponent = ng.core
 Component({
    selector: 'hello-cmp',
    template: 'Hello World!',
    viewProviders: [Service]
  .Class({
   constructor: [Service, function (service) {
   },`
  });

In Angular 5 , Class is missing anyone can provide Angular 5 with ES5 syntax currently
i am not able to switch ES6 so please avoid that suggestion.
if switching to ES6 is the only way then i will stick to angular 4 as of now

Body:
You need to use static properties annotations and parameters on your component class function something like this:

function Service() {}

function AppComponent(service) {
  console.log(service);
}

AppComponent.prototype.ngOnInit = function() {
  console.log('test ngOnInit');
};

AppComponent.annotations = [
  new Component({
    selector: 'my-app',
    template: '<h1>Example of Angular  5.0.5 in ES5</h1>',
    viewProviders: [Service]
  })
];

AppComponent.parameters = [ Service ];

Plunker Example


问:
string comparison "=" != "+" , incorrect results
Task is to check whether string results true or false for following given condition:

If a letter a to z occurs it must have '+' before and after the particular letter
This works fine expect the case when '=' comes before or after the letter.
Why this condition is wrong for '=' ?
This code returns true for these strings
Thanks

function SimpleSymbols(str) {
    var temp=str.split("")
    if(temp.length==1 || temp.length==2 )
    return false;
    for(i=0;i<temp.length;i++){
        if(temp[i]>='a' && temp[i]<='z'){
            if(i===0 || i===(temp.length-1)||
            (temp[i-1]!=='+' && temp[i+1]!=='+')){
                return false;
            }
        }
    }
  return true;
}
   ```

答:
The condition (temp[i-1]!=='+' && temp[i+1]!=='+') is only true if both the character before and after the letter are not pluses. If one of them is a plus sign the condition is false.

You need to change the logical and to an or operator: (temp[i-1]!=='+' || temp[i+1]!=='+')

Background: De Morgan's Laws

The original condition is that a letter is surrounded by plus signs:

```<code>temp[i-1] === '+' && temp[i+1] === '+'
</code>```

In your if clause you test that this condition is not matched. So, the original condition becomes:

```<code>!(temp[i-1] === '+' && temp[i+1] === '+')
</code>```

To transform this into a condition using not-equals, you need to apply De Morgan's Laws which basically say that a logical and becomes an or and vice-versa if you factor in a negation. This makes the resulting condition:

```<code>temp[i-1] !== '+' || temp[i+1] !== '+'
</code>```

Body:
The condition (temp[i-1]!=='+' && temp[i+1]!=='+') is only true if both the character before and after the letter are not pluses. If one of them is a plus sign the condition is false.

You need to change the logical and to an or operator: (temp[i-1]!=='+' || temp[i+1]!=='+')

Background: De Morgan's Laws

The original condition is that a letter is surrounded by plus signs:

temp[i-1] === '+' && temp[i+1] === '+'

In your if clause you test that this condition is not matched. So, the original condition becomes:

!(temp[i-1] === '+' && temp[i+1] === '+')

To transform this into a condition using not-equals, you need to apply De Morgan's Laws which basically say that a logical and becomes an or and vice-versa if you factor in a negation. This makes the resulting condition:

temp[i-1] !== '+' || temp[i+1] !== '+'


问:
Custom ListView one item for a specific screen height
I have coded an app to learn about Custom List View. While the app has no errors, I have one issue. I have shown it in the images as follows.
IMAGE 1
IMAGE 2

The problem is I have to scroll a long way before i can find the next list item.The list items do not appear one below the other.How to resolve this issue?
Here is my code:

```<code>package com.example.hp.customlistview;

import android.support.constraint.ConstraintLayout;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {

    int IMAGES[]={R.drawable.adsense, R.drawable.allo, R.drawable.chrome, R.drawable.firebase, R.drawable.youtube};
    String[] NAMES={"AdSense","Allo","Chrome","Firebase","YouTube"};
    String [] DESCRIPTIONS={"Money through ads","Video calling","Web Browser","Cloud Database","Video Streaming"};
    private ListView listView;
    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        listView=(ListView)findViewById(R.id.listView);
        CustomAdapter customAdapter=new CustomAdapter();
        listView.setAdapter(customAdapter);
    }

    class CustomAdapter extends BaseAdapter{

        @Override
        public int getCount() {
            Log.d("Length of Array ","The length is "+IMAGES.length);
            return IMAGES.length;
        }

        @Override
        public Object getItem(int i) {
            return null;
        }

        @Override
        public long getItemId(int i) {
            return i;
        }

        @Override
        public View getView(int i, View view, ViewGroup viewGroup) {
            LayoutInflater layoutInflater=(LayoutInflater)getApplicationContext().getSystemService(getApplicationContext().LAYOUT_INFLATER_SERVICE);
            view=layoutInflater.inflate(R.layout.customlayout, null);
            Log.d("Image ID","The id is "+R.id.imageView);
            ImageView imageView=(ImageView)view.findViewById(R.id.imageView);
            TextView textView_name=(TextView)view.findViewById(R.id.textView);
            TextView textView_desc=(TextView)view.findViewById(R.id.textView2);
            if(imageView==null)
                Log.d("NULL?","YES IT IS NULL");
            else
                Log.d("NULL?","NO IT IS NOT NULL");
            imageView.setImageResource(IMAGES[i]);
            textView_name.setText(NAMES[i]);
            textView_desc.setText(DESCRIPTIONS[i]);
            Log.d("Hello","Hello there "+textView_name.getText().toString());
            return view;
        }
    }
}
</code>```

customlayout.xml

```<code><?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="120dp">

    <ImageView
        android:id="@+id/imageView"
        android:layout_width="86dp"
        android:layout_height="91dp"
        android:layout_marginBottom="8dp"
        android:layout_marginStart="32dp"
        android:layout_marginTop="16dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.0"
        app:srcCompat="@mipmap/ic_launcher" />

    <TextView
        android:id="@+id/textView"
        android:layout_width="161dp"
        android:layout_height="39dp"
        android:layout_marginBottom="8dp"
        android:layout_marginStart="28dp"
        android:layout_marginTop="24dp"
        app:layout_constraintBottom_toTopOf="@+id/textView2"
        app:layout_constraintStart_toEndOf="@+id/imageView"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.0" />

    <TextView
        android:id="@+id/textView2"
        android:layout_width="237dp"
        android:layout_height="57dp"
        android:layout_marginBottom="380dp"
        android:layout_marginEnd="8dp"
        android:layout_marginRight="16dp"
        android:layout_marginStart="44dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="1.0"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintStart_toEndOf="@+id/imageView" />

    <CheckBox
        android:id="@+id/checkBox"
        android:layout_width="39dp"
        android:layout_height="39dp"
        android:layout_marginRight="16dp"
        android:layout_marginTop="16dp"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintStart_toEndOf="@+id/textView"
        app:layout_constraintTop_toTopOf="parent" />
</android.support.constraint.ConstraintLayout>
</code>```

activity_main.xml

```<code><?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.example.hp.customlistview.MainActivity">

    <ListView
        android:id="@+id/listView"
        android:layout_width="386dp"
        android:layout_height="409dp"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <Button
        android:id="@+id/button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="24dp"
        android:text="Ok"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/listView" />
</android.support.constraint.ConstraintLayout>
</code>```

To resolve this, i tried the following

1)android:layout_height="match_parent" to a specific height of 120 dp.
(It is in customlayout.xml)
But it did not work

2)Used some other layout, such as Absolute and Relative Layout, but image fills up the list content much beyond expected size

EDIT:
I have the list items displayed in a compact manner, as follows,
after suggestions by Ben P. in the comments below.
IMAGE 3
But the description is not appearing,although clearly i have set it programatically in MainActivity.java
I observed that setting android:layout_height to some custom value makes the description text view disappear in the preview.

If someone is downvoting,please give the reason for doing so. This will help me improve the quality of my questions.

答:
Ok, I figured it out. Posting it for anyone who may have similar doubts in future.
Set layout height as 120dp or some finite value even before dragging and dropping items.
Now start drag and drop operation on this reduced layout.
Pretty simple i guess. This helped me resolve it.
Here it is:)

Image 5

Body:
I have coded an app to learn about Custom List View. While the app has no errors, I have one issue. I have shown it in the images as follows.
IMAGE 1
IMAGE 2

The problem is I have to scroll a long way before i can find the next list item.The list items do not appear one below the other.How to resolve this issue?
Here is my code:

package com.example.hp.customlistview;

import android.support.constraint.ConstraintLayout;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {

    int IMAGES[]={R.drawable.adsense, R.drawable.allo, R.drawable.chrome, R.drawable.firebase, R.drawable.youtube};
    String[] NAMES={"AdSense","Allo","Chrome","Firebase","YouTube"};
    String [] DESCRIPTIONS={"Money through ads","Video calling","Web Browser","Cloud Database","Video Streaming"};
    private ListView listView;
    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        listView=(ListView)findViewById(R.id.listView);
        CustomAdapter customAdapter=new CustomAdapter();
        listView.setAdapter(customAdapter);
    }

    class CustomAdapter extends BaseAdapter{

        @Override
        public int getCount() {
            Log.d("Length of Array ","The length is "+IMAGES.length);
            return IMAGES.length;
        }

        @Override
        public Object getItem(int i) {
            return null;
        }

        @Override
        public long getItemId(int i) {
            return i;
        }

        @Override
        public View getView(int i, View view, ViewGroup viewGroup) {
            LayoutInflater layoutInflater=(LayoutInflater)getApplicationContext().getSystemService(getApplicationContext().LAYOUT_INFLATER_SERVICE);
            view=layoutInflater.inflate(R.layout.customlayout, null);
            Log.d("Image ID","The id is "+R.id.imageView);
            ImageView imageView=(ImageView)view.findViewById(R.id.imageView);
            TextView textView_name=(TextView)view.findViewById(R.id.textView);
            TextView textView_desc=(TextView)view.findViewById(R.id.textView2);
            if(imageView==null)
                Log.d("NULL?","YES IT IS NULL");
            else
                Log.d("NULL?","NO IT IS NOT NULL");
            imageView.setImageResource(IMAGES[i]);
            textView_name.setText(NAMES[i]);
            textView_desc.setText(DESCRIPTIONS[i]);
            Log.d("Hello","Hello there "+textView_name.getText().toString());
            return view;
        }
    }
}

customlayout.xml

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="120dp">

    <ImageView
        android:id="@+id/imageView"
        android:layout_width="86dp"
        android:layout_height="91dp"
        android:layout_marginBottom="8dp"
        android:layout_marginStart="32dp"
        android:layout_marginTop="16dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.0"
        app:srcCompat="@mipmap/ic_launcher" />

    <TextView
        android:id="@+id/textView"
        android:layout_width="161dp"
        android:layout_height="39dp"
        android:layout_marginBottom="8dp"
        android:layout_marginStart="28dp"
        android:layout_marginTop="24dp"
        app:layout_constraintBottom_toTopOf="@+id/textView2"
        app:layout_constraintStart_toEndOf="@+id/imageView"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.0" />

    <TextView
        android:id="@+id/textView2"
        android:layout_width="237dp"
        android:layout_height="57dp"
        android:layout_marginBottom="380dp"
        android:layout_marginEnd="8dp"
        android:layout_marginRight="16dp"
        android:layout_marginStart="44dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="1.0"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintStart_toEndOf="@+id/imageView" />

    <CheckBox
        android:id="@+id/checkBox"
        android:layout_width="39dp"
        android:layout_height="39dp"
        android:layout_marginRight="16dp"
        android:layout_marginTop="16dp"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintStart_toEndOf="@+id/textView"
        app:layout_constraintTop_toTopOf="parent" />
</android.support.constraint.ConstraintLayout>

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.example.hp.customlistview.MainActivity">

    <ListView
        android:id="@+id/listView"
        android:layout_width="386dp"
        android:layout_height="409dp"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <Button
        android:id="@+id/button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="24dp"
        android:text="Ok"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/listView" />
</android.support.constraint.ConstraintLayout>

To resolve this, i tried the following

1)android:layout_height="match_parent" to a specific height of 120 dp.
(It is in customlayout.xml)
But it did not work

2)Used some other layout, such as Absolute and Relative Layout, but image fills up the list content much beyond expected size

EDIT:
I have the list items displayed in a compact manner, as follows,
after suggestions by Ben P. in the comments below.
IMAGE 3
But the description is not appearing,although clearly i have set it programatically in MainActivity.java
I observed that setting android:layout_height to some custom value makes the description text view disappear in the preview.

If someone is downvoting,please give the reason for doing so. This will help me improve the quality of my questions.


问:
Which sorting algorithm is better?
I have read about Block sort algorithm and wondering now why it is not popular as for example quicksort, even though it is better than quicksort according to table in this  wikipedia page. Block sort algorithm's complexity worst case scenario is nlog(n) and memory complexity is constant, whereas quicksort have n^2 and log(n) respectively. Thanks in advance.</p>

答:
QuickSort is faster than mergesort because it has no loop in it's recursion where mergesort has to copy it's element in aux array and one more thing:

O(NlogN) is number of compares that mergesort does but it does also 6NlogN array acceses.

Quicksort uses NlogN but if you always shuffle before sorting then you can get some probablistic guarantee that you never has a worst case.

One thing i would say that Big-O notation is not a perfect way to compare two sorting algorithms running time. As i said Quicksort uses NlogN compares to sort an array but this is only true if i use BigO notation , with tilde notation quicksort makes ~1.39NlogN compares.

Title: Which sorting algorithm is better?


问:
Swift Value of type "ViewController" has no member named "Self" error
I am trying to understand trailing edge closures in Swift, and this code gives me an error in the promptForAnswer(). Specifically, I am getting an Xcode error which says:

Value of type "ViewController" has no member named "Self"

...even though I have declared it in the code.

Can someone explain what is wrong?

```<code>import UIKit
import GameplayKit

var allWords = [String]()
var usedWords = [String]()

class ViewController: UITableViewController {

    override func viewDidLoad() {
        super.viewDidLoad()

        navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: .add, target: self, action: #selector(promptForAnswer))

        if let startWordsPath = Bundle.main.path(forResource: "start", ofType: "txt") {
            if let startWords = try? String(contentsOfFile: startWordsPath) {
                allWords = startWords.components(separatedBy: "\n")
            }
        } else {
            allWords = ["silkworm"]
        }
        startGame()
    }

    @objc func promptForAnswer() {
        let ac = UIAlertController(title: "Enter answer", message: nil, preferredStyle: .alert)
        ac.addTextField()

        let submitAction = UIAlertAction(title: "Submit", style: .default) {
            [unowned self, ac] (action: UIAlertAction) in
            let answer = ac.textFields![0]
            self.submit(answer: answer.text!) // Value of type "ViewController" has no member type "self"
        }

        ac.addAction(submitAction)
        present(ac, animated: true)
    }

    func startGame() {
        allWords = GKRandomSource.sharedRandom().arrayByShufflingObjects(in: allWords) as! [String]
        title = allWords[0]
        usedWords.removeAll(keepingCapacity: true)
        tableView.reloadData()
    }

    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return usedWords.count
    }

    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "Word", for: indexPath)
        cell.textLabel?.text = usedWords[indexPath.row]
        return cell
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
}
</code>```

答:
When I pasted your code into a playground in Xcode 9.2 using the default toolchain (Swift 4.0), I got this error on the line you indicated:

Value of type 'ViewController' has no member 'submit'

You can resolve this error by adding a method to your controller that looks like this:

```<code>func submit(answer: String) {
  // ...
}
</code>```

Maybe there was a bug in whatever compiler version you were using. Or maybe it was just having a bad day. Sometimes weird things happen. ¯\_(ツ)_/¯

Things can change a lot between even minor versions of Swift, so make sure to include the versions of Xcode and the toolchain you are using. It makes reproducing your experience significantly easier.

Body:
I am trying to understand trailing edge closures in Swift, and this code gives me an error in the promptForAnswer(). Specifically, I am getting an Xcode error which says:

Value of type "ViewController" has no member named "Self"

...even though I have declared it in the code.

Can someone explain what is wrong?

import UIKit
import GameplayKit

var allWords = [String]()
var usedWords = [String]()

class ViewController: UITableViewController {

    override func viewDidLoad() {
        super.viewDidLoad()

        navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: .add, target: self, action: #selector(promptForAnswer))

        if let startWordsPath = Bundle.main.path(forResource: "start", ofType: "txt") {
            if let startWords = try? String(contentsOfFile: startWordsPath) {
                allWords = startWords.components(separatedBy: "\n")
            }
        } else {
            allWords = ["silkworm"]
        }
        startGame()
    }

    @objc func promptForAnswer() {
        let ac = UIAlertController(title: "Enter answer", message: nil, preferredStyle: .alert)
        ac.addTextField()

        let submitAction = UIAlertAction(title: "Submit", style: .default) {
            [unowned self, ac] (action: UIAlertAction) in
            let answer = ac.textFields![0]
            self.submit(answer: answer.text!) // Value of type "ViewController" has no member type "self"
        }

        ac.addAction(submitAction)
        present(ac, animated: true)
    }

    func startGame() {
        allWords = GKRandomSource.sharedRandom().arrayByShufflingObjects(in: allWords) as! [String]
        title = allWords[0]
        usedWords.removeAll(keepingCapacity: true)
        tableView.reloadData()
    }

    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return usedWords.count
    }

    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "Word", for: indexPath)
        cell.textLabel?.text = usedWords[indexPath.row]
        return cell
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
}

Body:
When I pasted your code into a playground in Xcode 9.2 using the default toolchain (Swift 4.0), I got this error on the line you indicated:

Value of type 'ViewController' has no member 'submit'

You can resolve this error by adding a method to your controller that looks like this:

func submit(answer: String) {
  // ...
}

Maybe there was a bug in whatever compiler version you were using. Or maybe it was just having a bad day. Sometimes weird things happen. ¯\_(ツ)_/¯

Things can change a lot between even minor versions of Swift, so make sure to include the versions of Xcode and the toolchain you are using. It makes reproducing your experience significantly easier.


问:
How to disable and put limits on checkboxes with radio button (Javascript)
I have a radio-type button and a few checkboxes. I basically want to disable the checkboxes when I choose Non-Exclusive then limit the checkboxes to 2 if I choose Package 1.

Here's my html code:

```<code><label>
    <input type="radio" value="non-exclusive" id="non-exclusive" name="packages"> Non-Exclusive
    </label>
    <label>
    <input type="radio" value="package1" id="package1" name="packages"> Package 1
    </label>
    <label>
    <input type="radio" value="package2" id="package2" name="packages"> Package 2
    </label>
<br />
    <label><h2>Rice </h2></label>
    <br />
    <a style="color: darkred;">2 Choices</a>
    <br />
    <div class="checkboxfood">
      <label>
      <input type="checkbox" class="food" value=""> Plain Rice (Mandatory)
      </label>
    <label>
      <input type="checkbox" class="food" value=""> Buttered Rice
      </label>
      <label>
      <input type="checkbox" class="food" value=""> Garlic Rice
      </label>
    <label>
      <input type="checkbox" class="food" value=""> Kimchi Rice
      </label>
    <label>
      <input type="checkbox" class="food" value=""> Adobo Rice
      </label>
    <label>
      <input type="checkbox" class="food" value=""> Yang Chow Rice
      </label>
    <br />
    <label>
      <input type="checkbox" class="food" value=""> Shanghai Rice
      </label>
    <label>
      <input type="checkbox" class="food" value=""> Bagoong Rice
      </label>
    </div>
</code>```

I've tried this javascript:

```<code>$('#package1').on('change', function() {
$('.checkBoxes :checkbox').prop('disabled', true);
$(':checkbox:eq(0), :checkbox:eq(1), :checkbox:eq(2), :checkbox:eq(3), :checkbox:eq(4), :checkbox:eq(5)\n\
, :checkbox:eq(6), :checkbox:eq(7), :checkbox:eq(8), :checkbox:eq(9), :checkbox:eq(10), :checkbox:eq(11), :checkbox:eq(12)\n\
, :checkbox:eq(13), :checkbox:eq(14), :checkbox:eq(15)').prop('disabled', false);

});

$('#package2').on('change', function() {
$('.checkBoxes :checkbox').prop('disabled', true);
$(':checkbox:eq(0), :checkbox:eq(1)').prop('disabled', false);
});

$('#non-exclusive').on('change', function() {
$('.checkBoxes :checkbox').prop('disabled', true);
});
</code>```

It enables checkboxes but it won't limit it. Also if I press back to Non-Exlusive the checkboxes doesn't go back to being "disabled".

I've also tried this code:

```<code>var limit = 3;
$('input.single-checkbox').on('change', function(evt) {
if($(this).siblings(':checked').length >= limit) {
   this.checked = false;
}
});
</code>```

Which limits my checkboxes but isn't responsive to my radio buttons.

答:
Using native JavaScript:

 let q = document.getElementsByClassName('food');
  q = Array.from(q);

  // handle chacked event
  let packages = document.querySelectorAll('input[name="packages"]')
  packages = Array.from(packages);

  let foods = Array.from(document.querySelectorAll('input[type="checkbox"]'))
  foods = Array.from(foods);

  for (let pack in packages) {
    if (packages.hasOwnProperty(pack)) {
      packages[pack].onclick = function () {
        let choosedPack = this.value;

        if (choosedPack === 'non-exclusive') {
          q.forEach(function (item) {
            item.disabled = true;
          });
        } else if (choosedPack === 'package1') {

          q.forEach(function (item) {
            item.disabled = false;
          });

          q.forEach(function (item) {
            item.checked = false;
          });

          for (let food in foods) {
            if (foods.hasOwnProperty(food)) {
              foods[food].onclick = function () {
                if ((document.querySelectorAll('input[type="checkbox"]:checked').length) > 2) {
                  alert('More than 2 values!');
                  this.disabled = false;
                  return false;
                }
              }
            }
          }
        }

      }
    }

  }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><label>
    <input type="radio" value="non-exclusive" id="non-exclusive" name="packages"> Non-Exclusive
</label>
<label>
    <input type="radio" value="package1" id="package1" name="packages"> Package 1
</label>
<label>
    <input type="radio" value="package2" id="package2" name="packages"> Package 2
</label>
<br />
<label><h2>Rice </h2></label>
<br />
2 Choices
<br />
<div class="checkboxfood">
    <label>
        <input type="checkbox" class="food" value=""> Plain Rice (Mandatory)
    </label>
    <label>
        <input type="checkbox" class="food" value=""> Buttered Rice
    </label>
    <label>
        <input type="checkbox" class="food" value=""> Garlic Rice
    </label>
    <label>
        <input type="checkbox" class="food" value=""> Kimchi Rice
    </label>
    <label>
        <input type="checkbox" class="food" value=""> Adobo Rice
    </label>
    <label>
        <input type="checkbox" class="food" value=""> Yang Chow Rice
    </label>
    <br />
    <label>
        <input type="checkbox" class="food" value=""> Shanghai Rice
    </label>
    <label>
        <input type="checkbox" class="food" value=""> Bagoong Rice
    </label>
</div></code>```

Body:
I have a radio-type button and a few checkboxes. I basically want to disable the checkboxes when I choose Non-Exclusive then limit the checkboxes to 2 if I choose Package 1.

Here's my html code:

    <input type="radio" value="non-exclusive" id="non-exclusive" name="packages"> Non-Exclusive

    <input type="radio" value="package1" id="package1" name="packages"> Package 1

    <input type="radio" value="package2" id="package2" name="packages"> Package 2

Rice

    2 Choices

      <input type="checkbox" class="food" value=""> Plain Rice (Mandatory)

      <input type="checkbox" class="food" value=""> Buttered Rice

      <input type="checkbox" class="food" value=""> Garlic Rice

      <input type="checkbox" class="food" value=""> Kimchi Rice

      <input type="checkbox" class="food" value=""> Adobo Rice

      <input type="checkbox" class="food" value=""> Yang Chow Rice

      <input type="checkbox" class="food" value=""> Shanghai Rice

      <input type="checkbox" class="food" value=""> Bagoong Rice

I've tried this javascript:

$('#package1').on('change', function() {
$('.checkBoxes :checkbox').prop('disabled', true);
$(':checkbox:eq(0), :checkbox:eq(1), :checkbox:eq(2), :checkbox:eq(3), :checkbox:eq(4), :checkbox:eq(5)\n\
, :checkbox:eq(6), :checkbox:eq(7), :checkbox:eq(8), :checkbox:eq(9), :checkbox:eq(10), :checkbox:eq(11), :checkbox:eq(12)\n\
, :checkbox:eq(13), :checkbox:eq(14), :checkbox:eq(15)').prop('disabled', false);

});

$('#package2').on('change', function() {
$('.checkBoxes :checkbox').prop('disabled', true);
$(':checkbox:eq(0), :checkbox:eq(1)').prop('disabled', false);
});

$('#non-exclusive').on('change', function() {
$('.checkBoxes :checkbox').prop('disabled', true);
});

It enables checkboxes but it won't limit it. Also if I press back to Non-Exlusive the checkboxes doesn't go back to being "disabled".

I've also tried this code:

var limit = 3;
$('input.single-checkbox').on('change', function(evt) {
if($(this).siblings(':checked').length >= limit) {
   this.checked = false;
}
});

Which limits my checkboxes but isn't responsive to my radio buttons.

Body:
Using native JavaScript:

 let q = document.getElementsByClassName('food');
  q = Array.from(q);

  // handle chacked event
  let packages = document.querySelectorAll('input[name="packages"]')
  packages = Array.from(packages);

  let foods = Array.from(document.querySelectorAll('input[type="checkbox"]'))
  foods = Array.from(foods);

  for (let pack in packages) {
    if (packages.hasOwnProperty(pack)) {
      packages[pack].onclick = function () {
        let choosedPack = this.value;

        if (choosedPack === 'non-exclusive') {
          q.forEach(function (item) {
            item.disabled = true;
          });
        } else if (choosedPack === 'package1') {

          q.forEach(function (item) {
            item.disabled = false;
          });

          q.forEach(function (item) {
            item.checked = false;
          });

          for (let food in foods) {
            if (foods.hasOwnProperty(food)) {
              foods[food].onclick = function () {
                if ((document.querySelectorAll('input[type="checkbox"]:checked').length) > 2) {
                  alert('More than 2 values!');
                  this.disabled = false;
                  return false;
                }
              }
            }
          }
        }

      }
    }

  }

<label>
    <input type="radio" value="non-exclusive" id="non-exclusive" name="packages"> Non-Exclusive
</label>
<label>
    <input type="radio" value="package1" id="package1" name="packages"> Package 1
</label>
<label>
    <input type="radio" value="package2" id="package2" name="packages"> Package 2
</label>
<br />
<label><h2>Rice </h2></label>
<br />
<a style="color: darkred;">2 Choices</a>
<br />
<div class="checkboxfood">
    <label>
        <input type="checkbox" class="food" value=""> Plain Rice (Mandatory)
    </label>
    <label>
        <input type="checkbox" class="food" value=""> Buttered Rice
    </label>
    <label>
        <input type="checkbox" class="food" value=""> Garlic Rice
    </label>
    <label>
        <input type="checkbox" class="food" value=""> Kimchi Rice
    </label>
    <label>
        <input type="checkbox" class="food" value=""> Adobo Rice
    </label>
    <label>
        <input type="checkbox" class="food" value=""> Yang Chow Rice
    </label>
    <br />
    <label>
        <input type="checkbox" class="food" value=""> Shanghai Rice
    </label>
    <label>
        <input type="checkbox" class="food" value=""> Bagoong Rice
    </label>
</div>


问:
iOS11 How to handle a custom file dropped in a custom view
I've been messing around with the drop feature of iOS11. I found a lot of examples with the standard UIImage etc but nothing with custom files.

The drop part works pretty well, I use it to drop a custom file and import it into my app.

The problem is that I only get the Data of this file and I would like to get its name and extension for example.

I don't know if my way of handling the custom file dropped is how it should be to obtain this information. And if so, how do you get this information from the file?

I have a DropFile class conforming to the NSItemProviderReading protocol.

```<code>class DropFile : NSObject, NSItemProviderReading {
  let fileData:Data?

  required init(data:Data, typeIdentifier:String) {
      fileData = data
  }

  static var readableTypeIdentifiersForItemProvider: [String] {
      var documentTypeArray: [String] = []

      for ext in FileImportProcessHelper.sharedInstance.getImportDocumentType() {
          let UTI = UTTypeCreatePreferredIdentifierForTag(kUTTagClassFilenameExtension, ext as CFString, nil)
          documentTypeArray.append((UTI?.takeRetainedValue() as String?)!)
      }
      return documentTypeArray

  }

  static func object(withItemProviderData data: Data, typeIdentifier: String) throws -> Self {
      return self.init(data: data, typeIdentifier: typeIdentifier)
  }
}
</code>```

This is my ViewController conforming to the UIDropInteractionDelegate

```<code>// MARK: Handling Drop

@available(iOS 11.0, *)
// We refuse the dropped items based on their UTI
func dropInteraction(_ interaction: UIDropInteraction, canHandle session: UIDropSession) -> Bool {

    var documentTypeArray: [String] = []

    for ext in FileImportProcessHelper.sharedInstance.getImportDocumentType() {
        let UTI = UTTypeCreatePreferredIdentifierForTag(kUTTagClassFilenameExtension, ext as CFString, nil)
        documentTypeArray.append(UTI?.takeRetainedValue() as! String)
    }
    return session.hasItemsConforming(toTypeIdentifiers: documentTypeArray) && session.items.count == 1
}

@available(iOS 11.0, *)
func dropInteraction(_ interaction: UIDropInteraction, sessionDidUpdate session: UIDropSession) -> UIDropProposal {
    // Copy file from source app
    return UIDropProposal(operation: .copy)
}

@available(iOS 11.0, *)
func dropInteraction(_ interaction: UIDropInteraction, performDrop session: UIDropSession) {
    // Consume drag items
    session.loadObjects(ofClass: DropFile.self) { items in
        if let fileItems = items as? [DropFile] {
            DragnDropManager.sharedManager.createDropObject(fileItems: fileItems)
        }
    }
}
</code>```

And then how I write my file.

```<code>func createDropObject(fileItems: [DropFile]) {
        let documentsPathString = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).first
        let inbox = URL(fileURLWithPath: documentsPathString!).appendingPathComponent("UserDropInbox/")

        do {
            try FileManager.default.createDirectory(atPath: inbox.path, withIntermediateDirectories: true, attributes: nil)
        } catch let error as NSError {
            NSLog("Unable to create directory \(error.debugDescription)")
        }

        for file in fileItems {
            do {
                let dropFilePath = inbox.appendingPathComponent("File").appendingPathExtension("pdf")
                try file.fileData?.write(to:dropFilePath)
            } catch {
                NSLog(error as! String)
            }
        }

        FileImportInboxManager.shared.hasReceivedFiles = true;
 }
</code>```

答:
I admit, it's not straightforward :

you can list all the UIDragItems dragged by the user in the UIDropSession items member

each of these items have a NSItemProvider itemProvider member

this item provider has an optional String? suggestedName member that may not be nil

A simple loop to print all the session's items suggested names :

```<code>for item in session.items {
   if let name = item.itemProvider.suggestedName {
      print(name)
   }
}
</code>```

Practically, when files come from the File app it will provide the name of the file without its extension, but given you can easily access its UTI, you can append an extension that will be close to the original one (jpeg instead of jpg for example).

Body:
I've been messing around with the drop feature of iOS11. I found a lot of examples with the standard UIImage etc but nothing with custom files.

The drop part works pretty well, I use it to drop a custom file and import it into my app.

The problem is that I only get the Data of this file and I would like to get its name and extension for example.

I don't know if my way of handling the custom file dropped is how it should be to obtain this information. And if so, how do you get this information from the file?

I have a DropFile class conforming to the NSItemProviderReading protocol.

class DropFile : NSObject, NSItemProviderReading {
  let fileData:Data?

  required init(data:Data, typeIdentifier:String) {
      fileData = data
  }

  static var readableTypeIdentifiersForItemProvider: [String] {
      var documentTypeArray: [String] = []

      for ext in FileImportProcessHelper.sharedInstance.getImportDocumentType() {
          let UTI = UTTypeCreatePreferredIdentifierForTag(kUTTagClassFilenameExtension, ext as CFString, nil)
          documentTypeArray.append((UTI?.takeRetainedValue() as String?)!)
      }
      return documentTypeArray

  }

  static func object(withItemProviderData data: Data, typeIdentifier: String) throws -> Self {
      return self.init(data: data, typeIdentifier: typeIdentifier)
  }
}

This is my ViewController conforming to the UIDropInteractionDelegate

// MARK: Handling Drop

@available(iOS 11.0, *)
// We refuse the dropped items based on their UTI
func dropInteraction(_ interaction: UIDropInteraction, canHandle session: UIDropSession) -> Bool {

    var documentTypeArray: [String] = []

    for ext in FileImportProcessHelper.sharedInstance.getImportDocumentType() {
        let UTI = UTTypeCreatePreferredIdentifierForTag(kUTTagClassFilenameExtension, ext as CFString, nil)
        documentTypeArray.append(UTI?.takeRetainedValue() as! String)
    }
    return session.hasItemsConforming(toTypeIdentifiers: documentTypeArray) && session.items.count == 1
}

@available(iOS 11.0, *)
func dropInteraction(_ interaction: UIDropInteraction, sessionDidUpdate session: UIDropSession) -> UIDropProposal {
    // Copy file from source app
    return UIDropProposal(operation: .copy)
}

@available(iOS 11.0, *)
func dropInteraction(_ interaction: UIDropInteraction, performDrop session: UIDropSession) {
    // Consume drag items
    session.loadObjects(ofClass: DropFile.self) { items in
        if let fileItems = items as? [DropFile] {
            DragnDropManager.sharedManager.createDropObject(fileItems: fileItems)
        }
    }
}

And then how I write my file.

func createDropObject(fileItems: [DropFile]) {
        let documentsPathString = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).first
        let inbox = URL(fileURLWithPath: documentsPathString!).appendingPathComponent("UserDropInbox/")

        do {
            try FileManager.default.createDirectory(atPath: inbox.path, withIntermediateDirectories: true, attributes: nil)
        } catch let error as NSError {
            NSLog("Unable to create directory \(error.debugDescription)")
        }

        for file in fileItems {
            do {
                let dropFilePath = inbox.appendingPathComponent("File").appendingPathExtension("pdf")
                try file.fileData?.write(to:dropFilePath)
            } catch {
                NSLog(error as! String)
            }
        }

        FileImportInboxManager.shared.hasReceivedFiles = true;
 }

Body:
I admit, it's not straightforward :

you can list all the UIDragItems dragged by the user in the UIDropSession items member

each of these items have a NSItemProvider itemProvider member

this item provider has an optional String? suggestedName member that may not be nil

A simple loop to print all the session's items suggested names :

for item in session.items {
   if let name = item.itemProvider.suggestedName {
      print(name)
   }
}

Practically, when files come from the File app it will provide the name of the file without its extension, but given you can easily access its UTI, you can append an extension that will be close to the original one (jpeg instead of jpg for example).


问:
Implementing callback function within a class in C++
I would like to implement a workaround to use a non-static class as a call-back function. I am working with Eclipse Paho MQTT code. The following type is implemented and used as callback:

```<code>typedef void MQTTAsync_onSuccess(void* context, MQTTAsync_successData* response);

MQTTAsync_onSuccess* onSuccess;

onSuccess = myStaticCallback;

void myStaticCallback (void* context, MQTTAsync_successData* response)
{
   //...callback actions...
}
</code>```

I want to wrap this C API (without modifying the existing MQTT C API) and implement non-static / non-centralized callback function that belongs to an object/class.

```<code>typedef void MQTTAsync_onSuccess(void* context, MQTTAsync_successData* response);

class myMQTTClass
{
   private:
      void myCallback (void* context, MQTTAsync_successData* response);
      MQTTAsync_onSuccess* onSuccess;

   public:
      void foo (void)
      {
          this->onSuccess = this->myCallback;
      }
}
</code>```

As you might guess, the code above causes the error:
cannot convert myCallback from type 'void (myMQTTClass::) (void*, MQTTAsync_successData*)' to type 'void (*)(void*, MQTTAsync_successData*)'.

Any guidance as to how to address this issue or any workaround is greately appreciated. I would be willing to provide any possible missing information. Thanks in advance.

EDIT: Actual code with some omissions

```<code>   namespace rover
    {
       typedef struct
       {
        char * clientID;
        char * topic;
        char * payload;
        int         qos;        // 1
        long int    timeout;    // Such as 10000L usec
       } RoverMQTT_Configure_t;

       class RoverPahoMQTT
       {
           public:
              RoverPahoMQTT (char * host_name, int port, RoverMQTT_Configure_t MQTT_Configure);

           private:

             /**
             * @brief Host name used for connecting to the Eclipse Paho MQTT server
             */
            char * HOST_NAME;

            /**
             * @brief Port used for connecting to the Eclipse Paho MQTT server
             */
            int PORT;

            RoverMQTT_Configure_t rover_MQTT_configure;

            /* Internal attributes */
            MQTTAsync client;

            /**
             * @brief Connect options
             */
            MQTTAsync_connectOptions conn_opts;

            /**
             * @brief Disconnect options
             */
            MQTTAsync_disconnectOptions disc_opts;

             //...
             static void onPublisherConnect (void* context, MQTTAsync_successData* response);
             void onPublisherConnect_ (MQTTAsync_successData* response);

           //...

       }
    }

    int rover::RoverPahoMQTT::publish (void)
    {
        this->flushFlags ();

        this->conn_opts = MQTTAsync_connectOptions_initializer;
        this->client = new MQTTAsync;
        int rc;

        char my_addr[20];
        this->constructAddress (my_addr);
        printf ("address: %s", my_addr);
        MQTTAsync_create (  &(this->client),
                            my_addr,
                            this->rover_MQTT_configure.clientID,
                            MQTTCLIENT_PERSISTENCE_NONE,
                            NULL);

        MQTTAsync_setCallbacks(this->client, NULL, onConnectionLost, NULL, NULL);

        conn_opts.keepAliveInterval = 20;
        conn_opts.cleansession = 1;
        conn_opts.onSuccess = rover::RoverPahoMQTT::onPublisherConnect;
        conn_opts.onFailure = onConnectFailure;
        conn_opts.context = this->client;

        if ((rc = MQTTAsync_connect(this->client, &(this->conn_opts))) != MQTTASYNC_SUCCESS)
        {
            printf("Failed to start connect, return code %d\n", rc);
            return rc;
        }

        /*printf("Waiting for publication of %s\n"
             "on topic %s for client with ClientID: %s\n",
             PAYLOAD, TOPIC, CLIENTID);*/
        while (!mqtt_finished)
            usleep(this->rover_MQTT_configure.timeout);

        MQTTAsync_destroy(&client);
        return rc;
    }

    void rover::RoverPahoMQTT::onPublisherConnect_(MQTTAsync_successData* response)
    {
        MQTTAsync_responseOptions opts = MQTTAsync_responseOptions_initializer;
        MQTTAsync_message pubmsg = MQTTAsync_message_initializer;
        int rc;

        printf("Successful connection\n");

        opts.onSuccess = onPublisherSend;
        opts.context = client;

        pubmsg.payload = &default_MQTT_configure.payload;
        pubmsg.payloadlen = strlen(default_MQTT_configure.payload);
        pubmsg.qos = default_MQTT_configure.qos;
        pubmsg.retained = 0;
        deliveredtoken = 0;

        if ((rc = MQTTAsync_sendMessage(client, default_MQTT_configure.topic, &pubmsg, &opts)) != MQTTASYNC_SUCCESS)
        {
            printf("Failed to start sendMessage, return code %d\n", rc);
            exit(EXIT_FAILURE);
        }
    }

    void rover::RoverPahoMQTT::onPublisherConnect (void* context, MQTTAsync_successData* response)
    {
        rover::RoverPahoMQTT* m = (rover::RoverPahoMQTT*) context;
        m->onPublisherConnect_(response);
        //((rover::RoverPahoMQTT*)context)->onPublisherConnect_(response);
        // ^^^HERE IS THE SEGMENTATION FAULT

    }
</code>```

答:
If you can use the context parameter to point to the object you want the callback to fire on you could simply make the callback function static and forward to an instance function. If the context parameter is needed for other data then I would use libffi to generate a closure and associate the object pointer with the closure's saved arguments.

There is no correct way to pass an actual instance function to that callback and be sure that it will work (even if you made the instance function be something like void MyCallback(MQTTAsync_successData*) and then forcibly cast that to the callback type you aren't guaranteed that the calling convention would match.

For the first (where you can use the context arg to point to 'this'):

```<code>class MyCallback
{
static void CallbackFunc(void * ptr, MQTTAsync_successData* data)
{
((MyCallback*)ptr)->RealCallback(data);
}
void RealCallback(MQTTAsync_successData*)
{}
};
</code>```

You would then assign &MyCallback::CallbackFunc to the function pointer.

libffi is quite a bit more complicated.

Body:
I would like to implement a workaround to use a non-static class as a call-back function. I am working with Eclipse Paho MQTT code. The following type is implemented and used as callback:

typedef void MQTTAsync_onSuccess(void* context, MQTTAsync_successData* response);

MQTTAsync_onSuccess* onSuccess;

onSuccess = myStaticCallback;

void myStaticCallback (void* context, MQTTAsync_successData* response)
{
   //...callback actions...
}

I want to wrap this C API (without modifying the existing MQTT C API) and implement non-static / non-centralized callback function that belongs to an object/class.

typedef void MQTTAsync_onSuccess(void* context, MQTTAsync_successData* response);

class myMQTTClass
{
   private:
      void myCallback (void* context, MQTTAsync_successData* response);
      MQTTAsync_onSuccess* onSuccess;

   public:
      void foo (void)
      {
          this->onSuccess = this->myCallback;
      }
}

As you might guess, the code above causes the error:
cannot convert myCallback from type 'void (myMQTTClass::) (void*, MQTTAsync_successData*)' to type 'void (*)(void*, MQTTAsync_successData*)'.

Any guidance as to how to address this issue or any workaround is greately appreciated. I would be willing to provide any possible missing information. Thanks in advance.

EDIT: Actual code with some omissions

   namespace rover
    {
       typedef struct
       {
        char * clientID;
        char * topic;
        char * payload;
        int         qos;        // 1
        long int    timeout;    // Such as 10000L usec
       } RoverMQTT_Configure_t;

       class RoverPahoMQTT
       {
           public:
              RoverPahoMQTT (char * host_name, int port, RoverMQTT_Configure_t MQTT_Configure);

           private:

             /**
             * @brief Host name used for connecting to the Eclipse Paho MQTT server
             */
            char * HOST_NAME;

            /**
             * @brief Port used for connecting to the Eclipse Paho MQTT server
             */
            int PORT;

            RoverMQTT_Configure_t rover_MQTT_configure;

            /* Internal attributes */
            MQTTAsync client;

            /**
             * @brief Connect options
             */
            MQTTAsync_connectOptions conn_opts;

            /**
             * @brief Disconnect options
             */
            MQTTAsync_disconnectOptions disc_opts;

             //...
             static void onPublisherConnect (void* context, MQTTAsync_successData* response);
             void onPublisherConnect_ (MQTTAsync_successData* response);

           //...

       }
    }

    int rover::RoverPahoMQTT::publish (void)
    {
        this->flushFlags ();

        this->conn_opts = MQTTAsync_connectOptions_initializer;
        this->client = new MQTTAsync;
        int rc;

        char my_addr[20];
        this->constructAddress (my_addr);
        printf ("address: %s", my_addr);
        MQTTAsync_create (  &(this->client),
                            my_addr,
                            this->rover_MQTT_configure.clientID,
                            MQTTCLIENT_PERSISTENCE_NONE,
                            NULL);

        MQTTAsync_setCallbacks(this->client, NULL, onConnectionLost, NULL, NULL);

        conn_opts.keepAliveInterval = 20;
        conn_opts.cleansession = 1;
        conn_opts.onSuccess = rover::RoverPahoMQTT::onPublisherConnect;
        conn_opts.onFailure = onConnectFailure;
        conn_opts.context = this->client;

        if ((rc = MQTTAsync_connect(this->client, &(this->conn_opts))) != MQTTASYNC_SUCCESS)
        {
            printf("Failed to start connect, return code %d\n", rc);
            return rc;
        }

        /*printf("Waiting for publication of %s\n"
             "on topic %s for client with ClientID: %s\n",
             PAYLOAD, TOPIC, CLIENTID);*/
        while (!mqtt_finished)
            usleep(this->rover_MQTT_configure.timeout);

        MQTTAsync_destroy(&client);
        return rc;
    }

    void rover::RoverPahoMQTT::onPublisherConnect_(MQTTAsync_successData* response)
    {
        MQTTAsync_responseOptions opts = MQTTAsync_responseOptions_initializer;
        MQTTAsync_message pubmsg = MQTTAsync_message_initializer;
        int rc;

        printf("Successful connection\n");

        opts.onSuccess = onPublisherSend;
        opts.context = client;

        pubmsg.payload = &default_MQTT_configure.payload;
        pubmsg.payloadlen = strlen(default_MQTT_configure.payload);
        pubmsg.qos = default_MQTT_configure.qos;
        pubmsg.retained = 0;
        deliveredtoken = 0;

        if ((rc = MQTTAsync_sendMessage(client, default_MQTT_configure.topic, &pubmsg, &opts)) != MQTTASYNC_SUCCESS)
        {
            printf("Failed to start sendMessage, return code %d\n", rc);
            exit(EXIT_FAILURE);
        }
    }

    void rover::RoverPahoMQTT::onPublisherConnect (void* context, MQTTAsync_successData* response)
    {
        rover::RoverPahoMQTT* m = (rover::RoverPahoMQTT*) context;
        m->onPublisherConnect_(response);
        //((rover::RoverPahoMQTT*)context)->onPublisherConnect_(response);
        // ^^^HERE IS THE SEGMENTATION FAULT

    }

Body:
If you can use the context parameter to point to the object you want the callback to fire on you could simply make the callback function static and forward to an instance function. If the context parameter is needed for other data then I would use libffi to generate a closure and associate the object pointer with the closure's saved arguments.

There is no correct way to pass an actual instance function to that callback and be sure that it will work (even if you made the instance function be something like void MyCallback(MQTTAsync_successData*) and then forcibly cast that to the callback type you aren't guaranteed that the calling convention would match.

For the first (where you can use the context arg to point to 'this'):

class MyCallback
{
static void CallbackFunc(void * ptr, MQTTAsync_successData* data)
{
((MyCallback*)ptr)->RealCallback(data);
}
void RealCallback(MQTTAsync_successData*)
{}
};

You would then assign &MyCallback::CallbackFunc to the function pointer.

libffi is quite a bit more complicated.


问:
Convert tuple to list in a dictionary
I have a dictionary like this:

```<code>a= {1982: [(1,2,3,4)],
    1542: [(4,5,6,7),
           (4,6,5,7)]}
</code>```

and I want to change the all the tuples (1,2,3,4),(4,5,6,7),(4,6,5,7) to lists, in this case: [1,2,3,4], [4,5,6,7], [4,6,5,7]

I have tried

```<code>for key, value in a.items():
    for i in value:
        i = tuple(i)
</code>```

but it does now work. How can I achieve it?

答:
In-place:

```<code>for key, value in a.items():
    for i, t in enumerate(value):
        value[i]= list(t)
</code>```

New objects:

```<code>{key: [list(t) for t in value] for key, value in a.items()}
</code>```

Title: Convert tuple to list in a dictionary

Body:
I have a dictionary like this:

a= {1982: [(1,2,3,4)],
    1542: [(4,5,6,7),
           (4,6,5,7)]}

and I want to change the all the tuples (1,2,3,4),(4,5,6,7),(4,6,5,7) to lists, in this case: [1,2,3,4], [4,5,6,7], [4,6,5,7]

I have tried

for key, value in a.items():
    for i in value:
        i = tuple(i)

but it does now work. How can I achieve it?

Body:
In-place:

for key, value in a.items():
    for i, t in enumerate(value):
        value[i]= list(t)

New objects:

{key: [list(t) for t in value] for key, value in a.items()}


问:
iPhone opengl es alpha-blending. I have black color in edge
I am developing iPhone game. I have the below Source image to draw it to the background. The Source image has alpha 0x00 and gradation around edge and the background's alpha is 0xff. When I draw the source image to the background, I have black color like you could see the Result image. I am using OpenGL ES glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA) method. I have changed every possible arguments, but every time it is not moved.

Why do I have the black color in the edge of the source image? What is the problem? Does not every games in iphone use gradation?

Do I need to make the source image with out gradation?

Does anyone know the solution?

Source image :

Result image :

答: Just check the view on which you are drawing is opaque or not. set opaque property to false</p>


问:
How to navigate with parameters on an universal app Windows 8.1 / WP 8.1 with MVVMLight
I develop an universal app Windows 8.1/ Windows Phone 8.1 with MVVMLight.
I would like to know which is the best practice to implement  navigation between the pages.

There is the following pages:

MainPage: is a login page

HomePage: is a hub with different sections "list of themes", "list of contacts", "user details"

ListArticlesFromTheme : list of articles for the selected theme

DetailsContact : details of the selected contact

DetailsArticle : details of the selected article

I need so to pass parameters by navigating from a page to another: the selected theme, the selected contact, the selected article, ...

I found an example implementation of navigation tavers MVVMLight v5, but without parameters:
navigationservice-in-mvvm-light-v5

I found another example with the parameters, but I haven't managed to implement it:

navigating-to-a-new-page-from-the-view-model-in-windows-phone-8-1-universal-app

Is it better to manage navigation through the Views or the ViewModels?

Do you have a more detailed example showing navigation with parameters?

答:
If you want to either:

Access the parameter that is passed in the NavigationServicesEx.Navigate method

Call a method in your ViewModel when a page is navigated to.

This blog by Marco Minerva shows how to hook in to the Frame_Navigating event that it missing from the vanilla NavigationServiceEx class.

Create the INavigable interface described in the blog:

```<code>public interface INavigable
{
    Task OnNavigatedToAsync(object parameter, NavigationMode mode);
    void OnNavigatingFrom(NavigatingCancelEventArgs e);
    void OnNavigatedFrom();
}
</code>```

Add a handler for the Frame.Navigating event in the NavigationServicesEx class (with some additional plumbing, see blog) then realise the INavigable interface in your ViewModels.

You will then be able to access the parameter that you passed in your Navigate call:

```<code>NavigationServiceEx.Navigate(typeof(DestinationPage).FullName, yourParameter);
</code>```

In the OnNavigatedToAsync method that you implement in your ViewModel:

```<code>public Task OnNavigatedToAsync(object parameter, NavigationMode mode)
{
    if (parameter != null)
    {
        YourThing thing = parameter as YourThing;
        this.UseYourThing(thing);
    }
    return Task.CompletedTask;
}
</code>```

EDIT: Oh, and navigate through the ViewModel. You can call a method in your VM that handles navigation from either a Command or in the View's code behind.

Body:
If you want to either:

Access the parameter that is passed in the NavigationServicesEx.Navigate method

Call a method in your ViewModel when a page is navigated to.

This blog by Marco Minerva shows how to hook in to the Frame_Navigating event that it missing from the vanilla NavigationServiceEx class.

Create the INavigable interface described in the blog:

public interface INavigable
{
    Task OnNavigatedToAsync(object parameter, NavigationMode mode);
    void OnNavigatingFrom(NavigatingCancelEventArgs e);
    void OnNavigatedFrom();
}

Add a handler for the Frame.Navigating event in the NavigationServicesEx class (with some additional plumbing, see blog) then realise the INavigable interface in your ViewModels.

You will then be able to access the parameter that you passed in your Navigate call:

NavigationServiceEx.Navigate(typeof(DestinationPage).FullName, yourParameter);

In the OnNavigatedToAsync method that you implement in your ViewModel:

public Task OnNavigatedToAsync(object parameter, NavigationMode mode)
{
    if (parameter != null)
    {
        YourThing thing = parameter as YourThing;
        this.UseYourThing(thing);
    }
    return Task.CompletedTask;
}

EDIT: Oh, and navigate through the ViewModel. You can call a method in your VM that handles navigation from either a Command or in the View's code behind.


问:
Change matplotlib.bar Order in python 2.7
In this example:

```<code>import matplotlib.pyplot as plt

colors = ['white', 'orange', 'green', 'purple']
rates = ['5','5','4','3']

plt.bar(colors, rates)
</code>```

the bars in the plot are ordered by the alphabetic order.

How do I make them to show in the same order as they are in the code (from highest to lowest rate)?

答:
Matplotlib 2.1 provides the new option to use strings as input to its plotting functions - called "categoricals". This is a new feature and not yet completely working. One caveat is that strings are automatically sorted (alphabetically). This restriction will be removed in the next release.

Until then you would produce your plot just as in times when matplotlib did not even allow for strings to put in. Convert data to numbers, and plot against the list index. Afterwards set the ticklabels to their names.

```<code>import matplotlib.pyplot as plt

colors = ['white', 'orange', 'green', 'purple']
rates = ['5','5','4','3']

plt.bar(range(len(colors)), list(map(float,rates)) )
plt.xticks(range(len(colors)), colors)

plt.show()
</code>```

Body:
In this example:

import matplotlib.pyplot as plt

colors = ['white', 'orange', 'green', 'purple']
rates = ['5','5','4','3']

plt.bar(colors, rates)

the bars in the plot are ordered by the alphabetic order.

How do I make them to show in the same order as they are in the code (from highest to lowest rate)?

Body:
Matplotlib 2.1 provides the new option to use strings as input to its plotting functions - called "categoricals". This is a new feature and not yet completely working. One caveat is that strings are automatically sorted (alphabetically). This restriction will be removed in the next release.

Until then you would produce your plot just as in times when matplotlib did not even allow for strings to put in. Convert data to numbers, and plot against the list index. Afterwards set the ticklabels to their names.

import matplotlib.pyplot as plt

colors = ['white', 'orange', 'green', 'purple']
rates = ['5','5','4','3']

plt.bar(range(len(colors)), list(map(float,rates)) )
plt.xticks(range(len(colors)), colors)

plt.show()


问:
Spell-checker in OSX not recognizing even basic English words
Regardless of which application I use in mac OS (Sierra), even the most basic English words are not being recognized by the spell checker. Is there any way to "reset" the Dictionary in mac OS?

答:
Press command-shift-semicolon to get into the spelling checker preferences, and check if you have picked a language other than English. </p>

<p>If it's set to German, yes, then it won't recognise even basic English words. </p>

Body:
Press command-shift-semicolon to get into the spelling checker preferences, and check if you have picked a language other than English.

If it's set to German, yes, then it won't recognise even basic English words.