问:
exception Convert ToInt32 dans c#
I have this code but  but when I run the program gives me this error System.FormatException: Input string was not in a correct format'.</p>

```<code>      public static void Main(string[] args)
    {

        string a =TextFormater("Teste teste ");

        Console.WriteLine(a);
    }
     public static string TextFormater(string ChaineTextArea)
    {
        string val = string.Empty;
        string Valreturn = string.Empty;
        int result;
        for (int i = 0; i <= ChaineTextArea.Length; i++)
        {
            val = ChaineTextArea.Substring(i, 1);
            var chars = val.ToCharArray();

            result = Convert.ToInt32(val);

            if (result != 13)
            {
                Valreturn= val;
            }

            else
            {
                Valreturn= "<br>" + val;
            }
        }
        return Valreturn;
    }
</code>```

答: I am not sure what you are trying to achieve. If you are trying to convert string to int then it is invalid conversion but you think if the val maybe int or string then try to use int.TryParse</p>

Title: exception Convert ToInt32 dans c#

Body:
I have this code but  but when I run the program gives me this error System.FormatException: Input string was not in a correct format'.

      public static void Main(string[] args)
    {

        string a =TextFormater("Teste teste ");

        Console.WriteLine(a);
    }
     public static string TextFormater(string ChaineTextArea)
    {
        string val = string.Empty;
        string Valreturn = string.Empty;
        int result;
        for (int i = 0; i <= ChaineTextArea.Length; i++)
        {
            val = ChaineTextArea.Substring(i, 1);
            var chars = val.ToCharArray();

            result = Convert.ToInt32(val);

            if (result != 13)
            {
                Valreturn= val;
            }

            else
            {
                Valreturn= "
" + val;
            }
        }
        return Valreturn;
    }


来源: stackexchange

问:
Android GPS service returns 0.0 every time
I've been searching around for days but can't find what the problem can be. I want to know my current position when I'm clicking button A, and also know my position when I'm clicking button B. Problem is this, when I click B it seems to work fine, but not in A. I use the exact same code on both of them, but in some way it just wont work for A.

Here is my GetGPSLocation code
`

```<code>package com.example.eandl.gps;

import android.Manifest;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.location.LocationListener;
import android.location.LocationManager;
import android.provider.Settings;
import android.support.v4.app.ActivityCompat;
import android.util.Log;
import android.view.View;
import android.widget.Toast;

public class GetGPSLocation {
    private Context context;
    private static double lat;
    private static double lang;

    public GetGPSLocation(Context context){
        this.context = context;
        this.lat = 0.0;
        this.lang = 0.0;
    }

    public void setLat(double lat) {
        this.lat = lat;
    }

    public void setLang(double lang) {
        this.lang = lang;
    }

    public Boolean displayGpsStatus() {
        final LocationManager manager = (LocationManager) context.getSystemService( Context.LOCATION_SERVICE );

        if ( !manager.isProviderEnabled( LocationManager.NETWORK_PROVIDER ) ) {
            return false;
        }else{
            return true;
        }
    }

    public double[] getLatLong(){
        double[] latLong = new double[2];
        if(displayGpsStatus()){

            LocationManager locationMangaer = (LocationManager)context.getSystemService(Context.LOCATION_SERVICE);
            LocationListener locationListener = new MyLocationListener(context, this);

            if (ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                // TODO: Consider calling
                //    ActivityCompat#requestPermissions
                // here to request the missing permissions, and then overriding
                //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
                //                                          int[] grantResults)
                // to handle the case where the user grants the permission. See the documentation
                // for ActivityCompat#requestPermissions for more details.
                ActivityCompat.requestPermissions((Activity)context,new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, 1);
            }
            if(checkLocationPermission()){
                locationMangaer.requestLocationUpdates(LocationManager
                        .NETWORK_PROVIDER, 0, 0, locationListener);
            }

            Log.d("findError", getLang() + "");
            latLong[0] = getLat();
            latLong[1] = getLang();

        }else{
            alertbox("Gps status", "Your Device's GPS is Disable");
        }

        return latLong;
    }

    public boolean checkLocationPermission()
    {
        String permission = "android.permission.ACCESS_FINE_LOCATION";
        int res = context.checkCallingOrSelfPermission(permission);

        return (res == PackageManager.PERMISSION_GRANTED);
    }

    protected void alertbox(String title, String mymessage) {
        AlertDialog.Builder builder = new AlertDialog.Builder(context);
        builder.setMessage(mymessage)
                .setCancelable(false)
                .setTitle(title)
                .setPositiveButton("Gps On",
                        new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int id) {
                                // finish the current activity
                                // AlertBoxAdvance.this.finish();
                                Intent myIntent = new Intent(
                                        Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                                context.startActivity(myIntent);
                                dialog.cancel();
                            }
                        })
                .setNegativeButton("Cancel",
                        new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int id) {
                                // cancel the dialog box
                                dialog.cancel();
                            }
                        });
        AlertDialog alert = builder.create();
        alert.show();
    }

}
</code>```

`

And the Listiener

```<code>package com.example.eandl.gps;

import android.content.Context;
import android.content.pm.PackageManager;
import android.location.Location;
import android.location.LocationListener;
import android.os.Bundle;
import android.util.Log;
import android.widget.Toast;

public class MyLocationListener implements LocationListener {

    private Context context;
    private GetGPSLocation getGPSLocation;

    public MyLocationListener(Context context, GetGPSLocation getGPSLocation) {
        this.context = context;
        this.getGPSLocation = getGPSLocation;
    }

    @Override
    public void onLocationChanged(Location loc) {
        if(loc != null){
            getGPSLocation.setLat(loc.getLatitude());
            getGPSLocation.setLang(loc.getLongitude());
        }
    }

    @Override
    public void onProviderDisabled(String provider) {
        // TODO Auto-generated method stub
    }

    @Override
    public void onProviderEnabled(String provider) {
        // TODO Auto-generated method stub
    }

    @Override
    public void onStatusChanged(String provider,
                                int status, Bundle extras) {
        // TODO Auto-generated method stub
    }
}
</code>```

The way I'm trying to call it is by new GetGPSLocation(context).getLatLong but as I said, sometimes it returns my position and sometimes 0.0

Thank you!

答:
Alright so first I'm setting it up when I create my view like this

```<code>    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) {
    //Fixa vit med blå text
    myView = inflater.inflate(R.layout.fragment_signup, container, false);
    placements = new ArrayList<CheckBox>();
    GetPlacements getPlacements = new GetPlacements(this);
    getPlacements.execute();

    getGPSLocation = new GetGPSLocation(myView.getContext());
    getGPSLocation.getLatLong();
</code>```

Then this is the onclicklistener on the button A

```<code>                getGPSLocation.getLatLong();
                DatabasSender databasSender = new DatabasSender(myView.getContext());
                User user = new User(name.getText().toString(), email.getText().toString(), 0);
                user.setSignup(true);
                user.setEdu(edu.getText().toString());
                user.setPhone(phone.getText().toString());
                user.setPlacements(places);
                databasSender.execute(user);
</code>```

That goes to my databassender that uses a AsyncTask

```<code>public DatabasSender(Context context) {
    this.context = context;
    getGPSLocation = new GetGPSLocation(context);

}

@Override
protected void onPreExecute() {
    latLong = getGPSLocation.getLatLong();
}
@Override
protected Object doInBackground(Object[] objects) {
    urlPatten = "..../"+latLong[0]+"&"+latLong[1];
}
</code>```

And I use the exact same code for Button B.

ContentLicense: CC BY-SA 3.0

Body:
I've been searching around for days but can't find what the problem can be. I want to know my current position when I'm clicking button A, and also know my position when I'm clicking button B. Problem is this, when I click B it seems to work fine, but not in A. I use the exact same code on both of them, but in some way it just wont work for A.

Here is my GetGPSLocation code
`

package com.example.eandl.gps;

import android.Manifest;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.location.LocationListener;
import android.location.LocationManager;
import android.provider.Settings;
import android.support.v4.app.ActivityCompat;
import android.util.Log;
import android.view.View;
import android.widget.Toast;

public class GetGPSLocation {
    private Context context;
    private static double lat;
    private static double lang;

    public GetGPSLocation(Context context){
        this.context = context;
        this.lat = 0.0;
        this.lang = 0.0;
    }

    public void setLat(double lat) {
        this.lat = lat;
    }

    public void setLang(double lang) {
        this.lang = lang;
    }

    public Boolean displayGpsStatus() {
        final LocationManager manager = (LocationManager) context.getSystemService( Context.LOCATION_SERVICE );

        if ( !manager.isProviderEnabled( LocationManager.NETWORK_PROVIDER ) ) {
            return false;
        }else{
            return true;
        }
    }

    public double[] getLatLong(){
        double[] latLong = new double[2];
        if(displayGpsStatus()){

            LocationManager locationMangaer = (LocationManager)context.getSystemService(Context.LOCATION_SERVICE);
            LocationListener locationListener = new MyLocationListener(context, this);

            if (ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                // TODO: Consider calling
                //    ActivityCompat#requestPermissions
                // here to request the missing permissions, and then overriding
                //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
                //                                          int[] grantResults)
                // to handle the case where the user grants the permission. See the documentation
                // for ActivityCompat#requestPermissions for more details.
                ActivityCompat.requestPermissions((Activity)context,new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, 1);
            }
            if(checkLocationPermission()){
                locationMangaer.requestLocationUpdates(LocationManager
                        .NETWORK_PROVIDER, 0, 0, locationListener);
            }

            Log.d("findError", getLang() + "");
            latLong[0] = getLat();
            latLong[1] = getLang();

        }else{
            alertbox("Gps status", "Your Device's GPS is Disable");
        }

        return latLong;
    }

    public boolean checkLocationPermission()
    {
        String permission = "android.permission.ACCESS_FINE_LOCATION";
        int res = context.checkCallingOrSelfPermission(permission);

        return (res == PackageManager.PERMISSION_GRANTED);
    }

    protected void alertbox(String title, String mymessage) {
        AlertDialog.Builder builder = new AlertDialog.Builder(context);
        builder.setMessage(mymessage)
                .setCancelable(false)
                .setTitle(title)
                .setPositiveButton("Gps On",
                        new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int id) {
                                // finish the current activity
                                // AlertBoxAdvance.this.finish();
                                Intent myIntent = new Intent(
                                        Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                                context.startActivity(myIntent);
                                dialog.cancel();
                            }
                        })
                .setNegativeButton("Cancel",
                        new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int id) {
                                // cancel the dialog box
                                dialog.cancel();
                            }
                        });
        AlertDialog alert = builder.create();
        alert.show();
    }

}

`

And the Listiener

package com.example.eandl.gps;

import android.content.Context;
import android.content.pm.PackageManager;
import android.location.Location;
import android.location.LocationListener;
import android.os.Bundle;
import android.util.Log;
import android.widget.Toast;

public class MyLocationListener implements LocationListener {

    private Context context;
    private GetGPSLocation getGPSLocation;

    public MyLocationListener(Context context, GetGPSLocation getGPSLocation) {
        this.context = context;
        this.getGPSLocation = getGPSLocation;
    }

    @Override
    public void onLocationChanged(Location loc) {
        if(loc != null){
            getGPSLocation.setLat(loc.getLatitude());
            getGPSLocation.setLang(loc.getLongitude());
        }
    }

    @Override
    public void onProviderDisabled(String provider) {
        // TODO Auto-generated method stub
    }

    @Override
    public void onProviderEnabled(String provider) {
        // TODO Auto-generated method stub
    }

    @Override
    public void onStatusChanged(String provider,
                                int status, Bundle extras) {
        // TODO Auto-generated method stub
    }
}

The way I'm trying to call it is by new GetGPSLocation(context).getLatLong but as I said, sometimes it returns my position and sometimes 0.0

Thank you!

Body:
Alright so first I'm setting it up when I create my view like this

    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) {
    //Fixa vit med blå text
    myView = inflater.inflate(R.layout.fragment_signup, container, false);
    placements = new ArrayList<CheckBox>();
    GetPlacements getPlacements = new GetPlacements(this);
    getPlacements.execute();

    getGPSLocation = new GetGPSLocation(myView.getContext());
    getGPSLocation.getLatLong();

Then this is the onclicklistener on the button A

                getGPSLocation.getLatLong();
                DatabasSender databasSender = new DatabasSender(myView.getContext());
                User user = new User(name.getText().toString(), email.getText().toString(), 0);
                user.setSignup(true);
                user.setEdu(edu.getText().toString());
                user.setPhone(phone.getText().toString());
                user.setPlacements(places);
                databasSender.execute(user);

That goes to my databassender that uses a AsyncTask

public DatabasSender(Context context) {
    this.context = context;
    getGPSLocation = new GetGPSLocation(context);

}

@Override
protected void onPreExecute() {
    latLong = getGPSLocation.getLatLong();
}
@Override
protected Object doInBackground(Object[] objects) {
    urlPatten = "..../"+latLong[0]+"&"+latLong[1];
}

And I use the exact same code for Button B.


问:
URL Encode and Decode in ASP.NET Core
```<code>HttpContext.Current.Server.UrlEncode
</code>```

This does only work in .NET Framework. How can I encode or decode URI arguments in ASP.NET Core?

答:
For ASP.NET Core 2.0+ just add System.Net namespace - WebUtility class is shipped as part of System.Runtime.Extensions nuget package, that is referenced by default in ASP.NET Core project.

For the previous version add Microsoft.AspNetCore.WebUtilities nuget package.

Then the WebUtility class will be available for you:

```<code>public static class WebUtility
{
    public static string UrlDecode(string encodedValue);
    public static string UrlEncode(string value);
}
</code>```

ContentLicense: CC BY-SA 4.0

Title: URL Encode and Decode in ASP.NET Core

Body:
HttpContext.Current.Server.UrlEncode

This does only work in .NET Framework. How can I encode or decode URI arguments in ASP.NET Core?

Body:
For ASP.NET Core 2.0+ just add System.Net namespace - WebUtility class is shipped as part of System.Runtime.Extensions nuget package, that is referenced by default in ASP.NET Core project.

For the previous version add Microsoft.AspNetCore.WebUtilities nuget package.

Then the WebUtility class will be available for you:

public static class WebUtility
{
    public static string UrlDecode(string encodedValue);
    public static string UrlEncode(string value);
}


问:
IOException when Uploading Videos to YouTube via Java API
I have been attempting to upload videos to YouTube via the JavaAPI using Direct Uploading.  I have been having a problem when I call the insert() method, I get a IOException with the error message

"Error writing request body to the server"

I have verified that the File object I am creating is correct as well as all the details in my VideoEntry object.  I have been using Fiddler to monitor the activity from my machine and no request is made to the upload API so the problem is not there.  Here is a summary of the code I am using:

```<code>VideoEntry newVideo = new VideoEntry();
//Defined video properties such as title and description here.
MediaFileSource ms = new MediaFileSource(videoFile, "video/flv");
newVideo.setMediaSource(ms);
VideoEntry createdEntry = settings.insert(new URL(apiUrl), newVideo);
</code>```

The IOException is thrown on the insert call (settings is my YouTubeService instance) and the API URL appears to be correct.

Prior to this I have succeeded in uploading this video using the C# API so I know the video file is valid.

--Update
This is the apiURL value:

http://uploads.gdata.youtube.com/feeds/api/users/default/uploads

答:
Make certain that videoFile actually points to the correct local file.  The File(String) constructor won't verify that it actually exists.  The MediaFileSource constructor and VideoEntry.setMediaSource() method also never check that the file is valid.  The error message "Error writing request body to the server" sounds like the insert method can not find the body of the message it is trying to send.

```<code>File videoFile = new File("...");
if (videoFile.exists() == false) {
    System.err.println("FAIL");
}
</code>```

to test if the file exists.

ContentLicense: CC BY-SA 2.5

Body:
I have been attempting to upload videos to YouTube via the JavaAPI using Direct Uploading.  I have been having a problem when I call the insert() method, I get a IOException with the error message

"Error writing request body to the server"

I have verified that the File object I am creating is correct as well as all the details in my VideoEntry object.  I have been using Fiddler to monitor the activity from my machine and no request is made to the upload API so the problem is not there.  Here is a summary of the code I am using:

VideoEntry newVideo = new VideoEntry();
//Defined video properties such as title and description here.
MediaFileSource ms = new MediaFileSource(videoFile, "video/flv");
newVideo.setMediaSource(ms);
VideoEntry createdEntry = settings.insert(new URL(apiUrl), newVideo);

The IOException is thrown on the insert call (settings is my YouTubeService instance) and the API URL appears to be correct.

Prior to this I have succeeded in uploading this video using the C# API so I know the video file is valid.

--Update
This is the apiURL value:

http://uploads.gdata.youtube.com/feeds/api/users/default/uploads

Body:
Make certain that videoFile actually points to the correct local file.  The File(String) constructor won't verify that it actually exists.  The MediaFileSource constructor and VideoEntry.setMediaSource() method also never check that the file is valid.  The error message "Error writing request body to the server" sounds like the insert method can not find the body of the message it is trying to send.

File videoFile = new File("...");
if (videoFile.exists() == false) {
    System.err.println("FAIL");
}

to test if the file exists.


问:
Swift: Recursively cycle through all subviews to find a specific class and append to an array
Having a devil of a time trying to figure this out. I asked a similar question here: Swift: Get all subviews of a specific type and add to an array

While this works, I realized there are many subviews and sub-sub views, and so I need a function that starts at the main UIView, cycles through all the subviews (and their subviews until there aren't any left) and adds it to an array for a custom button class which I have named CheckCircle.

Essentially I'd like to end up with an array of CheckCircles which constitute all the CheckCircles added to that view programmatically.

Any ideas? Here's what I've been working on. It doesn't seem to be appending any Checkcircles to the array:

```<code>    func getSubviewsOfView(v:UIView) -> [CheckCircle] {
        var circleArray = [CheckCircle]()
        // Get the subviews of the view

        var subviews = v.subviews

        if subviews.count == 0 {
            return circleArray
        }

        for subview : AnyObject in subviews{
  if let viewToAppend = subview as? CheckCircle {
        circleArray.append(viewToAppend as CheckCircle)
      }
            getSubviewsOfView(subview as! UIView)
        }
        return circleArray
    }
</code>```

答:
My approach with swift 3 and generics!

```<code>private func getSubviewsOf<T: UIView>(view: UIView) -> [T] {
    var subviews = [T]()

    for subview in view.subviews {
        subviews += getSubviewsOf(view: subview) as [T]

        if let subview = subview as? T {
            subviews.append(subview)
        }
    }

    return subviews
}
</code>```

To fetch all UILabel's in a view hierarchy, just do this:

```<code>let allLabels: [UILabel] = getSubviewsOf(view: theView)
</code>```

Body:
Having a devil of a time trying to figure this out. I asked a similar question here: Swift: Get all subviews of a specific type and add to an array

While this works, I realized there are many subviews and sub-sub views, and so I need a function that starts at the main UIView, cycles through all the subviews (and their subviews until there aren't any left) and adds it to an array for a custom button class which I have named CheckCircle.

Essentially I'd like to end up with an array of CheckCircles which constitute all the CheckCircles added to that view programmatically.

Any ideas? Here's what I've been working on. It doesn't seem to be appending any Checkcircles to the array:

    func getSubviewsOfView(v:UIView) -> [CheckCircle] {
        var circleArray = [CheckCircle]()
        // Get the subviews of the view

        var subviews = v.subviews

        if subviews.count == 0 {
            return circleArray
        }

        for subview : AnyObject in subviews{
  if let viewToAppend = subview as? CheckCircle {
        circleArray.append(viewToAppend as CheckCircle)
      }
            getSubviewsOfView(subview as! UIView)
        }
        return circleArray
    }

Body:
My approach with swift 3 and generics!

private func getSubviewsOf<T: UIView>(view: UIView) -> [T] {
    var subviews = [T]()

    for subview in view.subviews {
        subviews += getSubviewsOf(view: subview) as [T]

        if let subview = subview as? T {
            subviews.append(subview)
        }
    }

    return subviews
}

To fetch all UILabel's in a view hierarchy, just do this:

let allLabels: [UILabel] = getSubviewsOf(view: theView)


问:
Get Reference of Dialog in onClick
I am creating a Custom Dialog on click of a button in my activity. There is button in the Dialog and I have set it like this:

```<code> Button buttonTakePicture = (Button)dialog.findViewById(R.id.buttonTakePicture);
 buttonTakePicture.setOnClickListener(this);
</code>```

My Activity is implementing the onClickListener, and the overridden onClick method looks like this:

```<code>@Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.buttonTakePicture:
                Dialog dialog = //Get the dialog somehow from view;
                if (dialog != null) {
                    dialog.dismiss();
                }
                takePicture();
                break;
        }
    }
</code>```

I am struggling to get the Dialog Reference here. I have tried (Dialog)view.getParent() as well as (Dialog)view.getParent.getParent(), but they are not the Dialogs.

I don't want to have a Dialog Field in my Activity unless it is the only way.

Any help would be appreciated. Thanks in advance.

答:
I have solution for this ,

```<code>Button buttonTakePicture = (Button)dialog.findViewById(R.id.buttonTakePicture);
        buttonTakePicture.setTag(dialog);
        buttonTakePicture.setOnClickListener(this);
</code>```

and get the Dialog like this,

```<code>@Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.buttonTakePicture:
                Dialog dialog = (Dialog) view.getTag();
                if (dialog != null) {
                    view.setTag(null);
                    dialog.dismiss();
                }
                takePicture();
                break;
        }
    }
</code>```

Title: Get Reference of Dialog in onClick

Body:
I am creating a Custom Dialog on click of a button in my activity. There is button in the Dialog and I have set it like this:

 Button buttonTakePicture = (Button)dialog.findViewById(R.id.buttonTakePicture);
 buttonTakePicture.setOnClickListener(this);

My Activity is implementing the onClickListener, and the overridden onClick method looks like this:

@Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.buttonTakePicture:
                Dialog dialog = //Get the dialog somehow from view;
                if (dialog != null) {
                    dialog.dismiss();
                }
                takePicture();
                break;
        }
    }

I am struggling to get the Dialog Reference here. I have tried (Dialog)view.getParent() as well as (Dialog)view.getParent.getParent(), but they are not the Dialogs.

I don't want to have a Dialog Field in my Activity unless it is the only way.

Any help would be appreciated. Thanks in advance.

Body:
I have solution for this ,

Button buttonTakePicture = (Button)dialog.findViewById(R.id.buttonTakePicture);
        buttonTakePicture.setTag(dialog);
        buttonTakePicture.setOnClickListener(this);

and get the Dialog like this,

@Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.buttonTakePicture:
                Dialog dialog = (Dialog) view.getTag();
                if (dialog != null) {
                    view.setTag(null);
                    dialog.dismiss();
                }
                takePicture();
                break;
        }
    }


问:
Run spring boot with jdk9 using jigsaw modules
What's wrong with this application. I thought the mix of classpath jars and module jars are valid. For all jars not having an explicit module-info become an automatic module? When I delete my module-info.java it works. Because IDEA using the classpath for this case.

Java(TM) SE Runtime Environment (build 9+176)

IntelliJ IDEA 2017.1.4

module-info.java

```<code>module test {
    requires spring.boot.autoconfigure;
    requires spring.boot;
}
</code>```

App.java

```<code>package com.foo.test;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class App {

    public static void main(String[] args) {
        SpringApplication.run(App.class, args);
    }
}
</code>```

pom.xml

```<code><project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.foo.test</groupId>
    <artifactId>test</artifactId>
    <version>1.0-SNAPSHOT</version>
    <packaging>jar</packaging>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.0.0.M2</version>
    </parent>

    <name>test</name>
    <url>http://maven.apache.org</url>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <maven.compiler.source>1.9</maven.compiler.source>
        <maven.compiler.target>1.9</maven.compiler.target>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>3.8.1</version>
            <scope>test</scope>
        </dependency>
    </dependencies>
    <repositories>
        <repository>
            <id>spring-milestones</id>
            <name>Spring Milestones</name>
            <url>https://repo.spring.io/libs-milestone</url>
            <snapshots>
                <enabled>false</enabled>
            </snapshots>
        </repository>
    </repositories>
</project>
</code>```

Exception in thread "main" java.lang.IllegalArgumentException: Cannot
  instantiate interface
  org.springframework.context.ApplicationContextInitializer :
  org.springframework.boot.context.ConfigurationWarningsApplicationContextInitializer
    at
  spring.boot@2.0.0.M2/org.springframework.boot.SpringApplication.createSpringFactoriesInstances(SpringApplication.java:439)
    at
  spring.boot@2.0.0.M2/org.springframework.boot.SpringApplication.getSpringFactoriesInstances(SpringApplication.java:418)
    at
  spring.boot@2.0.0.M2/org.springframework.boot.SpringApplication.getSpringFactoriesInstances(SpringApplication.java:409)
    at
  spring.boot@2.0.0.M2/org.springframework.boot.SpringApplication.(SpringApplication.java:266)
    at
  spring.boot@2.0.0.M2/org.springframework.boot.SpringApplication.(SpringApplication.java:247)
    at
  spring.boot@2.0.0.M2/org.springframework.boot.SpringApplication.run(SpringApplication.java:1245)
    at
  spring.boot@2.0.0.M2/org.springframework.boot.SpringApplication.run(SpringApplication.java:1233)
    at test/com.foo.test.App.main(App.java:10) Caused by:
  java.lang.NoClassDefFoundError: java/sql/SQLException     at
  spring.beans@5.0.0.RC2/org.springframework.beans.BeanUtils.instantiateClass(BeanUtils.java:145)
    at
  spring.boot@2.0.0.M2/org.springframework.boot.SpringApplication.createSpringFactoriesInstances(SpringApplication.java:435)
    ... 7 more Caused by: java.lang.ClassNotFoundException:
  java.sql.SQLException     at
  java.base/jdk.internal.loader.BuiltinClassLoader.loadClass(BuiltinClassLoader.java:582)
    at
  java.base/jdk.internal.loader.ClassLoaders$AppClassLoader.loadClass(ClassLoaders.java:185)
    at java.base/java.lang.ClassLoader.loadClass(ClassLoader.java:496)
    ... 9 more

答:
finally, I got it... my module-info have to look like this:

```<code>module test {
    requires java.sql; // my real problem solved with this
    requires spring.boot.autoconfigure;
    requires spring.boot;
    exports com.foo.test; // subsequent error 1: beeing accessible for some spring modules
    opens com.foo.test to spring.core; // subsequent error 2: beeing accessible for spring.core in a deep reflection way
}
</code>```

Can someone explain why I have to requires java.sql; inside my own module when I don't use it?

Body:
What's wrong with this application. I thought the mix of classpath jars and module jars are valid. For all jars not having an explicit module-info become an automatic module? When I delete my module-info.java it works. Because IDEA using the classpath for this case.

Java(TM) SE Runtime Environment (build 9+176)

IntelliJ IDEA 2017.1.4

module-info.java

module test {
    requires spring.boot.autoconfigure;
    requires spring.boot;
}

App.java

package com.foo.test;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class App {

    public static void main(String[] args) {
        SpringApplication.run(App.class, args);
    }
}

pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.foo.test</groupId>
    <artifactId>test</artifactId>
    <version>1.0-SNAPSHOT</version>
    <packaging>jar</packaging>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.0.0.M2</version>
    </parent>

    <name>test</name>
    <url>http://maven.apache.org</url>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <maven.compiler.source>1.9</maven.compiler.source>
        <maven.compiler.target>1.9</maven.compiler.target>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>3.8.1</version>
            <scope>test</scope>
        </dependency>
    </dependencies>
    <repositories>
        <repository>
            <id>spring-milestones</id>
            <name>Spring Milestones</name>
            <url>https://repo.spring.io/libs-milestone</url>
            <snapshots>
                <enabled>false</enabled>
            </snapshots>
        </repository>
    </repositories>
</project>

Exception in thread "main" java.lang.IllegalArgumentException: Cannot
  instantiate interface
  org.springframework.context.ApplicationContextInitializer :
  org.springframework.boot.context.ConfigurationWarningsApplicationContextInitializer
    at
  spring.boot@2.0.0.M2/org.springframework.boot.SpringApplication.createSpringFactoriesInstances(SpringApplication.java:439)
    at
  spring.boot@2.0.0.M2/org.springframework.boot.SpringApplication.getSpringFactoriesInstances(SpringApplication.java:418)
    at
  spring.boot@2.0.0.M2/org.springframework.boot.SpringApplication.getSpringFactoriesInstances(SpringApplication.java:409)
    at
  spring.boot@2.0.0.M2/org.springframework.boot.SpringApplication.(SpringApplication.java:266)
    at
  spring.boot@2.0.0.M2/org.springframework.boot.SpringApplication.(SpringApplication.java:247)
    at
  spring.boot@2.0.0.M2/org.springframework.boot.SpringApplication.run(SpringApplication.java:1245)
    at
  spring.boot@2.0.0.M2/org.springframework.boot.SpringApplication.run(SpringApplication.java:1233)
    at test/com.foo.test.App.main(App.java:10) Caused by:
  java.lang.NoClassDefFoundError: java/sql/SQLException     at
  spring.beans@5.0.0.RC2/org.springframework.beans.BeanUtils.instantiateClass(BeanUtils.java:145)
    at
  spring.boot@2.0.0.M2/org.springframework.boot.SpringApplication.createSpringFactoriesInstances(SpringApplication.java:435)
    ... 7 more Caused by: java.lang.ClassNotFoundException:
  java.sql.SQLException     at
  java.base/jdk.internal.loader.BuiltinClassLoader.loadClass(BuiltinClassLoader.java:582)
    at
  java.base/jdk.internal.loader.ClassLoaders$AppClassLoader.loadClass(ClassLoaders.java:185)
    at java.base/java.lang.ClassLoader.loadClass(ClassLoader.java:496)
    ... 9 more

Body:
finally, I got it... my module-info have to look like this:

module test {
    requires java.sql; // my real problem solved with this
    requires spring.boot.autoconfigure;
    requires spring.boot;
    exports com.foo.test; // subsequent error 1: beeing accessible for some spring modules
    opens com.foo.test to spring.core; // subsequent error 2: beeing accessible for spring.core in a deep reflection way
}

Can someone explain why I have to requires java.sql; inside my own module when I don't use it?


问:
Leaky bucket problem help?
I'm trying to review for my final and I'm going over example problems given to me by my professor. Can anyone explain to me the concept of how leaky bucket works. Also Here's a review problem my professor gave to me about leaky buckets.

A leaky bucket is at the host network interface. The data rate in the network is 2 Mbyte/s and the data rate from the application to the bucket is 2m5 Mbyte/s

A.) Suppose the host has 250 Mbytes to send onto the network and it sends the data in one burst. What should the minimum capacity of the bucket (in byte) in order that no data is lost?

B.) Suppose the capacity of the bucket is 100M bytes. What is the longest burst time from the host in order that no data is lost?

答:
Leaky bucket symbolizes a bucket with a small hole allowing water (data) to come out at the bottom. Since the top of the bucket has a greater aperture than the bottom, you can put water in it faster that it goes out (so the bucket fills up).

Basically, it represents a buffer on a network between 2 links with different rates.

Problem A

We can compute that sending the data will take 250Mbyte / (2,5Mbyte / s) = 100 s.

During that 100 s, the bucket will have retransmitted (leaked) 100s * 2Mbyte/s = 200Mbytes

So the bucket will need a minimum capacity of 250MB - 200MB = 50MB in order not to lose any data

Problem B

Since the difference between the 2 data rates is 2.5MB/s - 2.0MB/s = 0.5MB/s, it means the bucked fills up by 0.5MB/s (when both links transmit at full capacity).

You can then calculate that the 100MB capacity will be filled after a burst of 100MB / 0.5MB/s = 200s = 3m 20s

Title: Leaky bucket problem help?


问:
Android Studio - automatic gradle sync at startup
Yesterday I updated the Android Studio to 2.2 (from 2.1.3). Since that the Android Studio always start gradle sync at startup on every opened projects. I found this question and I tried Mick's suggestion, but unfortunately that did'nt worked for me.

If I open Android Studio, and I wait until load my projects, sync gradle and then I close Android Studio (without any change on my projects), and after that, I open it again, AS also do the same as before (run a gradle sync again senselessly).

I think, this is not a serious problem, but it's pretty weird, because it sync senselessly (otherwise I start gradle sync manually if I need to, but AS start it on every startup senselessly), and I need to wait little more to start coding (a little waste of time and energy).

答:
Maybe this is what you want.

gradle --stop


问:
Sending and receiving data in parallel on socket android
I am currently working on file transfer between two mobile devices. For this, i am using socket communication. On socket using DataInput and Data Output Stream, i am able to get approximately 6 MB/s speed. But as per my use case user can select all images, videos, apk's, documents to transfer. so let's say user selected 2GB data to transfer with my app he has to wait for more than 6 minutes. so I have done some modifications.
1] On receiver side I opened up 5 ports (one for image, one for video and so on)
2] Sender will send appropriate files on corresponding ports.
3] I am sending all the files at a time parallelly using async task and receiver is receiving data in 5 different thread.

But the problem is speed still is same for 2GB it's approximately 6MB/s.
So my question is:
1] Will multiport socket increase performance?
2] if I am doing something wrong, then how can I send data parallelly on different ports on a socket?

答:
Android devices cannot go more than 7mb/s as per my experience. Use some data monitor start file transfer on lan. You will notice its maximum speed is approximately 7mb.
Sorry i cannot comment yet so added as answer.</p>


问:
How to deserialise a JSON where the corresponding Haskell type is available during runtime as a value?
I'm trying to implement a port of DelayedJob (from the Rails world) in Haskell.

Here's the typeclass I have which represents a DelayedJob

```<code>class (FromJSON j, ToJSON j, FromJSON r, ToJSON r) => DelayedJob j r | j -> r where
  serialise :: j -> Value
  serialise = toJSON

  deserialise :: Value -> Either String j
  deserialise = parseEither parseJSON

  runJob :: j -> AppM r
</code>```

Here's how I plan to use it:

```<code>createJob :: (DelayedJob j r) => j -> AppM JobId
</code>```

I'm getting stuck with writing a fairly general invokeJob function which will read a row from the jobs table, look at the jobs.jobtype column and invoke the correct version of the runJob version (i.e. the runJob function belonging to the correct type-class instance).

I have the following, but it is full of boilerplate:

```<code>data JobType = SyncContacts | SendEmail | SendSms deriving (Eq, Show, Generic)

invokeJob :: JobId -> AppM ()
invokeJob jid = do
  job <- fetchJob jid
  case (job ^. jobtype) of
     SyncContacts -> case (deserialise (job ^. jobdata) :: Either String SynContactsJob) of
       Left e -> error e
       Right j -> storeJobResult jid $ runAppM j
     SendEmail -> case (deserialise (job ^. jobdata) :: Either String SendEmailJob) of
       Left e -> error e
       Right j -> storeJobResult jid $ runAppM j
     SendSms -> case (deserialise (job ^. jobdata) :: Either String SendSms) of
       Left e -> error e
       Right j -> storeJobResult jid $ runAppM j
</code>```

Essentially, is there a way to constrain the concrete type of the deserialise function dynamically during runtime without having to write so much boilerplate?

答:
I wonder if something like this could work. I don't know the framework you are working with.

```<code>let go :: forall jobtype . Job -> JobID -> ....
    go job jid =
       case deserialise (job ^. jobdata) :: Either String jobtype of
          Left e -> error e
          Right j -> storeJobResult jid $ runAppM j
case (job ^. jobtype) of
     SyncContacts -> go @ SynContactsJob job jid
     SendEmail    -> go @ SendEmail job jid
     ...
</code>```

Otherwise, I'd try to see if singletons can help. Proxies could also be used if you don't want to enable ambiguous types & type applications.

Body:
I'm trying to implement a port of DelayedJob (from the Rails world) in Haskell.

Here's the typeclass I have which represents a DelayedJob

class (FromJSON j, ToJSON j, FromJSON r, ToJSON r) => DelayedJob j r | j -> r where
  serialise :: j -> Value
  serialise = toJSON

  deserialise :: Value -> Either String j
  deserialise = parseEither parseJSON

  runJob :: j -> AppM r

Here's how I plan to use it:

createJob :: (DelayedJob j r) => j -> AppM JobId

I'm getting stuck with writing a fairly general invokeJob function which will read a row from the jobs table, look at the jobs.jobtype column and invoke the correct version of the runJob version (i.e. the runJob function belonging to the correct type-class instance).

I have the following, but it is full of boilerplate:

data JobType = SyncContacts | SendEmail | SendSms deriving (Eq, Show, Generic)

invokeJob :: JobId -> AppM ()
invokeJob jid = do
  job <- fetchJob jid
  case (job ^. jobtype) of
     SyncContacts -> case (deserialise (job ^. jobdata) :: Either String SynContactsJob) of
       Left e -> error e
       Right j -> storeJobResult jid $ runAppM j
     SendEmail -> case (deserialise (job ^. jobdata) :: Either String SendEmailJob) of
       Left e -> error e
       Right j -> storeJobResult jid $ runAppM j
     SendSms -> case (deserialise (job ^. jobdata) :: Either String SendSms) of
       Left e -> error e
       Right j -> storeJobResult jid $ runAppM j

Essentially, is there a way to constrain the concrete type of the deserialise function dynamically during runtime without having to write so much boilerplate?

Body:
I wonder if something like this could work. I don't know the framework you are working with.

let go :: forall jobtype . Job -> JobID -> ....
    go job jid =
       case deserialise (job ^. jobdata) :: Either String jobtype of
          Left e -> error e
          Right j -> storeJobResult jid $ runAppM j
case (job ^. jobtype) of
     SyncContacts -> go @ SynContactsJob job jid
     SendEmail    -> go @ SendEmail job jid
     ...

Otherwise, I'd try to see if singletons can help. Proxies could also be used if you don't want to enable ambiguous types & type applications.


问:
how to write a code in vba so each time a function call its create a different sheet in a workbook
```<code> Public Sub text1(st As String)
    Dim oXL As Object        ' Excel application
    Dim oBook As Object      ' Excel workbook
    Dim oSheet As Object     ' Excel Worksheet
    Dim i As Integer

    'Start Excel and create a new workbook
    Set oXL = CreateObject("Excel.application")
    Set oBook = oXL.Workbooks.Open("E:\karan.xlsx")
    Set ws = oBook.Sheets.Add
    oBook.activesheet.Name = st
    ws.Activate
</code>```

答:
To what I understand you, you would like to add a workbook when your function is called. In such a case you could use this:

```<code>Sub AddWorkbook()
    Sheets.Add After:=Sheets(Sheets.Count)
End Sub
</code>```

If you additionally want to add a name:

```<code>Private Sub AddWorkbookWithName(workbookName As String)
    Sheets.Add After:=Sheets(Sheets.Count)
    Sheets(Sheets.Count).Select
    Sheets(Sheets.Count).Name = workbookName
End Sub

Sub AddWorkbook()
    AddWorkbookWithName ("MyWorkbookName")
End Sub
</code>```

Body:
To what I understand you, you would like to add a workbook when your function is called. In such a case you could use this:

Sub AddWorkbook()
    Sheets.Add After:=Sheets(Sheets.Count)
End Sub

If you additionally want to add a name:

Private Sub AddWorkbookWithName(workbookName As String)
    Sheets.Add After:=Sheets(Sheets.Count)
    Sheets(Sheets.Count).Select
    Sheets(Sheets.Count).Name = workbookName
End Sub

Sub AddWorkbook()
    AddWorkbookWithName ("MyWorkbookName")
End Sub


问:
Get UITextField Y coordinate on UIView level?
Currently I have a UITextField in a custom cell and I want to get the Y coordinate of that UITextField on the level of the View Controller's view (UIView). Currently I am trying to do something like this:

```<code>if (thetextField.superview.superview.superview.frame.origin.y >= keyboardY) {

}
</code>```

But it seems that the Y coordinate is always 0 when it is in fact not. Is there any way to achieve this?

I am doing this because I want to detect whether the UIKeyboard is blocking the UITextField on the UIView level so that I can re-arrange my cells accordingly.

Thanks!

答:
Swift 3 version:

```<code>thetextField.convert(thetextField.frame.origin, to:self.view)
</code>```

It returns a CGPoint, so you can access "x" or "y" properties.

Body:
Currently I have a UITextField in a custom cell and I want to get the Y coordinate of that UITextField on the level of the View Controller's view (UIView). Currently I am trying to do something like this:

if (thetextField.superview.superview.superview.frame.origin.y >= keyboardY) {

}

But it seems that the Y coordinate is always 0 when it is in fact not. Is there any way to achieve this?

I am doing this because I want to detect whether the UIKeyboard is blocking the UITextField on the UIView level so that I can re-arrange my cells accordingly.

Thanks!

Body:
Swift 3 version:

thetextField.convert(thetextField.frame.origin, to:self.view)

It returns a CGPoint, so you can access "x" or "y" properties.


问:
Doing explicit replays in axon 3.x
I have been trying out axon recently and read lots of stuff. From what I understand, the concept of event sourcing says that system state is rebuilt from the event store, while CQRS updates a view model that can be queried with the command side side is not queryable.

I will like to implement rebuilding of state myself each time the UI requests for some information. I've implemented the event processor and seen its replay capabilities. However I can't seem to find any evidence that axon allows for replays triggered on user demand. Therefore I'm asking here if its possible to personally trigger a replay to build a DAO required by the UI or axon only supports the CQRS way of doing it.

When axon does a replay (when token is deleted), does it read from the snapshot table (if implemented), then from the event table or does it always start from the beginning of time?

答:
Dropping the token manually is currently the way to go if you want your query side to be rebuilt.
So, if you'd like to trigger a replay, you'd have to add a component which does that for you.
This might be a tricky process as well, since you'd probably not want any other parties trying to access  your view(s) while they're rebuilding.
Take note that for this you do need to put your event handling components in a TrackingEventProcessor, otherwise it will have no recollection of how much of the events it has handled or not in the form of a TrackingToken.

The snapshot table is meant for your aggregates to ease the loading process. When you've set up axon to use the (Caching)EventSourcingRepository, it will first load an aggregate based on a snapshot and then source the remaining events.
So, to answer your second question: when you drop the token, it will read from the domain event entry table from the beginning of time.

Hope this helps!

 Update

For those looking for replay support in Axon Framework, it is recommended to look at this page of the Reference Guide. It describes the replay support constructed for Streaming Event Processsors (like the TrackingEventProcessor).

Title: Doing explicit replays in axon 3.x


问:
How to create Android UI Test for Android App Architecture ViewModels?
I have been working with the new Android App Architecture Components. The documentation on testing leaves a lot to the imagination. I have looked at android architecture components testing part of the documentation it was very vague as worded below.

User Interface & Interactions: This will be the only time you need an Android UI Instrumentation test. The best way to test UI code is to create an Espresso test. You can create the fragment and provide it a mock ViewModel. Since the fragment only talks to the ViewModel, mocking it will be sufficient to fully test this UI

How do you go about writing a Espresso test by passing in a mock of a ViewModel to the fragment? I have also looked at the sample apps provided by Google they were also not very helpful.

Suppose this is my example fragment class.

```<code>public class ExampleFragment extends LifecycleFragment {
    private ExampleViewModel mViewModel;
    @Inject ExampleViewModelFactory mViewModelFactory;

    public ExampleFragment() {
        // Required empty public constructor
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_example, container, false);
    }

    @Override
    public void onActivityCreated(@Nullable final Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);
    ExampleComponent component = DaggerExampleComponent.builder().build();
    component.inject(this);
    mViewModel = ViewModelProviders.of(this, mViewModelFactory).get(ExampleViewModel.class);
    mViewModel.getExampleString().observe(this, exampleString -> {
       //Update UI
        });
    }
}
</code>```

答:
There are two main approaches AFAIK about providing mock injected components.
The first one is the one implemented in google examples, which is to provide a mock viewmodel implementation as a different flavour (for example in your tests).

The other one is described in my blogpost here in the "testing the view" section, where the DaggerExampleComponent is provided by the Application object, and you override the application object in the espresso test runner having one that provides the fake ViewModel.

Full working example here

Body:
I have been working with the new Android App Architecture Components. The documentation on testing leaves a lot to the imagination. I have looked at android architecture components testing part of the documentation it was very vague as worded below.

User Interface & Interactions: This will be the only time you need an Android UI Instrumentation test. The best way to test UI code is to create an Espresso test. You can create the fragment and provide it a mock ViewModel. Since the fragment only talks to the ViewModel, mocking it will be sufficient to fully test this UI

How do you go about writing a Espresso test by passing in a mock of a ViewModel to the fragment? I have also looked at the sample apps provided by Google they were also not very helpful.

Suppose this is my example fragment class.

public class ExampleFragment extends LifecycleFragment {
    private ExampleViewModel mViewModel;
    @Inject ExampleViewModelFactory mViewModelFactory;

    public ExampleFragment() {
        // Required empty public constructor
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_example, container, false);
    }

    @Override
    public void onActivityCreated(@Nullable final Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);
    ExampleComponent component = DaggerExampleComponent.builder().build();
    component.inject(this);
    mViewModel = ViewModelProviders.of(this, mViewModelFactory).get(ExampleViewModel.class);
    mViewModel.getExampleString().observe(this, exampleString -> {
       //Update UI
        });
    }
}


问:
Regular expession for domain name
Can someone please tell regular expression for this:

```<code>anytext.com
anytext.org
anytext.net
anytext.mil
anytext.gov
</code>```

The requirement is any text given except these domain names (org, net, com, gov, mit) should be invalid.

Cuurently I am giving this regular expression which is not working:

```<code>/^[\w-\.]+.(?com)(?org)(?mil)(?net)(?edu)(?gov)?$/
</code>```

答:
This should work for you:

var regexp = /^[A-Za-z0-9-\.]+\.(com|org|mil|net|gov)$/

console.log('anytext.com', regexp.test('anytext.com'))```

Title: Regular expession for domain name

Body:
Can someone please tell regular expression for this:

anytext.com
anytext.org
anytext.net
anytext.mil
anytext.gov

The requirement is any text given except these domain names (org, net, com, gov, mit) should be invalid.

Cuurently I am giving this regular expression which is not working:

/^[\w-\.]+.(?com)(?org)(?mil)(?net)(?edu)(?gov)?$/


问:
SVN checkout ignore folder
Can I ignore a folder on svn checkout? I need to ignore DOCs folder on checkout at my build server.

edit: Ignore externals isn't an option. I have some externals that I need.

答:
I have recently resolved the same task.
The idea is to get the immediate list of folder/files under the repository exclude the entries you need, then check out the remaining folders and update the immediate files if any.
Here is the solution:

```<code>    # Path to the svn repository to be checked out
rpath=https://svn-repo.company.com/sw/trunk/ && \
    # This files are to be excluded (folders are ending with '/')
    # this is a regex pattern with OR ('|') between enties to be excluded
excludep='docs_folder/tests_folder/|huge_folder/|file1|file2' && \
    # Get list of the files/folders right under the repository path
filtered=`svn ls $rpath | egrep -v $excludep` && \
    # Get list of files out of filtered - they need to be 'uped'
files=`echo $filtered | sed 's| |\n|g' | egrep '^.*[^/]$'` && \
    # Get list of folders out of filtered - they need to be 'coed'
folders=`echo $filtered | sed 's| |\n|g' | egrep '^.*[/]$'` && \
    # Initial nonrecursive checkout of repository - just empty
    # to the current (./) working directory
svn co $rpath ./ --depth empty && \
    # Update the files
svn up $files &&\
    # Check out the all other folders finally.
svn co `echo $folders | sed "s|\<|$rpath|g"`
</code>```

Change to source working directory. Copy the commands. Paste. Change appropriate URL and exclude pattern. Run the command.

Thanks,

OwnerDisplayName: Zote

Title: SVN checkout ignore folder

Body:
I have recently resolved the same task.
The idea is to get the immediate list of folder/files under the repository exclude the entries you need, then check out the remaining folders and update the immediate files if any.
Here is the solution:

    # Path to the svn repository to be checked out
rpath=https://svn-repo.company.com/sw/trunk/ && \
    # This files are to be excluded (folders are ending with '/')
    # this is a regex pattern with OR ('|') between enties to be excluded
excludep='docs_folder/tests_folder/|huge_folder/|file1|file2' && \
    # Get list of the files/folders right under the repository path
filtered=`svn ls $rpath | egrep -v $excludep` && \
    # Get list of files out of filtered - they need to be 'uped'
files=`echo $filtered | sed 's| |\n|g' | egrep '^.*[^/]$'` && \
    # Get list of folders out of filtered - they need to be 'coed'
folders=`echo $filtered | sed 's| |\n|g' | egrep '^.*[/]$'` && \
    # Initial nonrecursive checkout of repository - just empty
    # to the current (./) working directory
svn co $rpath ./ --depth empty && \
    # Update the files
svn up $files &&\
    # Check out the all other folders finally.
svn co `echo $folders | sed "s|\<|$rpath|g"`

Change to source working directory. Copy the commands. Paste. Change appropriate URL and exclude pattern. Run the command.

Thanks,


问:
Export the tables from pdf to excel?
How do i export only the table contents to excel file through C# programming?
I am currently extracting all the contents from PDFs using PDFNET SDK ,but couldn't able to read the table as a tabular structure</p>

答:
Using bytescount PDF Extractor SDK we can be able to extract the whole page as below,

```<code>        CSVExtractor extractor = new CSVExtractor();
        extractor.RegistrationName = "demo";
        extractor.RegistrationKey = "demo";

        TableDetector tdetector = new TableDetector();
        tdetector.RegistrationKey = "demo";
        tdetector.RegistrationName = "demo";

            // Load the document
        extractor.LoadDocumentFromFile("C:\\sample.pdf");
        tdetector.LoadDocumentFromFile("C:\\sample.pdf");

           int pageCount = tdetector.GetPageCount();

            for (int i = 1; i <= pageCount; i++)
            {
                int j = 1;

                    do
                    {
                            extractor.SetExtractionArea(tdetector.GetPageRect_Left(i),
                            tdetector.GetPageRect_Top(i),
                            tdetector.GetPageRect_Width(i),
                            tdetector.GetPageRect_Height(i)
                        );

                        // and finally save the table into CSV file
                        extractor.SavePageCSVToFile(i, "C:\\page-" + i + "-table-" + j + ".csv");
                        j++;
                    } while (tdetector.FindNextTable()); // search next table
            }
</code>```

since it is an old post, hope it would help others.

Title: Export the tables from pdf to excel?

Body:
Using bytescount PDF Extractor SDK we can be able to extract the whole page as below,

        CSVExtractor extractor = new CSVExtractor();
        extractor.RegistrationName = "demo";
        extractor.RegistrationKey = "demo";

        TableDetector tdetector = new TableDetector();
        tdetector.RegistrationKey = "demo";
        tdetector.RegistrationName = "demo";

            // Load the document
        extractor.LoadDocumentFromFile("C:\\sample.pdf");
        tdetector.LoadDocumentFromFile("C:\\sample.pdf");

           int pageCount = tdetector.GetPageCount();

            for (int i = 1; i <= pageCount; i++)
            {
                int j = 1;

                    do
                    {
                            extractor.SetExtractionArea(tdetector.GetPageRect_Left(i),
                            tdetector.GetPageRect_Top(i),
                            tdetector.GetPageRect_Width(i),
                            tdetector.GetPageRect_Height(i)
                        );

                        // and finally save the table into CSV file
                        extractor.SavePageCSVToFile(i, "C:\\page-" + i + "-table-" + j + ".csv");
                        j++;
                    } while (tdetector.FindNextTable()); // search next table
            }

since it is an old post, hope it would help others.


问:
Rails Validate no White Space in User Name
I want to validate that a user name has no white/blank spaces for my Users.  Is there a built in validation that does this?  Or what is the best way to do this.  Seems like it would be a pretty common requirement.</p>

答:
You can use before_validation callback to strip whitespace

```<code>class User
  before_validation :strip_blanks

  protected

  def strip_blanks
    self.username = self.username.strip
  end
end
</code>```

Body:
You can use before_validation callback to strip whitespace

class User
  before_validation :strip_blanks

  protected

  def strip_blanks
    self.username = self.username.strip
  end
end


问:
Virtual Machine Setup and syncing project dependencies
Hi I am using vagrant to run a local linux environment on my windows OS.

The problem is, I am trying to run my python project on it but there are a whole lot of dependencies, including nltk, which takes a long time to download.

Other than manually re-downloading and installing all the dependencies onto the VM, is there a better way to sync my existing python libraries?

答:
You can download the package on your host machine, share the folder where you have the download and run the install in the VM from the shared directory.</p>

```<code>$ pip install mypackage --no-index --find-links file:///vagrant/share/package
</code>```

Body:
You can download the package on your host machine, share the folder where you have the download and run the install in the VM from the shared directory.

$ pip install mypackage --no-index --find-links file:///vagrant/share/package


问:
Swift: Get all subviews of a specific type and add to an array
I have a custom class of buttons in a UIView that I'd like to add to an array so that they're easily accessible. Is there a way to get all subviews of a specific class and add it to an array in Swift?</p>

答:
To do this recursively (I.e. fetching all subview's views aswell), you can use this generic function:

```<code>private func getSubviewsOf<T : UIView>(view:UIView) -> [T] {
    var subviews = [T]()

    for subview in view.subviews {
        subviews += getSubviewsOf(view: subview) as [T]

        if let subview = subview as? T {
            subviews.append(subview)
        }
    }

    return subviews
}
</code>```

To fetch all UILabel's in a view hierarchy, just do this:

```<code>let allLabels : [UILabel] = getSubviewsOf(view: theView)
</code>```

Body:
To do this recursively (I.e. fetching all subview's views aswell), you can use this generic function:

private func getSubviewsOf<T : UIView>(view:UIView) -> [T] {
    var subviews = [T]()

    for subview in view.subviews {
        subviews += getSubviewsOf(view: subview) as [T]

        if let subview = subview as? T {
            subviews.append(subview)
        }
    }

    return subviews
}

To fetch all UILabel's in a view hierarchy, just do this:

let allLabels : [UILabel] = getSubviewsOf(view: theView)


问:
Unknown input format: 'x11grab'
guys:

I have problems when i compile ffmpeg and run ffmpeg in linux.

My environment:

1: ubuntu 17.10_x64_bit(i don't think the os version is the key)

2: gcc (Ubuntu 6.3.0-19ubuntu1) 6.3.0 20170618

3: ffmpeg open source code:3.2

first, i download the source code from ffmpeg official site. I compile this project with there instructions：

```<code>./configure --prefix=/home/jjh/software/ffmpeg --enable-shared
make
make install
</code>```

and it worked without any error except some warning, then i run:

```<code>./ffmpeg -h
</code>```

i make sure that it works and output normally.

but i want use ffmpeg to grabbing screen. so i use this construction(o):

```<code>ffmpeg -f x11grab -video_size cif -framerate 25 -i :0.0 /tmp/out.mpg
</code>```

then output error:

```<code>Unknown input format: 'x11grab'
</code>```

i want to re-compile this project with --enable-x11grab option, btw , so many solution tell me to to this. but when i add this option, i get some errors:

```<code>Invalid option --enable-x11grab
</code>```

some people says that i should install some libs:

```<code>libxfixes-dev
sudo apt-get install libxext-dev
</code>```

so i installed these libs, but it always show this error. pls help me.

答:
I believe x11grab is deprecated in this version of ffmpeg, though they only write this to Changelog in version 3.3.

If you drag a git version of ffmpeg and check git log, you can see several commits around Mar 15 2017, 5ed4644d6d 4fef648d10 and others, which remove  legacy x11grab references.

The alternative of x11grab is called xcbgrab in ffmpeg (higher than 3.2), that can be built with --enable-libxcb.

Title: Unknown input format: 'x11grab'

Body:
guys:

I have problems when i compile ffmpeg and run ffmpeg in linux.

My environment:

1: ubuntu 17.10_x64_bit(i don't think the os version is the key)

2: gcc (Ubuntu 6.3.0-19ubuntu1) 6.3.0 20170618

3: ffmpeg open source code:3.2

first, i download the source code from ffmpeg official site. I compile this project with there instructions：

./configure --prefix=/home/jjh/software/ffmpeg --enable-shared
make
make install

and it worked without any error except some warning, then i run:

./ffmpeg -h

i make sure that it works and output normally.

but i want use ffmpeg to grabbing screen. so i use this construction(o):

ffmpeg -f x11grab -video_size cif -framerate 25 -i :0.0 /tmp/out.mpg

then output error:

Unknown input format: 'x11grab'

i want to re-compile this project with --enable-x11grab option, btw , so many solution tell me to to this. but when i add this option, i get some errors:

Invalid option --enable-x11grab

some people says that i should install some libs:

libxfixes-dev
sudo apt-get install libxext-dev

so i installed these libs, but it always show this error. pls help me.


问:
Concatenating string and integers in pandas dataframe(based on conditions)
In my dataframe I have 2 columns:

Country index(For example SK)

id_number(usually 8 digit,for example:98341852)

I want to concatenate them and it's easy:

```<code>sk_df['id'] = sk_df['country index'].str.cat(sk_df['id_number'].values.astype(str))
</code>```

But some of rows in column id_number has number of digits less than 8. In this case I want to add zeros as separator between Country index and id_number(for example, if length of id_number is 6 I want to add 8-6 = 2 zeros between variables: SK00813841. If id_number length is 7,than add 1 zero etc)

I tried this:

```<code>def indexing(row):
    if row['id_number'].astype(str).str.len() == 8:
        return row['country index'].str.cat(row['id_number'].values.astype(str))
    else:
        sep_mult = 8 - row['id_number'].astype(str).str.len()
        return row['country index'].str.cat(row['id_number'].values.astype(str),sep = '0'*sep_mult)

sk_df['id'] = sk_df.apply(lambda row: indexing(row),axis = 1)
</code>```

But it doesn't work.
How can I do it?

答:
Use .zfill():

```<code>sk_df['id'] = sk_df['country index'] + sk_df['id_number'].astype(str).str.zfill(8)
</code>```

Body:
In my dataframe I have 2 columns:

Country index(For example SK)

id_number(usually 8 digit,for example:98341852)

I want to concatenate them and it's easy:

sk_df['id'] = sk_df['country index'].str.cat(sk_df['id_number'].values.astype(str))

But some of rows in column id_number has number of digits less than 8. In this case I want to add zeros as separator between Country index and id_number(for example, if length of id_number is 6 I want to add 8-6 = 2 zeros between variables: SK00813841. If id_number length is 7,than add 1 zero etc)

I tried this:

def indexing(row):
    if row['id_number'].astype(str).str.len() == 8:
        return row['country index'].str.cat(row['id_number'].values.astype(str))
    else:
        sep_mult = 8 - row['id_number'].astype(str).str.len()
        return row['country index'].str.cat(row['id_number'].values.astype(str),sep = '0'*sep_mult)

sk_df['id'] = sk_df.apply(lambda row: indexing(row),axis = 1)

But it doesn't work.
How can I do it?

Body:
Use .zfill():

sk_df['id'] = sk_df['country index'] + sk_df['id_number'].astype(str).str.zfill(8)


问:
Node.js: use request module receive error bytes in http response
I'm using nodejs to send http request to a server, and get http response from it(the http response body is encrypted, while the http header is normal). The response body will be written to a file. But I find the response body is different from what the server sent.

This is what I've done:

```<code>request.post({
    headers: {'content-type':'application/json'},
        url:'url-to-server',
        body:data-to-send
    }, function(error, response, body){
    if(!error && response.statusCode==200){
        fs.writeFile(path-to-file,body,function(err){
        });
    }
});
</code>```

The problem is, some byte values are replaced by ef bf bd

```
Server Send:
    <b>f5</b> cb b6 48 77 <b>b6</b> 26 6a d2 4c d8 d9 ...
Received data:
    <b>ef bf bd</b> cb b6 48 77 <b>ef bf bd</b> 26 6a ...
```

Any ideas?

答:
I've found that ef bf bd occurs when it tries to use utf-8 encoding. So I want to recieve raw data without encoding.

And I found this question about getting binary content, according to this link, i add encoding:null in my code, see below:

```

    request.post({
        headers: {'content-type':'application/json'},
        url:'url-to-server',
        <b>encoding:null</b>,
        body:data-to-send
    }, function(error, response, body){
        if(!error && response.statusCode==200){
            fs.writeFile(path-to-file,body,function(err){
            });
        }
    });

```

And now the received data is correct.

Body:
I'm using nodejs to send http request to a server, and get http response from it(the http response body is encrypted, while the http header is normal). The response body will be written to a file. But I find the response body is different from what the server sent.

This is what I've done:

request.post({
    headers: {'content-type':'application/json'},
        url:'url-to-server',
        body:data-to-send
    }, function(error, response, body){
    if(!error && response.statusCode==200){
        fs.writeFile(path-to-file,body,function(err){
        });
    }
});

The problem is, some byte values are replaced by ef bf bd

Server Send:
    f5 cb b6 48 77 b6 26 6a d2 4c d8 d9 ...
Received data:
    ef bf bd cb b6 48 77 ef bf bd 26 6a ...

Any ideas?

Body:
I've found that ef bf bd occurs when it tries to use utf-8 encoding. So I want to recieve raw data without encoding.

And I found this question about getting binary content, according to this link, i add encoding:null in my code, see below:

    request.post({
        headers: {'content-type':'application/json'},
        url:'url-to-server',
        encoding:null,
        body:data-to-send
    }, function(error, response, body){
        if(!error && response.statusCode==200){
            fs.writeFile(path-to-file,body,function(err){
            });
        }
    });

And now the received data is correct.


问:
UnableToResolveError : unable to resolve module `merge` from Libraries/ART/React Native ART.js
I am new to React-native.

I am stuck with this error :
UnableToResolveError : unable to resolve module merge from Libraries/ART/ReactNativeART.js

dependencies I have used are :

```<code>"dependencies": {
    "apsl-react-native-button": "^3.0.2",
    "react": "16.0.0-alpha.6",
    "react-native": "0.44.2",
    "react-native-deprecated-custom-components": "^0.1.0",
    .....................
  },
</code>```

in node_modules -> react-native/Libraries/ART/ReactNativeART.js file is also available.

When I run react-native run-android command, I am facing this error.

Can anyone help me in this ?

答: Just need to install this module npm i --save merge

Body:
I am new to React-native.

I am stuck with this error :
UnableToResolveError : unable to resolve module merge from Libraries/ART/ReactNativeART.js

dependencies I have used are :

"dependencies": {
    "apsl-react-native-button": "^3.0.2",
    "react": "16.0.0-alpha.6",
    "react-native": "0.44.2",
    "react-native-deprecated-custom-components": "^0.1.0",
    .....................
  },

in node_modules -> react-native/Libraries/ART/ReactNativeART.js file is also available.

When I run react-native run-android command, I am facing this error.

Can anyone help me in this ?


问:
Not getting exact text from BeautifulSoup
I am trying to get the exact text from the HTML page but output text is different than expected text.

text on HTML page

```<code>Салнас 14
</code>```

text show by beautifulSoup

```<code>ĐĄĐ°ĐťĐ˝Đ°Ń 14
</code>```

My code is

```<code>page = BeautifulSoup(url.read(),'html.parser')
page.find(id='tdo_11').text
</code>```

Html inspect code for the div

```<code><td class="ads_opt" id="tdo_11" nowrap=""><b>Салнас 14</b></td>
</code>```

I'm not understanding what causes this?
Should I use the different parser?

答:
Use the requests library for making HTTP requests, it's much better than what Python has built in for many reasons. It takes care of encodings automatically and intelligently.

```<code>import requests
response = requests.get('https://www.ss.lv/msg/ru/real-estate/flats/riga/plyavnieki/onlol.html')
page = BeautifulSoup(response.text, 'html.parser')
</code>```

Body:
I am trying to get the exact text from the HTML page but output text is different than expected text.

text on HTML page

Салнас 14

text show by beautifulSoup

ĐĄĐ°ĐťĐ˝Đ°Ń 14

My code is

page = BeautifulSoup(url.read(),'html.parser')
page.find(id='tdo_11').text

Html inspect code for the div

Салнас 14

I'm not understanding what causes this?
Should I use the different parser?

Body:
Use the requests library for making HTTP requests, it's much better than what Python has built in for many reasons. It takes care of encodings automatically and intelligently.

import requests
response = requests.get('https://www.ss.lv/msg/ru/real-estate/flats/riga/plyavnieki/onlol.html')
page = BeautifulSoup(response.text, 'html.parser')


问:
Load Website via Dedicted IP in CentOS + Direct Admin
I use Direct Admin and Apache in CentOS 6.5, When i browse Server IP a white page load that Apache is functioning normally .

How can change this that when i browse IP see my website.com?

I don't want use IP/~Username method.

答:
Check this folder:
/var/www/html

There's your index.html file containing "Apache is functioning normally".

Also you can create sub-folders here and access them via:
http://ip/subFolderName


问:
Linq with dot notation - which is better form or what's the difference between these two?
I've been reading Jon Skeet's C# In Depth: Second Edition and I noticed something slightly different in one of his examples from something I do myself.

He has something similar to the following:

```<code>var item = someObject.Where(user => user.Id == Id).Single();
</code>```

Whereas I've been doing the following:

```<code>var item = someObject.Single(user => user.Id == Id);
</code>```

Is there any real difference between the two? I know Jon Skeet is pretty much the c# god so I tend to think his knowledge in this area is better than mine so I might be misunderstanding something here. Hope someone can help.

答:
Specifically for Linq2Objects, I personally prefer using the Enumerable.Single(this, predicate) version directly, simply because adding the Enumerable.Where will introduce an additional enumeration which Enumerable.Single will pull the data from.

By using Enumerable.Single directly on the primary enumerable, no additional enumerations are started. I have never benchmarked this to evaluate the real performance impact, but why execute more code when you don't need to right? Especially if readability is not impacted, of course this last point is rather subjective.

Body:
I've been reading Jon Skeet's C# In Depth: Second Edition and I noticed something slightly different in one of his examples from something I do myself.

He has something similar to the following:

var item = someObject.Where(user => user.Id == Id).Single();

Whereas I've been doing the following:

var item = someObject.Single(user => user.Id == Id);

Is there any real difference between the two? I know Jon Skeet is pretty much the c# god so I tend to think his knowledge in this area is better than mine so I might be misunderstanding something here. Hope someone can help.


问:
Youtube API v3 return 401 when i try to upload video
I use ServiceAccount uploader for youtube. I use Youtube API v3.
I have simple console application, that upload video to youtube

```<code>String serviceAccountEmail = "...";

        var certificate = new X509Certificate2(@"G:\Youtube\1ffd6ea22be7c41e0852935a0f35438e4beb2e2d-privatekey.p12", "notasecret", X509KeyStorageFlags.Exportable);
        //, YouTubeService.Scope.YoutubeUpload
        ServiceAccountCredential credential = new ServiceAccountCredential(
           new ServiceAccountCredential.Initializer(serviceAccountEmail)
           {
                                  Scopes = new[] { YouTubeService.Scope.Youtube, YouTubeService.Scope.YoutubeUpload }
           }.FromCertificate(certificate));

        var youtube = new YouTubeService(new BaseClientService.Initializer()
        {
            HttpClientInitializer = credential,
        });

        var video = new Video
        {
            Snippet = new VideoSnippet
            {
                Title = "Video title",
                Description = "Video description",
                Tags = new string[] {"tag1", "tag2"},
                CategoryId = "22"
            },
            Status = new VideoStatus {PrivacyStatus = "public"}
        };

        var fileStream = new FileStream("G:\\1.mp4", FileMode.Open);

        var videosInsertRequest = youtube.Videos.Insert(video, "snippet,status", fileStream, "video/*");
        videosInsertRequest.ProgressChanged += videosInsertRequest_ProgressChanged;
        videosInsertRequest.ResponseReceived += videosInsertRequest_ResponseReceived;

        var uploadThread = new Thread(() => videosInsertRequest.Upload());
        uploadThread.Start();
        uploadThread.Join();

        Console.Read();
</code>```

But this code return error:
Response status code does not indicate success: 401 (Unauthorized).
Help me, please

This is result by Fiddler:

```<code>    HTTP/1.1 401 Unauthorized
WWW-Authenticate: Bearer realm="https://www.google.com/accounts/AuthSubRequest", error=invalid_token
Content-Type: application/json
Content-Length: 255
Date: Sun, 10 Nov 2013 14:36:29 GMT
Server: HTTP Upload Server Built on Nov 5 2013 16:15:49 (1383696949)
Alternate-Protocol: 443:quic

{
 "error": {
  "errors": [
   {
    "domain": "youtube.header",
    "reason": "youtubeSignupRequired",
    "message": "Unauthorized",
    "locationType": "header",
    "location": "Authorization"
   }
  ],
  "code": 401,
  "message": "Unauthorized"
 }
}
</code>```

答: Try to create your channel by Youtube App.</p>

Body:
I use ServiceAccount uploader for youtube. I use Youtube API v3.
I have simple console application, that upload video to youtube

String serviceAccountEmail = "...";

        var certificate = new X509Certificate2(@"G:\Youtube\1ffd6ea22be7c41e0852935a0f35438e4beb2e2d-privatekey.p12", "notasecret", X509KeyStorageFlags.Exportable);
        //, YouTubeService.Scope.YoutubeUpload
        ServiceAccountCredential credential = new ServiceAccountCredential(
           new ServiceAccountCredential.Initializer(serviceAccountEmail)
           {
                                  Scopes = new[] { YouTubeService.Scope.Youtube, YouTubeService.Scope.YoutubeUpload }
           }.FromCertificate(certificate));

        var youtube = new YouTubeService(new BaseClientService.Initializer()
        {
            HttpClientInitializer = credential,
        });

        var video = new Video
        {
            Snippet = new VideoSnippet
            {
                Title = "Video title",
                Description = "Video description",
                Tags = new string[] {"tag1", "tag2"},
                CategoryId = "22"
            },
            Status = new VideoStatus {PrivacyStatus = "public"}
        };

        var fileStream = new FileStream("G:\\1.mp4", FileMode.Open);

        var videosInsertRequest = youtube.Videos.Insert(video, "snippet,status", fileStream, "video/*");
        videosInsertRequest.ProgressChanged += videosInsertRequest_ProgressChanged;
        videosInsertRequest.ResponseReceived += videosInsertRequest_ResponseReceived;

        var uploadThread = new Thread(() => videosInsertRequest.Upload());
        uploadThread.Start();
        uploadThread.Join();

        Console.Read();

But this code return error:
Response status code does not indicate success: 401 (Unauthorized).
Help me, please

This is result by Fiddler:

    HTTP/1.1 401 Unauthorized
WWW-Authenticate: Bearer realm="https://www.google.com/accounts/AuthSubRequest", error=invalid_token
Content-Type: application/json
Content-Length: 255
Date: Sun, 10 Nov 2013 14:36:29 GMT
Server: HTTP Upload Server Built on Nov 5 2013 16:15:49 (1383696949)
Alternate-Protocol: 443:quic

{
 "error": {
  "errors": [
   {
    "domain": "youtube.header",
    "reason": "youtubeSignupRequired",
    "message": "Unauthorized",
    "locationType": "header",
    "location": "Authorization"
   }
  ],
  "code": 401,
  "message": "Unauthorized"
 }
}


问:
Iterating a multidimensional Lua Table in C
I have a problem iterating a multidimensional Lua table in C.

Let the Lua table be this i.e.:

```<code>local MyLuaTable = {
  {0x04, 0x0001, 0x0001, 0x84, 0x000000},
  {0x04, 0x0001, 0x0001, 0x84, 0x000010}
}
</code>```

I tried to extend the C sample code:

```<code> /* table is in the stack at index 't' */
 lua_pushnil(L);  /* first key */
 while (lua_next(L, t) != 0) {
   /* uses 'key' (at index -2) and 'value' (at index -1) */
   printf("%s - %s\n",
          lua_typename(L, lua_type(L, -2)),
          lua_typename(L, lua_type(L, -1)));
   /* removes 'value'; keeps 'key' for next iteration */
   lua_pop(L, 1);
 }
</code>```

by the second dimension:

```<code>/* table is in the stack at index 't' */
lua_pushnil(L);  /* first key */ /* Iterating the first dimension */
while (lua_next(L, t) != 0)
{
   /* uses 'key' (at index -2) and 'value' (at index -1) */
   printf("%s - %s\n",
          lua_typename(L, lua_type(L, -2)),
          lua_typename(L, lua_type(L, -1)));

   if(lua_istable(L, -1))
   {
      lua_pushnil(L);  /* first key */ /* Iterating the second dimension */
      while (lua_next(L, -2) != 0) /* table is in the stack at index -2 */
      {
         printf("%s - %s\n",
                lua_typename(L, lua_type(L, -2)),
                lua_typename(L, lua_type(L, -1)));
      }
      /* removes 'value'; keeps 'key' for next iteration */
      lua_pop(L, 1);
   }
   /* removes 'value'; keeps 'key' for next iteration */
   lua_pop(L, 1);
}
</code>```

The output is:

"number - table" (from the first dimension)

"number - number" (from the second dimension)

"number - thread" (from the second dimension)

Afterwards my code crashes in the "while (lua_next(L, -2) != 0)"

Has anybody an idea how to correctly iterate the two dimensional Lua table?

答:
The lua_pop(L, 1) from the second dimension is outside your iteration!

```<code>  while (lua_next(L, -2) != 0) /* table is in the stack at index -2 */
  {
     printf("%s - %s\n",
            lua_typename(L, lua_type(L, -2)),
            lua_typename(L, lua_type(L, -1)));
  }
  /* removes 'value'; keeps 'key' for next iteration */
  lua_pop(L, 1);
</code>```

You need to put it inside the while-loop to get it working to have the value removed, which lua_next() in your while-condition implicitly puts on the stack.

```<code>  while (lua_next(L, -2) != 0) /* table is in the stack at index -2 */
  {
     printf("%s - %s\n",
            lua_typename(L, lua_type(L, -2)),
            lua_typename(L, lua_type(L, -1)));
     /* removes 'value'; keeps 'key' for next iteration */
     lua_pop(L, 1);
  }
</code>```

This way it should work as expected.

Body:
I have a problem iterating a multidimensional Lua table in C.

Let the Lua table be this i.e.:

local MyLuaTable = {
  {0x04, 0x0001, 0x0001, 0x84, 0x000000},
  {0x04, 0x0001, 0x0001, 0x84, 0x000010}
}

I tried to extend the C sample code:

 /* table is in the stack at index 't' */
 lua_pushnil(L);  /* first key */
 while (lua_next(L, t) != 0) {
   /* uses 'key' (at index -2) and 'value' (at index -1) */
   printf("%s - %s\n",
          lua_typename(L, lua_type(L, -2)),
          lua_typename(L, lua_type(L, -1)));
   /* removes 'value'; keeps 'key' for next iteration */
   lua_pop(L, 1);
 }

by the second dimension:

/* table is in the stack at index 't' */
lua_pushnil(L);  /* first key */ /* Iterating the first dimension */
while (lua_next(L, t) != 0)
{
   /* uses 'key' (at index -2) and 'value' (at index -1) */
   printf("%s - %s\n",
          lua_typename(L, lua_type(L, -2)),
          lua_typename(L, lua_type(L, -1)));

   if(lua_istable(L, -1))
   {
      lua_pushnil(L);  /* first key */ /* Iterating the second dimension */
      while (lua_next(L, -2) != 0) /* table is in the stack at index -2 */
      {
         printf("%s - %s\n",
                lua_typename(L, lua_type(L, -2)),
                lua_typename(L, lua_type(L, -1)));
      }
      /* removes 'value'; keeps 'key' for next iteration */
      lua_pop(L, 1);
   }
   /* removes 'value'; keeps 'key' for next iteration */
   lua_pop(L, 1);
}

The output is:

"number - table" (from the first dimension)

"number - number" (from the second dimension)

"number - thread" (from the second dimension)

Afterwards my code crashes in the "while (lua_next(L, -2) != 0)"

Has anybody an idea how to correctly iterate the two dimensional Lua table?

Body:
The lua_pop(L, 1) from the second dimension is outside your iteration!

  while (lua_next(L, -2) != 0) /* table is in the stack at index -2 */
  {
     printf("%s - %s\n",
            lua_typename(L, lua_type(L, -2)),
            lua_typename(L, lua_type(L, -1)));
  }
  /* removes 'value'; keeps 'key' for next iteration */
  lua_pop(L, 1);

You need to put it inside the while-loop to get it working to have the value removed, which lua_next() in your while-condition implicitly puts on the stack.

  while (lua_next(L, -2) != 0) /* table is in the stack at index -2 */
  {
     printf("%s - %s\n",
            lua_typename(L, lua_type(L, -2)),
            lua_typename(L, lua_type(L, -1)));
     /* removes 'value'; keeps 'key' for next iteration */
     lua_pop(L, 1);
  }

This way it should work as expected.


问:
VALIDATE statement is causing a value not to be stored in the database
I have been dealing with an issue recently and am stuck. A particular program(a compiled .p) has codes written where its trying to save values to a particular field in the db.

Below this there is a VAILDATE statement on that table. This is causing the value to revert while doing an update operation. I messaged before and after VALIDATE and can see the value updated before VALIDATE and reverted just after VALIDATE. Please can someone help me on this. Many thanks in advance.

答:
From the documentation:

```<code>VALIDATE statement:
Verifies that a record complies with mandatory field and unique index definitions.
</code>```

So, if your UPDATE is reverted after VALIDATE it means that at least one the filed value is not as per constraints. See your table schema and field values. Check if they are okay. It is not clear from your question if you have access to code or not. If you have access to the code and if VALIDATE statement has NO-ERROR, try removing NO-ERROR. If you remove NO-ERROR you can see error message and it might have some clues in it.

Body:
From the documentation:

VALIDATE statement:
Verifies that a record complies with mandatory field and unique index definitions.

So, if your UPDATE is reverted after VALIDATE it means that at least one the filed value is not as per constraints. See your table schema and field values. Check if they are okay. It is not clear from your question if you have access to code or not. If you have access to the code and if VALIDATE statement has NO-ERROR, try removing NO-ERROR. If you remove NO-ERROR you can see error message and it might have some clues in it.


问:
How to cancel or block incoming calls programmatically in iOS? Is it possible?
How to block or cancel income calls programmatically or How to activate "do not disturb" mode in iOS programmatically.

答:
It's clearly forbidden for a third-part app to block incoming calls. As it's described here:
Can an iPhone app block phone calls?

However you can use CallKit to block unwanted calls. Your app should be able to add blocked numbers.

The reason Apple doesn't allow you to block it is because there would be a lot of abuse and Malware that would disturb user experience.


问:
ng-options getting null value in the drop-down.I'm using for controllers?
I'm new to angular .I'm passing ng-model for selected option in the drop-down.
My code is

```<code><label>Tables</label><select ng-options="option.display for option in
tableviewOptions" ng-model="selectedOption" ng-change="getView
(selectedOption)></select>
</code>```

In this I'm I changed table options the option is not showing as selected in the DOM.

答:
we have updated your question. But I have post it as an answer with some changes

like option.display is wrong, that should be like below .

```<code><label>Tables</label><select ng-options="option as option.display  for option in
tableviewOptions" ng-model="selectedOption" ng-change="getView
(selectedOption)></select>
</code>```

But if you post your controller code and JSON data , then it could be better to avoid guess answers

Body:
I'm new to angular .I'm passing ng-model for selected option in the drop-down.
My code is

Tables<select ng-options="option.display for option in
tableviewOptions" ng-model="selectedOption" ng-change="getView
(selectedOption)></select>

In this I'm I changed table options the option is not showing as selected in the DOM.

Body:
we have updated your question. But I have post it as an answer with some changes

like option.display is wrong, that should be like below .

<label>Tables</label><select ng-options="option as option.display  for option in
tableviewOptions" ng-model="selectedOption" ng-change="getView
(selectedOption)></select>

But if you post your controller code and JSON data , then it could be better to avoid guess answers


问:
Supervisor alternatives on shared hosting
I have deployed my app on shared host "Hostgator", I've ssh successfull access, however I can't install supervisor to manage queue processing, the command sudo apt-get install supervisor always return errors, so I have contacted support and I was told that I can't make sudo commands with sharedhost "cloud" plan and I have to move to VPS or dedicated which I can't move to at this time.

My question is : is there any alternative can I use to manage the queue processing without supervisor or another way to go around this ? anybody wen through this and found a solution ?

I was thinking to make a cron job with command php artisan queue:work every morning maybe but is this a good practice ?

Thanks in advance any help is appreciated.

答:
For anyone there who is going through something similar, I managed that by cron jobs that run every hour but you have to migrate failed jobs table to make sure that failed jobs are handled and don't stop the queue processing, even though this is not ideal but it somehow works. The ideal solution is considering VPS hosting or mixing Laravel Forge with DigitalOcean for example as mentioned in laravel docs.

Cheers.