答:
You can tell Composer to autoload any (non-PSR) class by adding the base folder to:

```<code>"autoload": {
"classmap": [
    "app/commands",
    "app/database/migrations",
    "app/database/seeds",
    "app/tests/TestCase.php"
],
....
</code>```

And you can also autoload autoloaders by adding them to the files section:

```<code>"autoload": {
"files": [
    "temboo/src/Temboo_Loader.php"
],
</code>```

...

After adding those entries, execute:

```<code>composer dumpautoload
</code>```

And check the file vendor/composer/autoload_classmap.php, the available classes must be all listed in it, if one file is not there it will not be autoloaded.

Title: Adding Third party library to Laravel

Body:
You can tell Composer to autoload any (non-PSR) class by adding the base folder to:

"autoload": {
"classmap": [
    "app/commands",
    "app/database/migrations",
    "app/database/seeds",
    "app/tests/TestCase.php"
],
....

And you can also autoload autoloaders by adding them to the files section:

"autoload": {
"files": [
    "temboo/src/Temboo_Loader.php"
],

...

After adding those entries, execute:

composer dumpautoload

And check the file vendor/composer/autoload_classmap.php, the available classes must be all listed in it, if one file is not there it will not be autoloaded.


来源: stackexchange

问:
Add or Remove multiple records without manual comparision
I have three tables: Person, Books and PersonBook. Person and Books are the main tables and PersonBook is a "mapping table" between them.

The logic is very simple: Each person has multiple books. In the Add / Remove Book Screen, the Person can Add a new book or remove the existing book.

Note: I depicted only the limited column for easy understanding, but
  the actual table has large number of columns and much more constrains.

Person:

```<code>PersonId    FirstName    LastName
_____________________________________
1           Emma         Watsan
2           John         Peter
3           Albert       Einsten
(....)
</code>```

Book:

```<code>BookId      BookName                ISBN           Author
___________________________________________________________
1           Beautiful Darkness
2           Bones Never Lies
3           The Lion
(...)
</code>```

PersonBook:

```<code>Id    PersonId     BookId
___________________________
1     1            1
2     2            3
3     3            3
(...)
</code>```

I have a list PersonBook, and I need to update it in the table using Entity State.

I'm currently doing the following:

```<code>Context.PersonBook.RemoveRange(Context.PersonBook.Where(m => m.PersonId == PersonId));
Context.PersonBook.AddRange(ListOfBooks);
</code>```

Here I give a simple condition:

```<code>Context.PersonBook.Where(m => m.PersonId == PersonId)
</code>```

But in reality, I have many checks.

My Requirement is to remove only the records which do not exist in the local collection ListOfBooks and add the records which do not exist in the DbSet.

Note: Each Person has 1K+ Books. In each edit request, comparing of
  all the records leads to performance degradation and what I am doing
  currently is better than that comparison, but it increases the
  primary key (auto Incremental Key PersonBook.Id) value to very large numbers.

答:
The comparison will be much faster if you prepare and use a fast lookup data structures. Since here you are processing the person books, it could be a Dictionary<int, PersonBook> for both old and new records with BookId being a key:

```<code>var oldBooks = Context.PersonBook.Where(e => e.PersonId == PersonId).ToDictionary(e => e.BookId);
var newBooks = ListOfBooks.ToDictionary(e => e.BookId);
Context.PersonBook.RemoveRange(oldBooks.Values.Where(e => !newBooks.ContainsKey(e.BookId)));
Context.PersonBook.AddRange(newBooks.Values.Where(e => !oldBooks.ContainsKey(e.BookId)));
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have three tables: Person, Books and PersonBook. Person and Books are the main tables and PersonBook is a "mapping table" between them.

The logic is very simple: Each person has multiple books. In the Add / Remove Book Screen, the Person can Add a new book or remove the existing book.

Note: I depicted only the limited column for easy understanding, but
  the actual table has large number of columns and much more constrains.

Person:

PersonId    FirstName    LastName
_____________________________________
1           Emma         Watsan
2           John         Peter
3           Albert       Einsten
(....)

Book:

BookId      BookName                ISBN           Author
___________________________________________________________
1           Beautiful Darkness
2           Bones Never Lies
3           The Lion
(...)

PersonBook:

Id    PersonId     BookId
___________________________
1     1            1
2     2            3
3     3            3
(...)

I have a list PersonBook, and I need to update it in the table using Entity State.

I'm currently doing the following:

Context.PersonBook.RemoveRange(Context.PersonBook.Where(m => m.PersonId == PersonId));
Context.PersonBook.AddRange(ListOfBooks);

Here I give a simple condition:

Context.PersonBook.Where(m => m.PersonId == PersonId)

But in reality, I have many checks.

My Requirement is to remove only the records which do not exist in the local collection ListOfBooks and add the records which do not exist in the DbSet.

Note: Each Person has 1K+ Books. In each edit request, comparing of
  all the records leads to performance degradation and what I am doing
  currently is better than that comparison, but it increases the
  primary key (auto Incremental Key PersonBook.Id) value to very large numbers.

Body:
The comparison will be much faster if you prepare and use a fast lookup data structures. Since here you are processing the person books, it could be a Dictionary<int, PersonBook> for both old and new records with BookId being a key:

var oldBooks = Context.PersonBook.Where(e => e.PersonId == PersonId).ToDictionary(e => e.BookId);
var newBooks = ListOfBooks.ToDictionary(e => e.BookId);
Context.PersonBook.RemoveRange(oldBooks.Values.Where(e => !newBooks.ContainsKey(e.BookId)));
Context.PersonBook.AddRange(newBooks.Values.Where(e => !oldBooks.ContainsKey(e.BookId)));


问:
Convert Ruby Date to Integer
How can I convert a Ruby Date to an integer?</p>

答:
```<code>Time.now.to_i
</code>```

returns seconds since epoch format

ContentLicense: CC BY-SA 2.5

Title: Convert Ruby Date to Integer

Body:
Time.now.to_i

returns seconds since epoch format

ContentLicense: CC BY-SA 4.0


问:
Does resnet have fully connected layers?
In my understanding, fully connected layer(fc in short) is used for predicting.

For example, VGG Net used 2 fc layers, which are both 4096 dimension. The last layer for softmax has dimension same with classes num:1000.

But for resnet, it used global average pooling, and use the pooled result of last convolution layer as the input.

But they still has a fc layer! Does this layer a really fc layer? Or this layer is only to make input into a vector of features which number is classes number? Does this layer has function for prediction result?

In a word, how many fc layers do resnet and VGGnet have? Does VGGnet's 1st 2nd 3rd fc layer has different function?

答:
VGG has three FC layers, two with 4096 neurons and one with 1000 neurons which outputs the class probabilities.

ResNet only has one FC layer with 1000 neurons which again outputs the class probabilities. In a NN classifier always the best choice is to use softmax, some authors make this explicit in the diagram while others do not.


问:
How to have 100% opacity even when control is disabled in wpf C#
I have a textbox in my wpf, when I disable it the opacity decrease. This happens to tell the user that the textbox is not enable. Is there any way to disable a control and keep the look as the same?</p>

答:
Set the Template property to your own custom ControlTemplate:

```<code><TextBox IsEnabled="False" Margin="10">
    <TextBox.Template>
        <ControlTemplate TargetType="{x:Type TextBox}">
            <Border x:Name="border" BorderBrush="{TemplateBinding BorderBrush}" BorderThickness="{TemplateBinding BorderThickness}" Background="{TemplateBinding Background}" SnapsToDevicePixels="True">
                <ScrollViewer x:Name="PART_ContentHost" Focusable="false" HorizontalScrollBarVisibility="Hidden" VerticalScrollBarVisibility="Hidden"/>
            </Border>
            <ControlTemplate.Triggers>
                <!--<Trigger Property="IsEnabled" Value="false">
                            <Setter Property="Opacity" TargetName="border" Value="0.56"/>
                        </Trigger>-->
                <Trigger Property="IsMouseOver" Value="true">
                    <Setter Property="BorderBrush" TargetName="border" Value="#FF7EB4EA"/>
                </Trigger>
                <Trigger Property="IsKeyboardFocused" Value="true">
                    <Setter Property="BorderBrush" TargetName="border" Value="#FF569DE5"/>
                </Trigger>
            </ControlTemplate.Triggers>
        </ControlTemplate>
    </TextBox.Template>
</TextBox>
</code>```

Body:
Set the Template property to your own custom ControlTemplate:

<TextBox IsEnabled="False" Margin="10">
    <TextBox.Template>
        <ControlTemplate TargetType="{x:Type TextBox}">
            <Border x:Name="border" BorderBrush="{TemplateBinding BorderBrush}" BorderThickness="{TemplateBinding BorderThickness}" Background="{TemplateBinding Background}" SnapsToDevicePixels="True">
                <ScrollViewer x:Name="PART_ContentHost" Focusable="false" HorizontalScrollBarVisibility="Hidden" VerticalScrollBarVisibility="Hidden"/>
            </Border>
            <ControlTemplate.Triggers>
                <!--<Trigger Property="IsEnabled" Value="false">
                            <Setter Property="Opacity" TargetName="border" Value="0.56"/>
                        </Trigger>-->
                <Trigger Property="IsMouseOver" Value="true">
                    <Setter Property="BorderBrush" TargetName="border" Value="#FF7EB4EA"/>
                </Trigger>
                <Trigger Property="IsKeyboardFocused" Value="true">
                    <Setter Property="BorderBrush" TargetName="border" Value="#FF569DE5"/>
                </Trigger>
            </ControlTemplate.Triggers>
        </ControlTemplate>
    </TextBox.Template>
</TextBox>


问:
use node-redis with node 8 util.promisify
node -v : 8.1.2

I use redis client node_redis with node 8 util.promisify , no blurbird.

the callback redis.get is ok, but promisify type get error message

TypeError: Cannot read property 'internal_send_command' of undefined

      at get (D:\Github\redis-test\node_modules\redis\lib\commands.js:62:24)

      at get (internal/util.js:229:26)

      at D:\Github\redis-test\app.js:23:27

      at Object. (D:\Github\redis-test\app.js:31:3)

      at Module._compile (module.js:569:30)

      at Object.Module._extensions..js (module.js:580:10)

      at Module.load (module.js:503:32)

      at tryModuleLoad (module.js:466:12)

      at Function.Module._load (module.js:458:3)

      at Function.Module.runMain (module.js:605:10)

my test code

```<code>const util = require('util');

var redis = require("redis"),
    client = redis.createClient({
        host: "192.168.99.100",
        port: 32768,
    });

let get = util.promisify(client.get);

(async function () {
    client.set(["aaa", JSON.stringify({
        A: 'a',
        B: 'b',
        C: "C"
    })]);

    client.get("aaa", (err, value) => {
        console.log(`use callback: ${value}`);
    });

    try {
        let value = await get("aaa");
        console.log(`use promisify: ${value}`);
    } catch (e) {
        console.log(`promisify error:`);
        console.log(e);
    }

    client.quit();
})()
</code>```

答:
changing let get = util.promisify(client.get);

to let get = util.promisify(client.get).bind(client);

solved it for me :)

Body:
node -v : 8.1.2

I use redis client node_redis with node 8 util.promisify , no blurbird.

the callback redis.get is ok, but promisify type get error message

TypeError: Cannot read property 'internal_send_command' of undefined

      at get (D:\Github\redis-test\node_modules\redis\lib\commands.js:62:24)

      at get (internal/util.js:229:26)

      at D:\Github\redis-test\app.js:23:27

      at Object. (D:\Github\redis-test\app.js:31:3)

      at Module._compile (module.js:569:30)

      at Object.Module._extensions..js (module.js:580:10)

      at Module.load (module.js:503:32)

      at tryModuleLoad (module.js:466:12)

      at Function.Module._load (module.js:458:3)

      at Function.Module.runMain (module.js:605:10)

my test code

const util = require('util');

var redis = require("redis"),
    client = redis.createClient({
        host: "192.168.99.100",
        port: 32768,
    });

let get = util.promisify(client.get);

(async function () {
    client.set(["aaa", JSON.stringify({
        A: 'a',
        B: 'b',
        C: "C"
    })]);

    client.get("aaa", (err, value) => {
        console.log(`use callback: ${value}`);
    });

    try {
        let value = await get("aaa");
        console.log(`use promisify: ${value}`);
    } catch (e) {
        console.log(`promisify error:`);
        console.log(e);
    }

    client.quit();
})()


问:
Can I cache contents loaded by jQuery.getScript()
As per jQuery documentation (https://api.jquery.com/jquery.getscript/) use more flexible $.ajax() method, but it doesn't work for me described in here (jQuery cannot load plugin file using ajax before calling the plugin function, thus, gives kind of weird result)

By default, $.getScript() sets the cache setting to false. This
  appends a timestamped query parameter to the request URL to ensure
  that the browser downloads the script each time it is requested. You
  can override this feature by setting the cache property globally using
  $.ajaxSetup():

```<code>$.ajaxSetup({
  cache: true
});
</code>```

But I need to cache few of the contents not all.

Alternatively, you could define a new method that uses the more
  flexible $.ajax() method.

It didn't work for me as it doesn't guarantee loading files in a sequence.

Now what is the best solution for this situation?

答:
```<code>$.getScript({
    url: "foo.js",
    cache: true
})
</code>```

Supported on jQuery 1.12.0 or later

Body:
As per jQuery documentation (https://api.jquery.com/jquery.getscript/) use more flexible $.ajax() method, but it doesn't work for me described in here (jQuery cannot load plugin file using ajax before calling the plugin function, thus, gives kind of weird result)

By default, $.getScript() sets the cache setting to false. This
  appends a timestamped query parameter to the request URL to ensure
  that the browser downloads the script each time it is requested. You
  can override this feature by setting the cache property globally using
  $.ajaxSetup():

$.ajaxSetup({
  cache: true
});

But I need to cache few of the contents not all.

Alternatively, you could define a new method that uses the more
  flexible $.ajax() method.

It didn't work for me as it doesn't guarantee loading files in a sequence.

Now what is the best solution for this situation?

Body:
$.getScript({
    url: "foo.js",
    cache: true
})

Supported on jQuery 1.12.0 or later


问:
ANDROID How can I send result in a new Activity after scanning a QR Code?
Hello to everyone I'm trying to create an app that scan a QR Code.

In the main activity I want to make the scan of the QR Code and I want to send the result in a new Activity.

Here is my code

Main Activity.java:

```<code>public class MainActivity extends AppCompatActivity {

SurfaceView cameraView;
BarcodeDetector barcode;
CameraSource cameraSource;
SurfaceHolder holder;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    if (ContextCompat.checkSelfPermission(this, android.Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED){
        ActivityCompat.requestPermissions(this, new String[]{android.Manifest.permission.CAMERA}, 200);
    }

    cameraView = (SurfaceView) findViewById(R.id.cameraView);
    cameraView.setZOrderMediaOverlay(true);
    holder = cameraView.getHolder();
    barcode = new BarcodeDetector.Builder(this)
            .setBarcodeFormats(Barcode.QR_CODE)
            .build();
    if(!barcode.isOperational()){
        Toast.makeText(getApplicationContext(), "Sorry, Couldn't setup the detector", Toast.LENGTH_LONG).show();
        this.finish();
    }
    cameraSource = new CameraSource.Builder(this, barcode)
            .setFacing(CameraSource.CAMERA_FACING_BACK)
            .setRequestedFps(24)
            .setAutoFocusEnabled(true)
            .setRequestedPreviewSize(1920,1024)
            .build();
    cameraView.getHolder().addCallback(new SurfaceHolder.Callback() {
        @Override
        public void surfaceCreated(SurfaceHolder holder) {
            try{
                if(ContextCompat.checkSelfPermission(MainActivity.this, android.Manifest.permission.CAMERA) == PackageManager.PERMISSION_GRANTED){
                    cameraSource.start(cameraView.getHolder());
                }
            }
            catch (IOException e){
                e.printStackTrace();
            }
        }

        @Override
        public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {

        }

        @Override
        public void surfaceDestroyed(SurfaceHolder holder) {

        }
    });
    barcode.setProcessor(new Detector.Processor<Barcode>() {
        @Override
        public void release() {

        }

        @Override
        public void receiveDetections(Detector.Detections<Barcode> detections) {
            final SparseArray<Barcode> barcodes =  detections.getDetectedItems();
            if(barcodes.size() > 0){

                Intent intent = new Intent(MainActivity.this, Result.class);
                startActivityForResult(intent, 100);
                intent.putExtra("barcode", barcodes.valueAt(0));
                setResult(RESULT_OK, intent);
                finish();
            }
        }
    });
}}
</code>```

Result.java:

```<code>public class Result extends AppCompatActivity {

TextView result;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_result);
    result = (TextView) findViewById(R.id.result);
}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    if(requestCode == 100 && resultCode == RESULT_OK){
        if(data != null){
            final Barcode barcode = data.getParcelableExtra("barcode");
            result.post(new Runnable() {
                @Override
                public void run() {
                    result.setText(barcode.displayValue);
                }
            });
        }
    }
}}
</code>```

But when I try to test the app in the result activity i can't see the result.

What's wrong?

Thank you to everyone

答:
In Result activity the retrieving of the data should be in onCreate method, not in onActivityResult, your Result class should look like this:

```<code>public class Result extends AppCompatActivity {
    TextView result;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_result);
        result = (TextView) findViewById(R.id.result);
        final Barcode barcode = getIntent().getParcelableExtra("barcode");
        result.setText(barcode.displayValue);
    }
}
</code>```

and in MainActivity, this line:

```<code>intent.putExtra("barcode", barcodes.valueAt(0));
</code>```

should be before

```<code>startActivityForResult(intent, 100);
</code>```

not after, like this:

```<code>Intent intent = new Intent(MainActivity.this, Result.class);
intent.putExtra("barcode", barcodes.valueAt(0));
startActivityForResult(intent, 100);
finish();
</code>```

Body:
Hello to everyone I'm trying to create an app that scan a QR Code.

In the main activity I want to make the scan of the QR Code and I want to send the result in a new Activity.

Here is my code

Main Activity.java:

public class MainActivity extends AppCompatActivity {

SurfaceView cameraView;
BarcodeDetector barcode;
CameraSource cameraSource;
SurfaceHolder holder;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    if (ContextCompat.checkSelfPermission(this, android.Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED){
        ActivityCompat.requestPermissions(this, new String[]{android.Manifest.permission.CAMERA}, 200);
    }

    cameraView = (SurfaceView) findViewById(R.id.cameraView);
    cameraView.setZOrderMediaOverlay(true);
    holder = cameraView.getHolder();
    barcode = new BarcodeDetector.Builder(this)
            .setBarcodeFormats(Barcode.QR_CODE)
            .build();
    if(!barcode.isOperational()){
        Toast.makeText(getApplicationContext(), "Sorry, Couldn't setup the detector", Toast.LENGTH_LONG).show();
        this.finish();
    }
    cameraSource = new CameraSource.Builder(this, barcode)
            .setFacing(CameraSource.CAMERA_FACING_BACK)
            .setRequestedFps(24)
            .setAutoFocusEnabled(true)
            .setRequestedPreviewSize(1920,1024)
            .build();
    cameraView.getHolder().addCallback(new SurfaceHolder.Callback() {
        @Override
        public void surfaceCreated(SurfaceHolder holder) {
            try{
                if(ContextCompat.checkSelfPermission(MainActivity.this, android.Manifest.permission.CAMERA) == PackageManager.PERMISSION_GRANTED){
                    cameraSource.start(cameraView.getHolder());
                }
            }
            catch (IOException e){
                e.printStackTrace();
            }
        }

        @Override
        public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {

        }

        @Override
        public void surfaceDestroyed(SurfaceHolder holder) {

        }
    });
    barcode.setProcessor(new Detector.Processor<Barcode>() {
        @Override
        public void release() {

        }

        @Override
        public void receiveDetections(Detector.Detections<Barcode> detections) {
            final SparseArray<Barcode> barcodes =  detections.getDetectedItems();
            if(barcodes.size() > 0){

                Intent intent = new Intent(MainActivity.this, Result.class);
                startActivityForResult(intent, 100);
                intent.putExtra("barcode", barcodes.valueAt(0));
                setResult(RESULT_OK, intent);
                finish();
            }
        }
    });
}}

Result.java:

public class Result extends AppCompatActivity {

TextView result;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_result);
    result = (TextView) findViewById(R.id.result);
}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    if(requestCode == 100 && resultCode == RESULT_OK){
        if(data != null){
            final Barcode barcode = data.getParcelableExtra("barcode");
            result.post(new Runnable() {
                @Override
                public void run() {
                    result.setText(barcode.displayValue);
                }
            });
        }
    }
}}

But when I try to test the app in the result activity i can't see the result.

What's wrong?

Thank you to everyone

Body:
In Result activity the retrieving of the data should be in onCreate method, not in onActivityResult, your Result class should look like this:

public class Result extends AppCompatActivity {
    TextView result;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_result);
        result = (TextView) findViewById(R.id.result);
        final Barcode barcode = getIntent().getParcelableExtra("barcode");
        result.setText(barcode.displayValue);
    }
}

and in MainActivity, this line:

intent.putExtra("barcode", barcodes.valueAt(0));

should be before

startActivityForResult(intent, 100);

not after, like this:

Intent intent = new Intent(MainActivity.this, Result.class);
intent.putExtra("barcode", barcodes.valueAt(0));
startActivityForResult(intent, 100);
finish();


问:
Detect Phone Number & Link in xamarin.Form
assume we have the following text :

Contact us on 015546889 or email@hotmail.com

How I can display the above text in same label in xamarin.forms and handle click on email by send email and handle phone call by click on the number.

I can use the the following code to make clickable label

```<code>Label label = new Label;
     label.GestureRecognizers.Add(new TapGestureRecognizer()
    {
         Command = new Command(() => {
           //do some function here
        })
   });
</code>```

How to hyperlink same as messaging app or Whatsapp application

答:
Check out the Label element in Forms9Patch.  It has a HtmlText property that allows simple markup.

```<code>using System;
using Xamarin.Forms;
namespace Forms9PatchDemo
{
    public class LabelLink : ContentPage
    {
        public LabelLink()
        {
            var label = new Forms9Patch.Label
            {
                HtmlText = "Contact us on <a id=\"phone\" href=\"tel:+353015546889\">015546889</a> or <a id=\"email\" href=\"mailto:email@hotmail.com\">email@hotmail.com</a>"
            };
            label.ActionTagTapped += (object sender, Forms9Patch.ActionTagEventArgs e) =>
            {
                var id = e.Id;
                var href = e.Href;
                var uri = new Uri(e.Href);
                Device.OpenUri(uri);
            };
            Content = new StackLayout
            {
                VerticalOptions = LayoutOptions.Center,
                Children = {
                    new Label { Text = "Forms9Patch.Label.HtmlText <a> example" },
                    new BoxView { BackgroundColor = Color.Black, HeightRequest = 1 },
                    label
                }
            };
        }
    }
}
</code>```

Note that the above example won't work on iOS emulators because the tel: and mailto: schemes are not supported.  It does work on actual iOS devices.

Body:
assume we have the following text :

Contact us on 015546889 or email@hotmail.com

How I can display the above text in same label in xamarin.forms and handle click on email by send email and handle phone call by click on the number.

I can use the the following code to make clickable label

Label label = new Label;
     label.GestureRecognizers.Add(new TapGestureRecognizer()
    {
         Command = new Command(() => {
           //do some function here
        })
   });

How to hyperlink same as messaging app or Whatsapp application

Body:
Check out the Label element in Forms9Patch.  It has a HtmlText property that allows simple markup.

using System;
using Xamarin.Forms;
namespace Forms9PatchDemo
{
    public class LabelLink : ContentPage
    {
        public LabelLink()
        {
            var label = new Forms9Patch.Label
            {
                HtmlText = "Contact us on <a id=\"phone\" href=\"tel:+353015546889\">015546889</a> or <a id=\"email\" href=\"mailto:email@hotmail.com\">email@hotmail.com</a>"
            };
            label.ActionTagTapped += (object sender, Forms9Patch.ActionTagEventArgs e) =>
            {
                var id = e.Id;
                var href = e.Href;
                var uri = new Uri(e.Href);
                Device.OpenUri(uri);
            };
            Content = new StackLayout
            {
                VerticalOptions = LayoutOptions.Center,
                Children = {
                    new Label { Text = "Forms9Patch.Label.HtmlText <a> example" },
                    new BoxView { BackgroundColor = Color.Black, HeightRequest = 1 },
                    label
                }
            };
        }
    }
}

Note that the above example won't work on iOS emulators because the tel: and mailto: schemes are not supported.  It does work on actual iOS devices.


问:
Rewriting example.com/section.php?username=xyz to example.com/xyz/section
Using the following htaccess, I have been able to rewrite example.com/profile.php?username=xyz to example.com/xyz,

```<code>RewriteEngine On
RewriteRule ^([a-zA-Z0-9_-]+)$ profile.php?user=$1
RewriteRule ^([a-zA-Z0-9_-]+)/$ profile.php?user=$1
</code>```

Adding the following to the above,

```<code>RewriteRule ^([a-zA-Z0-9_-]+)/section$ section.php?user=$1
RewriteRule ^([a-zA-Z0-9_-]+)/section/$ section.php?user=$1
</code>```

did not resolve example.com/section.php?username=xyz to example.com/xyz/section.

Am I doing something wrong here?

答:
To look for static files (images, css) in the right directory without having to write the file address, do:

```<code>RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
</code>```

Before writing the code suggested by RageD

(Sorry, should have posted it as a comment but I needed newlines)

Body:
Using the following htaccess, I have been able to rewrite example.com/profile.php?username=xyz to example.com/xyz,

RewriteEngine On
RewriteRule ^([a-zA-Z0-9_-]+)$ profile.php?user=$1
RewriteRule ^([a-zA-Z0-9_-]+)/$ profile.php?user=$1

Adding the following to the above,

RewriteRule ^([a-zA-Z0-9_-]+)/section$ section.php?user=$1
RewriteRule ^([a-zA-Z0-9_-]+)/section/$ section.php?user=$1

did not resolve example.com/section.php?username=xyz to example.com/xyz/section.

Am I doing something wrong here?

Body:
To look for static files (images, css) in the right directory without having to write the file address, do:

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d

Before writing the code suggested by RageD

(Sorry, should have posted it as a comment but I needed newlines)


问:
Procedure for creating a database locally using mongodb
I've connected to mLab using MongoClient.connect, but now I want to create a local database rather than use mLab. I've tried changing the URL to "mongodb://localhost:27017/mydb" to create a database locally as suggested, but I'm getting a failed to connect to server error. Is there anything I should install? Or am I just missing something?

答:
First you need to understand how server works and mlab works. mLab is a company who provide database as a services. Means you no need to handle server hurdles, they take care server , backups , infrastructure etc. They provide mongodb server , You just need to create database on mongodb server's and use them.

Now comes to main points.

If you want use mongodb on your local system then you first need to install mongodb on your local system and then connect it.


问:
Codeigniter project is not working after installing at server
I build codeigniter project and i have tested it in my local machine using http://localhost/wg/ as base url. I upload that project to server and my new url like http://project.microsols.com/wardrobe/ Home page is working. But when i click on any other link it will give error.
It is giving

Not Found

  The requested URL /index.php/person was not found on this server.

  Additionally, a 404 Not Found error was encountered while trying to use an ErrorDocument to handle the request.

But it will work fine when i put index.php before my controller it will work fine..
And this is my .htaccess file:

```<code>RewriteEngine on
RewriteBase /wardrobe/
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d

RewriteRule ^(.*)$ index.php/$1 [L,QSA]
</code>```

What is the issue behind this error??

答:
Paste this code in your .htaccess file and then try:

```<code><IfModule mod_rewrite.c>
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php?/$1 [L]
</IfModule>
</code>```

It will work fine.

Body:
I build codeigniter project and i have tested it in my local machine using http://localhost/wg/ as base url. I upload that project to server and my new url like http://project.microsols.com/wardrobe/ Home page is working. But when i click on any other link it will give error.
It is giving

Not Found

  The requested URL /index.php/person was not found on this server.

  Additionally, a 404 Not Found error was encountered while trying to use an ErrorDocument to handle the request.

But it will work fine when i put index.php before my controller it will work fine..
And this is my .htaccess file:

RewriteEngine on
RewriteBase /wardrobe/
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d

RewriteRule ^(.*)$ index.php/$1 [L,QSA]

What is the issue behind this error??

Body:
Paste this code in your .htaccess file and then try:

<IfModule mod_rewrite.c>
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php?/$1 [L]
</IfModule>

It will work fine.


问:
What is semantics?
So there are copy semantics, move semantics and maybe more semantics that I don't know of. I have read articles about both but I still do not really get have a good definition of "semantics". As the name suggests, move semantics have something to do with moving things but why is it called move semantics?

The more clear version: What is the meaning of semantics in the context of programming? Example: Move and copy semantics.

答:
The word semantics is used to describe an underlying meaning of something.

You can say that an operation has the move semantics when it transfers an object state from one object to another. In reality of course what happens is some pointers are probably copied over and that's it, but semantically your object has been moved.

Another example is the ownership transfer, when the most important thing that is moved is the responsibility (i.e. the promise to release some resource). In that case from the computational point of view pretty much nothing happens, but semantically the ownership is transferred.

The same goes for copy semantics: you can say that passing an object to a function has copy semantics i.e. your object would be duplicated and the function will get a standalone copy with its own lifetime.

Another side of the coin is the syntax which is how you describe what you want following the rules of the language.

C++ has really flexible syntax - overloading operators, user-defined conversions,  macros and what not, so almost any desirable semantics can be attached to any particular syntax.

Title: What is semantics?


问:
Display google navigation based on given locations
I am working on google maps integration I am trying to display google navigation at present I am using the following code. I am trying to display like google navigation based on location what I pass through the api

```<code>NSURL *url=[[NSURL alloc] initWithString:[NSString stringWithFormat:@"http://maps.googleapis.com/maps/api/directions/json?origin=%f,%f&destination=%f,%f&alternateroutes=false&sensor=true" ,12.920631,77.670494,8.3075,77.2218]];
NSURLResponse *res;
NSError *err;NSURL *url=[[NSURL alloc] initWithString:[NSString stringWithFormat:@"http://maps.googleapis.com/maps/api/directions/json?origin=%f,%f&destination=%f,%f&alternateroutes=false&sensor=true" ,12.920631,77.670494,8.3075,77.2218]];
NSURLResponse *res;
NSError *err;

NSData *data=[NSURLConnection sendSynchronousRequest:[[NSURLRequest alloc] initWithURL:url] returningResponse:&res error:&err];
if(data)
{
    NSDictionary *dic=[NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
    if(dic)
    {
            NSArray *routes=dic[@"routes"];
            NSArray *legs=routes[0][@"legs"];
            NSArray *steps=legs[0][@"steps"];
            NSLog(@"the legs are:%@",steps);
            NSMutableArray *textsteps=[[NSMutableArray alloc] init];
            NSMutableArray *latlong=[[NSMutableArray alloc]init];
            for(int i=0; i< [steps count]; i++){
                NSString *html=steps[i][@"html_instructions"];
                [latlong addObject:steps[i][@"end_location"]];
                NSLog(@"the data:%@",steps[i][@"end_location"]);
                [textsteps addObject:html];
                encodedPath    = [[[steps objectAtIndex:i] valueForKey:@"polyline"] valueForKey:@"points"];
                [self polylineWithEncodedString:encodedPath];

                polyline.strokeColor = [UIColor redColor];
                polyline.strokeWidth = 2.f;
                polyline.map = mapView;
                NSLog(@"the encoded patg:%@",encodedPath);

                GMSMarker *marker1 = [[GMSMarker alloc]init];
                marker1.map = mapView;
                NSLog(@"Direction path");
}

}
else
{
    UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"" message:@"Connection Error" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:@"", nil];
    [alert show];
}
</code>```

I am expecting an output like

答:
You want to show same direction, time and everything as Google Maps do. Google Maps SDK of iOS will draw a path for you on maps.

You can use the Google Direction API to get and request for direction between source and destination. You can use GMSPolyline to draw it.

But other things, like where to take a turn, whats time is left to reach the destination and other things, you need to manage manually. If you want to show same as Google, you need to make URL and open in WebView.

You can see URLSchema documentation for more detail.

Body:
I am working on google maps integration I am trying to display google navigation at present I am using the following code. I am trying to display like google navigation based on location what I pass through the api

NSURL *url=[[NSURL alloc] initWithString:[NSString stringWithFormat:@"http://maps.googleapis.com/maps/api/directions/json?origin=%f,%f&destination=%f,%f&alternateroutes=false&sensor=true" ,12.920631,77.670494,8.3075,77.2218]];
NSURLResponse *res;
NSError *err;NSURL *url=[[NSURL alloc] initWithString:[NSString stringWithFormat:@"http://maps.googleapis.com/maps/api/directions/json?origin=%f,%f&destination=%f,%f&alternateroutes=false&sensor=true" ,12.920631,77.670494,8.3075,77.2218]];
NSURLResponse *res;
NSError *err;

NSData *data=[NSURLConnection sendSynchronousRequest:[[NSURLRequest alloc] initWithURL:url] returningResponse:&res error:&err];
if(data)
{
    NSDictionary *dic=[NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
    if(dic)
    {
            NSArray *routes=dic[@"routes"];
            NSArray *legs=routes[0][@"legs"];
            NSArray *steps=legs[0][@"steps"];
            NSLog(@"the legs are:%@",steps);
            NSMutableArray *textsteps=[[NSMutableArray alloc] init];
            NSMutableArray *latlong=[[NSMutableArray alloc]init];
            for(int i=0; i< [steps count]; i++){
                NSString *html=steps[i][@"html_instructions"];
                [latlong addObject:steps[i][@"end_location"]];
                NSLog(@"the data:%@",steps[i][@"end_location"]);
                [textsteps addObject:html];
                encodedPath    = [[[steps objectAtIndex:i] valueForKey:@"polyline"] valueForKey:@"points"];
                [self polylineWithEncodedString:encodedPath];

                polyline.strokeColor = [UIColor redColor];
                polyline.strokeWidth = 2.f;
                polyline.map = mapView;
                NSLog(@"the encoded patg:%@",encodedPath);

                GMSMarker *marker1 = [[GMSMarker alloc]init];
                marker1.map = mapView;
                NSLog(@"Direction path");
}

}
else
{
    UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"" message:@"Connection Error" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:@"", nil];
    [alert show];
}

I am expecting an output like


问:
How to use markup in an OpenLayers layer name
I have a number of data layers defined in the following manner:

```<code>var mylayer = new OpenLayers.Layer.TMS("MY LAYER NAME", "", { type: "png", getURL: my_layer_geturl, isBaseLayer: false, visibility: false, attribution: 'Some Attribution text' });
</code>```

Which I add to the map and it appears on the layer switcher and all is well etc.
However, I have noticed that the resulting HTML contains the following:

```<code><div class="dataLayersDiv">
    <input type="checkbox" id="OpenLayers.Control.LayerSwitcher_29_input_MY LAYER NAME" name="MY LAYER NAME" value="MY LAYER NAME">
    <span class="labelSpan" style="vertical-align: baseline;">MY LAYER NAME</span>
    <br>
</div>
</code>```

You will notice that the form input ID and NAME both contain the layer name verbatim. This seems a little odd to me as the ID and NAME attributes can quite easily become invalid. To compound matters, I wish to add some markup to the layer labels in order to show/hide the layer names in different languages. Having markup in the form fields is a) rubbish and b) causing IIS to complain of 'potentially unsafe requests' when a form is submitted (asp.net webforms, single form wrapping the page so can't really escape it without a load of work!)

I know how to circumvent the unsafe page request warning but my admin will throw a bit of a stop if I do. I was wondering if anyone out there knows of a way to neatly set the layer labels without interfering with the underlying control markup?

Cheers,
Steve

答:
I think you're gonna have to change the LayerSwitcher for this, creating your own markup there, in a better way... Mayby something is already going on for OL3, have you checked the coming updates?

(Tumbleweed temporarily stopped by the walls of a deserted saloon.)

Body:
I have a number of data layers defined in the following manner:

var mylayer = new OpenLayers.Layer.TMS("MY LAYER NAME", "", { type: "png", getURL: my_layer_geturl, isBaseLayer: false, visibility: false, attribution: 'Some Attribution text' });

Which I add to the map and it appears on the layer switcher and all is well etc.
However, I have noticed that the resulting HTML contains the following:

    <input type="checkbox" id="OpenLayers.Control.LayerSwitcher_29_input_MY LAYER NAME" name="MY LAYER NAME" value="MY LAYER NAME">
    MY LAYER NAME

You will notice that the form input ID and NAME both contain the layer name verbatim. This seems a little odd to me as the ID and NAME attributes can quite easily become invalid. To compound matters, I wish to add some markup to the layer labels in order to show/hide the layer names in different languages. Having markup in the form fields is a) rubbish and b) causing IIS to complain of 'potentially unsafe requests' when a form is submitted (asp.net webforms, single form wrapping the page so can't really escape it without a load of work!)

I know how to circumvent the unsafe page request warning but my admin will throw a bit of a stop if I do. I was wondering if anyone out there knows of a way to neatly set the layer labels without interfering with the underlying control markup?

Cheers,
Steve


问:
Delete some data from a .txt file and then store the rest into two lists..
I have data stored in a .txt file...

```<code>Subset 1    1   350.000 0.096
Subset 1    2   351.000 0.095
Subset 1    3   352.000 0.095
Subset 1    4   353.000 0.097
Subset 1    5   354.000 0.096
Subset 1    6   355.000 0.095
Subset 1    7   356.000 0.097
Subset 1    8   357.000 0.094
Subset 1    9   358.000 0.091
Subset 1    10  359.000 0.091
Subset 1    11  360.000 0.091
Subset 1    12  361.000 0.092
Subset 1    13  362.000 0.091
Subset 1    14  363.000 0.089
Subset 1    15  364.000 0.089
Subset 1    16  365.000 0.090
</code>```

And I want to use only the values 350, 351... and 0.096, 0.95,... . So I need in the first place to delete all the Subset 1  and number 1,2,3,4... and then store 350, 351... and 0.096, 0.95,... in two different lists in order to plot them.

What I tried to do is something like:

```<code>import io
# Load the txt file
text_file = io.open("/home/stagiaire/Bureau/01.Dark Skin.txt","r",
encoding = "utf-16")
# Read the lines and then strip
lines = text_file.readlines()
li = lines.strip(',')
# Delete "susbset1" by replacing it with nothing...
nkia = lines.replace("Subset 1","")
</code>```

But it doesn't work...Any suggestions on how I can do it ? Thank you.

答:
You're trying to apply string modifications to lists. I could fix your code, but let's take a more elegant (and one-line) approach:

I would read the line & split it (without arguments so it acts like awk, it considers the field separator as "one or more spaces or tabulations"), keep only the 2 last fields and convert them to float, all in a nested list comprehension:

```<code>coords = [[float(x) for x in l.split()[-2:]] for l in text_file]
</code>```

that gives me this list of couples:

```<code>[[350.0, 0.096], [351.0, 0.095], [352.0, 0.095], [353.0, 0.097], [354.0, 0.096], [355.0, 0.095], [356.0, 0.097], [357.0, 0.094], [358.0, 0.091], [359.0, 0.091], [360.0, 0.091], [361.0, 0.092], [362.0, 0.091], [363.0, 0.089], [364.0, 0.089], [365.0, 0.09]]
</code>```

if you really need 2 lists, after that, extract them with list comprehensions as well:

[c[0] for c in coords] and [c[1] for c in coords]

Body:
I have data stored in a .txt file...

Subset 1    1   350.000 0.096
Subset 1    2   351.000 0.095
Subset 1    3   352.000 0.095
Subset 1    4   353.000 0.097
Subset 1    5   354.000 0.096
Subset 1    6   355.000 0.095
Subset 1    7   356.000 0.097
Subset 1    8   357.000 0.094
Subset 1    9   358.000 0.091
Subset 1    10  359.000 0.091
Subset 1    11  360.000 0.091
Subset 1    12  361.000 0.092
Subset 1    13  362.000 0.091
Subset 1    14  363.000 0.089
Subset 1    15  364.000 0.089
Subset 1    16  365.000 0.090

And I want to use only the values 350, 351... and 0.096, 0.95,... . So I need in the first place to delete all the Subset 1  and number 1,2,3,4... and then store 350, 351... and 0.096, 0.95,... in two different lists in order to plot them.

What I tried to do is something like:

import io
# Load the txt file
text_file = io.open("/home/stagiaire/Bureau/01.Dark Skin.txt","r",
encoding = "utf-16")
# Read the lines and then strip
lines = text_file.readlines()
li = lines.strip(',')
# Delete "susbset1" by replacing it with nothing...
nkia = lines.replace("Subset 1","")

But it doesn't work...Any suggestions on how I can do it ? Thank you.

Body:
You're trying to apply string modifications to lists. I could fix your code, but let's take a more elegant (and one-line) approach:

I would read the line & split it (without arguments so it acts like awk, it considers the field separator as "one or more spaces or tabulations"), keep only the 2 last fields and convert them to float, all in a nested list comprehension:

coords = [[float(x) for x in l.split()[-2:]] for l in text_file]

that gives me this list of couples:

[[350.0, 0.096], [351.0, 0.095], [352.0, 0.095], [353.0, 0.097], [354.0, 0.096], [355.0, 0.095], [356.0, 0.097], [357.0, 0.094], [358.0, 0.091], [359.0, 0.091], [360.0, 0.091], [361.0, 0.092], [362.0, 0.091], [363.0, 0.089], [364.0, 0.089], [365.0, 0.09]]

if you really need 2 lists, after that, extract them with list comprehensions as well:

[c[0] for c in coords] and [c[1] for c in coords]


问:
Why Django server with Docker is running without database in postgresql?
I wonder why my server is running and why it doesn't see another database. To wit psql and \l:

```<code>                                    List of databases
    Name     |    Owner    | Encoding |   Collate   |    Ctype    |   Access privileges
-------------+-------------+----------+-------------+-------------+-----------------------
 aso         | postgres    | UTF8     | en_US.UTF-8 | en_US.UTF-8 |
 template0   | postgres    | UTF8     | en_US.UTF-8 | en_US.UTF-8 | =c/postgres          +
             |             |          |             |             | postgres=CTc/postgres
 template1   | postgres    | UTF8     | en_US.UTF-8 | en_US.UTF-8 | =c/postgres          +
             |             |          |             |             | postgres=CTc/postgres
 owner       | owner       | UTF8     | en_US.UTF-8 | en_US.UTF-8 |
(4 rows)
</code>```

My Django settings:

```<code>DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql',
        'NAME': 'postgres',
        'USER': 'postgres',
        'HOST': 'db',
        'PORT': 5432,
    }
}
</code>```

As you can see there is no database named postgres but server is running properly (save data etc.). On the other hand when I use:

```<code>DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql',
        'NAME': 'aso',
        'USER': 'postgres',
        'HOST': 'db',
        'PORT': 5432,
    }
}
</code>```

I get django.db.utils.OperationalError: FATAL:  database "aso" does not exist
Can anyone explain me this?

EDITED
@Adaikalaraj advised to create database in docker. I'm trying in this way:

init.sql:

```<code>CREATE USER postgres;
CREATE DATABASE aso;
GRANT ALL PRIVILEGES ON DATABASE aso TO postgres;
</code>```

My updated Dockerfile:

```<code>FROM python:3.6.1
ENV PYTHONUNBUFFERED 1
RUN mkdir /code
WORKDIR /code
ADD requirements.txt /code/
RUN pip3 install -r requirements.txt
ADD . /code/
FROM library/postgres
ADD init.sql /docker-entrypoint-initdb.d/
</code>```

Unfortunately I get:

```<code>db_1   | LOG:  database system was shut down at 2017-07-05 14:02:41 UTC
web_1  | /usr/local/bin/docker-entrypoint.sh: line 145: exec: python3: not found
db_1   | LOG:  MultiXact member wraparound protections are now enabled
db_1   | LOG:  autovacuum launcher started
db_1   | LOG:  database system is ready to accept connections
dockerpri_web_1 exited with code 127
</code>```

答: Here 'HOST': 'db' is running inside docker, Seems you are checking psql in your system. Either you can give your IP adress (eg: 127.0.0.1) in HOST : 127.0.0.1 or you can create the db aso in the postgres running inside docker.

Body:
I wonder why my server is running and why it doesn't see another database. To wit psql and \l:

                                    List of databases
    Name     |    Owner    | Encoding |   Collate   |    Ctype    |   Access privileges
-------------+-------------+----------+-------------+-------------+-----------------------
 aso         | postgres    | UTF8     | en_US.UTF-8 | en_US.UTF-8 |
 template0   | postgres    | UTF8     | en_US.UTF-8 | en_US.UTF-8 | =c/postgres          +
             |             |          |             |             | postgres=CTc/postgres
 template1   | postgres    | UTF8     | en_US.UTF-8 | en_US.UTF-8 | =c/postgres          +
             |             |          |             |             | postgres=CTc/postgres
 owner       | owner       | UTF8     | en_US.UTF-8 | en_US.UTF-8 |
(4 rows)

My Django settings:

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql',
        'NAME': 'postgres',
        'USER': 'postgres',
        'HOST': 'db',
        'PORT': 5432,
    }
}

As you can see there is no database named postgres but server is running properly (save data etc.). On the other hand when I use:

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql',
        'NAME': 'aso',
        'USER': 'postgres',
        'HOST': 'db',
        'PORT': 5432,
    }
}

I get django.db.utils.OperationalError: FATAL:  database "aso" does not exist
Can anyone explain me this?

EDITED
@Adaikalaraj advised to create database in docker. I'm trying in this way:

init.sql:

CREATE USER postgres;
CREATE DATABASE aso;
GRANT ALL PRIVILEGES ON DATABASE aso TO postgres;

My updated Dockerfile:

FROM python:3.6.1
ENV PYTHONUNBUFFERED 1
RUN mkdir /code
WORKDIR /code
ADD requirements.txt /code/
RUN pip3 install -r requirements.txt
ADD . /code/
FROM library/postgres
ADD init.sql /docker-entrypoint-initdb.d/

Unfortunately I get:

db_1   | LOG:  database system was shut down at 2017-07-05 14:02:41 UTC
web_1  | /usr/local/bin/docker-entrypoint.sh: line 145: exec: python3: not found
db_1   | LOG:  MultiXact member wraparound protections are now enabled
db_1   | LOG:  autovacuum launcher started
db_1   | LOG:  database system is ready to accept connections
dockerpri_web_1 exited with code 127


问:
How can I return a class from an async method
Is it possible to return a class from an async method? I get an error message that there is an GetAwaiter missing? Don't know what this means.

```<code>StatusButton.Click += async (sender, e) =>
        {
            ...
            byte[] TheResponse = new byte[1024];
            await TheResponse = client.Read(); // <---- GetAwaiter ?
        };

public class Client
{
    ...

    public async Task<byte[]> Read()
    {
        var ns = tcpClient.GetStream();
        byte[] Result = new byte[1024];
        await ns.ReadAsync(Result, 0, Result.Length);
        return Result;
    }
}
</code>```

答:
Is it possible to return a class from an async method?

Yes.

I get an error message that there is an GetAwaiter missing, what does that mean?

It means that the variable namely TheResponse was declare as a byte[], however you're attempting to assign it as a Task<byte[]>. The IDE however, has a preemptive check on the use of the async keyword and complains to you about the type you're attempting to await doesn't have the GetAwaiter method. This is because it is a byte[]. Here is an example .NET fiddle demonstrating this issue.

There are lots of little things that I want to call attention to here. First, when your return type is Task, Task<T> or any other asynchronous return type - it is best practice to name the method with the "Async" suffix, i.e.; ReadAsync. Furthermore, it wouldn't hurt to be more explicit than that. Since you're only able to return a Task<byte[]> from this method, let's call it ReadBytesAsync, yeah?

Ok, so now that we have a clearly defined client and corresponding API let us look at its usage. When you use the async keyword that enables the usage of the corresponding await keyword. These two keywords work together and can never be used alone.

Think of the Task<byte[]> as a promise that after sometime I'll give you a byte[], but you must "await" this. In your code, you're placing the await in the wrong location. Instead you should have the following:

```<code>StatusButton.Click += async (sender, e) =>
    {
        ...

        byte[] bytes = await client.ReadBytesAsync();
    };
</code>```

There is no reason to declare and initialize the variable only to attempt to reassign it, as you had done. Instead simple declare and initialize the value from the awaited response of the invocation to the .ReadBytesAsync call. Note, that without the await keyword you'd have the Task<byte[]> that represents the asynchronous operation.

Body:
Is it possible to return a class from an async method? I get an error message that there is an GetAwaiter missing? Don't know what this means.

StatusButton.Click += async (sender, e) =>
        {
            ...
            byte[] TheResponse = new byte[1024];
            await TheResponse = client.Read(); // <---- GetAwaiter ?
        };

public class Client
{
    ...

    public async Task<byte[]> Read()
    {
        var ns = tcpClient.GetStream();
        byte[] Result = new byte[1024];
        await ns.ReadAsync(Result, 0, Result.Length);
        return Result;
    }
}

Body:
Is it possible to return a class from an async method?

Yes.

I get an error message that there is an GetAwaiter missing, what does that mean?

It means that the variable namely TheResponse was declare as a byte[], however you're attempting to assign it as a Task<byte[]>. The IDE however, has a preemptive check on the use of the async keyword and complains to you about the type you're attempting to await doesn't have the GetAwaiter method. This is because it is a byte[]. Here is an example .NET fiddle demonstrating this issue.

There are lots of little things that I want to call attention to here. First, when your return type is Task, Task<T> or any other asynchronous return type - it is best practice to name the method with the "Async" suffix, i.e.; ReadAsync. Furthermore, it wouldn't hurt to be more explicit than that. Since you're only able to return a Task<byte[]> from this method, let's call it ReadBytesAsync, yeah?

Ok, so now that we have a clearly defined client and corresponding API let us look at its usage. When you use the async keyword that enables the usage of the corresponding await keyword. These two keywords work together and can never be used alone.

Think of the Task<byte[]> as a promise that after sometime I'll give you a byte[], but you must "await" this. In your code, you're placing the await in the wrong location. Instead you should have the following:

StatusButton.Click += async (sender, e) =>
    {
        ...

        byte[] bytes = await client.ReadBytesAsync();
    };

There is no reason to declare and initialize the variable only to attempt to reassign it, as you had done. Instead simple declare and initialize the value from the awaited response of the invocation to the .ReadBytesAsync call. Note, that without the await keyword you'd have the Task<byte[]> that represents the asynchronous operation.


问:
How to integrate bluemix APP ID service to python web application
I have tried the bluemix service 'APP ID' for node.js project which I downloaded from APP ID service instance only. The application runs well with Google and Facebook authentication.

But I have to apply authentication to Python Flask web application. For this,I have followed the github link . Here, I have provided 'clientid', 'secret' and 'redirect_uri' which I got from the 'Service Credentials' tab of the 'APP ID' instance in bluemix.
After running the app, I am getting login page but when I click 'Login' button then I am getting the error 'tenandid is in invalid format'.

Please suggest where I am doing wrong.

Thanks in advance !

Regards,
Rahul Modi

答:
I solved the error my self. I just provided clientId, secret, redirectUri and serverUrl in the file serviceConfig.py file of the GitHub python project.

There is need to change this file by providing the above parameters otherwise you may land into the error on the line "clientId = serviceConfig.clientId" of 'welcome.py' because clientId is not accessible from serviceConfig class. The same case for 'secret' as well. Hence, define them separately in serviceConfig.py file.

The four parameters looks like below:

serverUrl='https://appid-oauth.ng.bluemix.net/oauth/v3/1b668c6a-XXXX-XXXX-XXXX-c4633e8e0c78'

redirectUri='http://localhost:5000/afterauth'

secret='NjNiODY5NDQtOXXXXXXXXXXXXXXXXXXXXzUxNDMzNzYxYjAy'

clientId='6284418c-XXXX-XXXX-XXXX-af8bf44588ec'

All these parameters you can collect from the 'Service Credentials' tab of the 'APP ID' instance in Bluemix.

Note: No need to change anything in 'welcome.py' file.


问:
Display  in random order
In one of mine site I am displaying 3 different  into my site. Now as per my client requirement he wants to show any 1  into the site in random oder.

Is there a way that we can do it.

答:
You can achieve it by following :-

```<code> <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script>
function randomdiv()
{
var elems = $("div");
if (elems.length) {
  var keep = Math.floor(Math.random() * elems.length);
  for (var i = 0; i < elems.length; ++i) {
    if (i !== keep) {
      $(elems[i]).hide();
    }
  }
}
}
</script>
</code>```

And by adding following code on your Body tag

```<code><div id="content1"><iframe src=""></iframe>  </div>
 <div id="content2"><iframe src=""></iframe> </div>
 <div id="content3"><iframe src=""></iframe> </div>
</code>```

Title: Display <iframe> in random order

Body:
You can achieve it by following :-

 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script>
function randomdiv()
{
var elems = $("div");
if (elems.length) {
  var keep = Math.floor(Math.random() * elems.length);
  for (var i = 0; i < elems.length; ++i) {
    if (i !== keep) {
      $(elems[i]).hide();
    }
  }
}
}
</script>

And by adding following code on your Body tag

<div id="content1"><iframe src=""></iframe>  </div>
 <div id="content2"><iframe src=""></iframe> </div>
 <div id="content3"><iframe src=""></iframe> </div>


问:
webpack-dev-server opens localhost:8080/undefined
When I run $ npm run dev ("dev": "webpack-dev-server") it opens localhost:8080/undefined instead of localhost:8080 or at least localhost:8080/index.html

webpack-config.js devServer part:

devServer: {

```<code>    contentBase: path.join(__dirname, 'dist'),

    compress: true,

    stats: "errors-only",

    hot: true,

    open: true
</code>```

If I delete the /undefined part of the URL it works properly even the hot module replacement so it's not a big problem; just want to know why is that happening.

Edit: Im on MacOS

Edit2: Console info when npm run dev:

Project is running at http://localhost:8080/
webpack output is served from /
Content not from webpack is served from /Users/cozarkd/folders/dist
webpack: wait until bundle finished: /undefined
webpack: Compiled successfully.

Ty

答:
This seems to be caused by a bug: https://github.com/webpack/webpack-dev-server/issues/960

A quick workaround is offered (here):

```<code>devServer: {
  contentBase: path.join(__dirname, 'dist'),
  compress: true,
  stats: "errors-only",
  hot: true,
  open: true,
  openPage: '' // <-- this
}
</code>```

Body:
When I run $ npm run dev ("dev": "webpack-dev-server") it opens localhost:8080/undefined instead of localhost:8080 or at least localhost:8080/index.html

webpack-config.js devServer part:

devServer: {

    contentBase: path.join(__dirname, 'dist'),

    compress: true,

    stats: "errors-only",

    hot: true,

    open: true

If I delete the /undefined part of the URL it works properly even the hot module replacement so it's not a big problem; just want to know why is that happening.

Edit: Im on MacOS

Edit2: Console info when npm run dev:

Project is running at http://localhost:8080/
webpack output is served from /
Content not from webpack is served from /Users/cozarkd/folders/dist
webpack: wait until bundle finished: /undefined
webpack: Compiled successfully.

Ty

Body:
This seems to be caused by a bug: https://github.com/webpack/webpack-dev-server/issues/960

A quick workaround is offered (here):

devServer: {
  contentBase: path.join(__dirname, 'dist'),
  compress: true,
  stats: "errors-only",
  hot: true,
  open: true,
  openPage: '' // <-- this
}


问:
Are there any good 3rd party GUI products for Python?
In .Net you have companies like DevEpxress, and Infragistics that offer a range of GUI widgets.  Is there any market like that for Python GUI widgets?  I'm thinking specifically about widgets like the DevExpress xtraGrid Suite.

Edit 01-16-09:  For Example:

http://www.devexpress.com/Downloads/NET/OnlineDemos.xml
http://demos.devexpress.com/ASPxGridViewDemos/

http://www.infragistics.com/products/default.aspx

答:
There's also wxPython, which is a wrapper around wxWidgets which is quite popular, works on many platforms and liberally licensed.

QT would probably be the other one I would look at, especially now that the next release will be licensed under the LGPL.

OwnerDisplayName: mchean

LastEditorDisplayName: mchean

OwnerDisplayName: Evan

LastEditorDisplayName: Evan


问:
display dynamic tags in meta tag
On my index.php, i am trying to implode an array of meta tags loaded from MYSQL db. I am trying to echo it in <meta> tag. But it shows the last tag only. Why is it so?

html

```<code>$meta_t=mysqli_query($con,"select * from tags");
while($row1=mysqli_fetch_array($meta_t,MYSQLI_ASSOC)){
    $meta_tags=array();
    $meta_tags[]=$row1['tag_name'];
    $comma_separated = implode($meta_tags);
   }
?>

<!DOCTYPE html>
<html lang="en">
<head>

    <meta charset="utf-8" />
    <title>GripOffers</title>
    <meta name="keywords" content="<?php echo $comma_separated;?>">
</code>```

答:
set $commaa_separated value after complete while loop

```<code>$meta_tags=array();
$meta_t=mysqli_query($con,"select * from tags");
    while($row1=mysqli_fetch_array($meta_t,MYSQLI_ASSOC)){

        $meta_tags[]=$row1['tag_name'];

       }
        $comma_separated = implode($meta_tags);
    ?>
</code>```

Title: display dynamic tags in meta tag

Body:
On my index.php, i am trying to implode an array of meta tags loaded from MYSQL db. I am trying to echo it in <meta> tag. But it shows the last tag only. Why is it so?

html

$meta_t=mysqli_query($con,"select * from tags");
while($row1=mysqli_fetch_array($meta_t,MYSQLI_ASSOC)){
    $meta_tags=array();
    $meta_tags[]=$row1['tag_name'];
    $comma_separated = implode($meta_tags);
   }
?>

<!DOCTYPE html>

    <meta charset="utf-8" />
    <title>GripOffers</title>
    <meta name="keywords" content="<?php echo $comma_separated;?>">

Body:
set $commaa_separated value after complete while loop

$meta_tags=array();
$meta_t=mysqli_query($con,"select * from tags");
    while($row1=mysqli_fetch_array($meta_t,MYSQLI_ASSOC)){

        $meta_tags[]=$row1['tag_name'];

       }
        $comma_separated = implode($meta_tags);
    ?>


问:
Validate if command was successfull in a batch file or revert back all settings
Please check my batch file command as I need to dis-join computer from old domain and join it to a new one.

Sometimes computer succeeded to dis-join the computer but fails to add it in a new domain so this computer will be out of domain. I need to add command to validate if the computer is successfully joined to the new domain otherwise revert it back to the old domain.

@echo off
netdom.exe remove %computername% /domain:MyOlddomain.local /UserD:Myusername /PasswordD:Mypassword
Ping 127.0.0.1 -n 5 >nul
netdom.exe join %computername% /domain:MyNewDomain /UserD:Myusername /PasswordD:Mypassword
Ping 127.0.0.1 -n 5 >nul
shutdown -t 5 -r -f
```

答:
The best way about it is to use a IF statement.

The basic structure of a IF statement is as follows.

```<code>IF EXIST "%1" (
    echo "it's here!"
) ELSE (
    echo "it isn't here!"
)
</code>```

Going about it like this will allow you to revert when needed.
More in depth reading!

Body:
The best way about it is to use a IF statement.

The basic structure of a IF statement is as follows.

IF EXIST "%1" (
    echo "it's here!"
) ELSE (
    echo "it isn't here!"
)

Going about it like this will allow you to revert when needed.
More in depth reading!


问:
Create middle point on the EDGE of Connected Vertices' of an Object in threeJS
given Vertices array in Vector3
square vectors3 [{-1,1,0}, {1,1,0}, {-1,-1,0}, {1,-1,0}]
is there any way could be done on Matrix modification and return 4 Verctors?

enter image description here

答:
If I got you correctly, then:

```<code>var angle = Math.PI / 4; // rotate 45 deg CCW, negative angle is CW
var m = new THREE.Matrix4();
m.set(
   Math.cos(angle), Math.sin(angle), 0, 0,
  -Math.sin(angle), Math.cos(angle), 0, 0,
   0              , 0              , 1, 0,
   0              , 0              , 0, Math.sqrt(2) // diagonal length is square root of 2 times of side length
);

var originals = [
  new THREE.Vector3(-1,  1, 0),
  new THREE.Vector3( 1,  1, 0),
  new THREE.Vector3(-1, -1, 0),
  new THREE.Vector3( 1, -1, 0)
];

function applyMatrix(points, matrix4){
  var result = [];
  points.forEach((point)=>{
    result.push(point.clone().applyMatrix4(matrix4));
  })
  return result;
}

var images = applyMatrix(originals, m);
</code>```

jsfiddle example r86

PS The solution is exceptionally for what you gave in the picture.

Body:
If I got you correctly, then:

var angle = Math.PI / 4; // rotate 45 deg CCW, negative angle is CW
var m = new THREE.Matrix4();
m.set(
   Math.cos(angle), Math.sin(angle), 0, 0,
  -Math.sin(angle), Math.cos(angle), 0, 0,
   0              , 0              , 1, 0,
   0              , 0              , 0, Math.sqrt(2) // diagonal length is square root of 2 times of side length
);

var originals = [
  new THREE.Vector3(-1,  1, 0),
  new THREE.Vector3( 1,  1, 0),
  new THREE.Vector3(-1, -1, 0),
  new THREE.Vector3( 1, -1, 0)
];

function applyMatrix(points, matrix4){
  var result = [];
  points.forEach((point)=>{
    result.push(point.clone().applyMatrix4(matrix4));
  })
  return result;
}

var images = applyMatrix(originals, m);

jsfiddle example r86

PS The solution is exceptionally for what you gave in the picture.


问:
Cannot retrieve paper-input value in JS - WHY?
Literally no idea what is going on here. It worked in one file on my computer and doesn't in another...

Using an if statement to decide whether a div should be expanded or not, I am using the content of a paper-input to be the boolean operator.

The JS issue is that the value of the input is "undefined"

Please help!

```<code><paper-input id="searchMe" class="searchMe" name="searchMe" placeholder="Enter your search here..." on-input="inputText">
      <div suffix>
        <paper-icon-button class="clear" id="clearIcon" icon="clear" on-click="clearInput" style="display: none;"></paper-icon-button>
        <paper-icon-button id="searchIcon" class="search" icon="search" on-click="searchClick"></paper-icon-button>
      </div>
</paper-input>
</code>```

JS

```<code>if(this.$.searchMe.value == "") {
   /* expand div */
}
</code>```

答:
Try this

```<code><paper-input id="searchMe" class="searchMe" name="searchMe" placeholder="Enter your search here..." on-input="inputText" value="{{search}}">
</code>```

And this

```<code>if(this.search == "") {
</code>```

Body:
Literally no idea what is going on here. It worked in one file on my computer and doesn't in another...

Using an if statement to decide whether a div should be expanded or not, I am using the content of a paper-input to be the boolean operator.

The JS issue is that the value of the input is "undefined"

Please help!

<paper-input id="searchMe" class="searchMe" name="searchMe" placeholder="Enter your search here..." on-input="inputText">

        <paper-icon-button class="clear" id="clearIcon" icon="clear" on-click="clearInput" style="display: none;"></paper-icon-button>
        <paper-icon-button id="searchIcon" class="search" icon="search" on-click="searchClick"></paper-icon-button>

</paper-input>

JS

if(this.$.searchMe.value == "") {
   /* expand div */
}

Body:
Try this

<paper-input id="searchMe" class="searchMe" name="searchMe" placeholder="Enter your search here..." on-input="inputText" value="{{search}}">

And this

if(this.search == "") {


问:
Jquery Editable input textbox field
I have created this simple form

```<code><html>
<head>
 <title>Datatable</title>
 <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css">
  <script type="text/javascript" src="../jquery-1.11.3.min.js"></script>
  <script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/js/bootstrap.min.js"></script>
  <script type="text/javascript" src="../jquery/Jobseeker/EditDatatable.js"></script>
</head>

<body>
<form>
<table id="example">
<tr>
<td>
<label>Ab Va</label>
</td>
<td>
<input type="text" value="99"/>
</td>
</tr>
<tr>
<td>
<label>Sa Va</label>
</td>
<td>
<input type="text" value="9986"/>
</td>
</tr>

</table>
<button id="btn">Edit</button>
</form>
</body>
</html>
</code>```

The jquery code to edit the input textbox of this table is

```<code>$(document).ready(function() {
    var table = $('#example').DataTable();

    $('button').click( function() {
        var data = table.$('input, select').serialize();
        alert(
            "The following data would have been submitted to the server: \n\n"+

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

The problem what I am facing is the input textbox field id editable without click of the button "Edit".
But I want it to be editable only when the user clicks on the Edit button.
Please let me know how can i do this

答:
you can add disabled attribute to input and then remove it on btn click.</p>

```<code><input type="text" value="99" disabled/>

<input type="text" value="9986" disabled/>

$(document).ready(function() {
    var table = $('#example').DataTable();

    $('button').click( function() {
        $('input').removeAttr('disabled');
        var data = table.$('input, select').serialize();
        alert("The following data would have been submitted to the server: \n\n");
        return false;
    } );
} );
</code>```

Title: Jquery Editable input textbox field

Body:
I have created this simple form

 <title>Datatable</title>
 <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css">

<form>

Ab Va

<input type="text" value="99"/>

Sa Va

<input type="text" value="9986"/>

<button id="btn">Edit</button>
</form>

The jquery code to edit the input textbox of this table is

$(document).ready(function() {
    var table = $('#example').DataTable();

    $('button').click( function() {
        var data = table.$('input, select').serialize();
        alert(
            "The following data would have been submitted to the server: \n\n"+

        );
        return false;
    } );
} );

The problem what I am facing is the input textbox field id editable without click of the button "Edit".
But I want it to be editable only when the user clicks on the Edit button.
Please let me know how can i do this

Body:
you can add disabled attribute to input and then remove it on btn click.

<input type="text" value="99" disabled/>

<input type="text" value="9986" disabled/>

$(document).ready(function() {
    var table = $('#example').DataTable();

    $('button').click( function() {
        $('input').removeAttr('disabled');
        var data = table.$('input, select').serialize();
        alert("The following data would have been submitted to the server: \n\n");
        return false;
    } );
} );


问:
Error is occurring in my interstitial ad code for AdMob when i am using my own ad unit id
I am new to AdMob i added app name and platform in admob account.In this app i have added unit ad of interstitial ad.And created its ad unit id.

Now in android studio i have wrote simple code as per the instructions from AdMob.
So when button gets clicked it shows ad perfectly when i use the testing ad unit id but when i use my own created id its not getting load and the logcat shows as follows:

```<code>07-04 23:47:25.165 17901-17914/h.safmical.kk W/Ads: There was a problem getting an ad response. ErrorCode: 0
07-04 23:47:25.169 17901-17901/h.safmical.kk W/Ads: Failed to load ad: 0
07-04 23:47:25.169 17901-17901/h.safmical.kk I/Ads: onAdFailedToLoad
07-04 23:47:33.028 17901-17901/h.safmical.kk D/TAG: The interstitial wasn't loaded yet.
07-04 23:50:57.947 17901-18143/h.safmical.kk E/Surface: getSlotFromBufferLocked: unknown buffer: 0xb9aabcf0
</code>```

My mainactivity:

MainActivity.java:

```<code>package h.safmical.kk;

import android.app.Activity;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;

import com.google.android.gms.ads.AdListener;
import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.InterstitialAd;

public class MainActivity extends Activity {
    private InterstitialAd mInterstitialAd;

    Button click;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mInterstitialAd = new InterstitialAd(this);
        mInterstitialAd.setAdUnitId("*************************");
        mInterstitialAd.loadAd(new AdRequest.Builder().build());

        click = (Button) findViewById(R.id.click);
        click.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mInterstitialAd.isLoaded()) {
                    mInterstitialAd.show();
                } else {
                    Log.d("TAG", "The interstitial wasn't loaded yet.");
                }
            }
        });

        mInterstitialAd.setAdListener(new AdListener() {
            @Override
            public void onAdLoaded() {
               Log.i("Ads", "onAdLoaded");
            }

            @Override
            public void onAdFailedToLoad(int errorCode) {
              Log.i("Ads", "onAdFailedToLoad");
            }

            @Override
            public void onAdOpened() {
            Log.i("Ads", "onAdOpened");
            }

            @Override
            public void onAdLeftApplication() {
            Log.i("Ads", "onAdLeftApplication");
            }

            @Override
            public void onAdClosed() {
              mInterstitialAd.loadAd(new AdRequest.Builder().build());
            }
        });
    }
}
</code>```

My Gradle file:

```<code>apply plugin: 'com.android.application'

android {
    compileSdkVersion 25
    buildToolsVersion "25.0.2"
    defaultConfig {
        applicationId "h.safmical.kk"
        minSdkVersion 15
        targetSdkVersion 25
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
        exclude group: 'com.android.support', module: 'support-annotations'
    })
    compile 'com.android.support:appcompat-v7:25.3.1'
    compile 'com.android.support.constraint:constraint-layout:1.0.2'
    compile 'com.google.android.gms:play-services-ads:10.2.4'
    testCompile 'junit:junit:4.12'
}
</code>```

Please help me to solve this.

答: If its working fine with the test id then there is no error in the code. Try generating a signed apk of your app and then run it with your own id. It worked in my case.</p>

Body:
I am new to AdMob i added app name and platform in admob account.In this app i have added unit ad of interstitial ad.And created its ad unit id.

Now in android studio i have wrote simple code as per the instructions from AdMob.
So when button gets clicked it shows ad perfectly when i use the testing ad unit id but when i use my own created id its not getting load and the logcat shows as follows:

07-04 23:47:25.165 17901-17914/h.safmical.kk W/Ads: There was a problem getting an ad response. ErrorCode: 0
07-04 23:47:25.169 17901-17901/h.safmical.kk W/Ads: Failed to load ad: 0
07-04 23:47:25.169 17901-17901/h.safmical.kk I/Ads: onAdFailedToLoad
07-04 23:47:33.028 17901-17901/h.safmical.kk D/TAG: The interstitial wasn't loaded yet.
07-04 23:50:57.947 17901-18143/h.safmical.kk E/Surface: getSlotFromBufferLocked: unknown buffer: 0xb9aabcf0

My mainactivity:

MainActivity.java:

package h.safmical.kk;

import android.app.Activity;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;

import com.google.android.gms.ads.AdListener;
import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.InterstitialAd;

public class MainActivity extends Activity {
    private InterstitialAd mInterstitialAd;

    Button click;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mInterstitialAd = new InterstitialAd(this);
        mInterstitialAd.setAdUnitId("*************************");
        mInterstitialAd.loadAd(new AdRequest.Builder().build());

        click = (Button) findViewById(R.id.click);
        click.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mInterstitialAd.isLoaded()) {
                    mInterstitialAd.show();
                } else {
                    Log.d("TAG", "The interstitial wasn't loaded yet.");
                }
            }
        });

        mInterstitialAd.setAdListener(new AdListener() {
            @Override
            public void onAdLoaded() {
               Log.i("Ads", "onAdLoaded");
            }

            @Override
            public void onAdFailedToLoad(int errorCode) {
              Log.i("Ads", "onAdFailedToLoad");
            }

            @Override
            public void onAdOpened() {
            Log.i("Ads", "onAdOpened");
            }

            @Override
            public void onAdLeftApplication() {
            Log.i("Ads", "onAdLeftApplication");
            }

            @Override
            public void onAdClosed() {
              mInterstitialAd.loadAd(new AdRequest.Builder().build());
            }
        });
    }
}

My Gradle file:

apply plugin: 'com.android.application'

android {
    compileSdkVersion 25
    buildToolsVersion "25.0.2"
    defaultConfig {
        applicationId "h.safmical.kk"
        minSdkVersion 15
        targetSdkVersion 25
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
        exclude group: 'com.android.support', module: 'support-annotations'
    })
    compile 'com.android.support:appcompat-v7:25.3.1'
    compile 'com.android.support.constraint:constraint-layout:1.0.2'
    compile 'com.google.android.gms:play-services-ads:10.2.4'
    testCompile 'junit:junit:4.12'
}

Please help me to solve this.


问:
visual c++ 2010 can't add resource file
i want to add to my project a resource file but vs2010 won't let me.
what do i do?

答: If you use Express Edition, then you can't compile resources (may be it is a reason, why you can't add them too).</p>

Title: visual c++ 2010 can't add resource file


问:
Is there a better way to DELETE 80 million+ rows from a table?
Is there a better way to DELETE 80 million+ rows from a table? </p>

```<code>WHILE EXISTS (SELECT TOP 1 * FROM large_table)
    BEGIN
        WITH LT AS
            (
                SELECT TOP 60000 *
                FROM large_table
            )
        DELETE FROM LT
    END
</code>```

<p>This does the job of keeping my transaction logs from becoming too large, but I need to know if there is a way to make this process go faster? I've had my computer on for 5+ days now running this script and I haven't gotten very far, very fast. </p>

答:
You can truncate the table simply by.

```<code>TRUNCATE TABLE large_table
GO
</code>```

You can also use delete by using where condition. The time taken by delete depends on various aspects. You can reduce the cost by eliminating SELECT query in the condition of WHILE loop.

```<code>DECLARE @rows INT = 1

WHILE (@rows>0)
BEGIN

   DELETE TOP 1000 *
   FROM large_table

   @rows = @@ROWCOUNT

END
</code>```

Body:
Is there a better way to DELETE 80 million+ rows from a table?

WHILE EXISTS (SELECT TOP 1 * FROM large_table)
    BEGIN
        WITH LT AS
            (
                SELECT TOP 60000 *
                FROM large_table
            )
        DELETE FROM LT
    END

This does the job of keeping my transaction logs from becoming too large, but I need to know if there is a way to make this process go faster? I've had my computer on for 5+ days now running this script and I haven't gotten very far, very fast.

Body:
You can truncate the table simply by.

TRUNCATE TABLE large_table
GO

You can also use delete by using where condition. The time taken by delete depends on various aspects. You can reduce the cost by eliminating SELECT query in the condition of WHILE loop.

DECLARE @rows INT = 1

WHILE (@rows>0)
BEGIN

   DELETE TOP 1000 *
   FROM large_table

   @rows = @@ROWCOUNT

END


问:
How to compare current item with the next item in foreach asp.net
I have a question.

I have model, and I show in the page this model thanks to foreach. And in the model I have column (vPeriod) and I need to compare current item (e.g vPeriod = 2016) with next item (e.g. vPeriod = 2017) and I don't know how to compare!

```<code>foreach(var item in Model)
{
if(current.vPeriod == next.vPeriod)
{
//do something
}
else
{
//do something
}
}
</code>```

If I use for, it's the easy way. But how do I do this with foreach?

Code view:

```<code> <tr class="line2">
                <td></td>
                <td></td>
                <td></td>
                <td></td>
                <td style="color: #5f6877;">2016</td>
                <td></td>
                <td></td>
                <td></td>
                <td></td>
            </tr>

@foreach (var itemData in Model)
            {
                if (itemData.vPeriod == "2016")
                {
                    <tr class="line3">
                        <td>@itemData.vAddress</td>
                        <td>@itemData.vCreateDate</td>
                        <td>@itemData.iCountOfFloors</td>
                        <td>@itemData.iCountOfRooms</td>
                        <td>@itemData.iAreaOfRooms</td>
                        <td>@itemData.vLastRepairs</td>
                        <td>@itemData.vType</td>
                        <td>@itemData.vBelonging</td>
                        <td>@itemData.vPlanRepairs</td>
                    </tr>
                }
            }

            <tr class="line2">
                <td></td>
                <td></td>
                <td></td>
                <td></td>
                <td style="color: #5f6877;">2017</td>
                <td></td>
                <td></td>
                <td></td>
                <td></td>
            </tr>

            @foreach (var itemData in Model)
            {
                if (itemData.vPeriod == "2017")
                {
                    <tr class="line3">
                        <td>@itemData.vAddress</td>
                        <td>@itemData.vCreateDate</td>
                        <td>@itemData.iCountOfFloors</td>
                        <td>@itemData.iCountOfRooms</td>
                        <td>@itemData.iAreaOfRooms</td>
                        <td>@itemData.vLastRepairs</td>
                        <td>@itemData.vType</td>
                        <td>@itemData.vBelonging</td>
                        <td>@itemData.vPlanRepairs</td>
                    </tr>
                }
            }
</code>```

It's like really awful! I can have many different years and all the time need to create a block with data and a `foreach block for year.

答:
You can't access the next element using foreach loop. Rather you should use for loop and on the basis of array index you can compare the two values. Use something like this

```<code>for(int i=0; i<Model.Count-1; i++)
{
   list[i] != list.Last() ? Compare(list[i], list[i+1]) : break;
}
</code>```

Hope this helps!

Body:
I have a question.

I have model, and I show in the page this model thanks to foreach. And in the model I have column (vPeriod) and I need to compare current item (e.g vPeriod = 2016) with next item (e.g. vPeriod = 2017) and I don't know how to compare!

foreach(var item in Model)
{
if(current.vPeriod == next.vPeriod)
{
//do something
}
else
{
//do something
}
}

If I use for, it's the easy way. But how do I do this with foreach?

Code view:

                2016

@foreach (var itemData in Model)
            {
                if (itemData.vPeriod == "2016")
                {

                        @itemData.vAddress
                        @itemData.vCreateDate
                        @itemData.iCountOfFloors
                        @itemData.iCountOfRooms
                        @itemData.iAreaOfRooms
                        @itemData.vLastRepairs
                        @itemData.vType
                        @itemData.vBelonging
                        @itemData.vPlanRepairs

                }
            }

                2017

            @foreach (var itemData in Model)
            {
                if (itemData.vPeriod == "2017")
                {

                        @itemData.vAddress
                        @itemData.vCreateDate
                        @itemData.iCountOfFloors
                        @itemData.iCountOfRooms
                        @itemData.iAreaOfRooms
                        @itemData.vLastRepairs
                        @itemData.vType
                        @itemData.vBelonging
                        @itemData.vPlanRepairs

                }
            }

It's like really awful! I can have many different years and all the time need to create a block with data and a `foreach block for year.

Body:
You can't access the next element using foreach loop. Rather you should use for loop and on the basis of array index you can compare the two values. Use something like this

for(int i=0; i<Model.Count-1; i++)
{
   list[i] != list.Last() ? Compare(list[i], list[i+1]) : break;
}

Hope this helps!


问:
No authorization token was found in node authorisation
I am using JWT for authenticating requests for the back-end api and it results in a unexpected error.

```<code>const generateJwt = function(rows) {
var expiry = new Date();
expiry.setDate(expiry.getDate() + 7);

return jwt.sign({
    _id: 1,
    email: rows.email,
    name: rows.username,
    exp: parseInt(expiry.getTime() / 1000),
}, "MY_SECRET"); // DO NOT KEEP YOUR SECRET IN THE CODE!
</code>```

};

I am using the above code to generate the jwt and it generates successfully.

```<code>var jwt = require('express-jwt');
var auth = jwt({
secret: 'MY_SECRET',
userProperty: 'payload'
});

var router = express.Router();

router.get('/list',auth, controller.getMerchantList);
</code>```

after a user is logged in I return the jwt token and I send the token when the client makes calls to the back-end.

```<code>$http.get('/api/merchant/list',{
  headers: {
    Authorization: 'Bearer '+ authentication.getToken()
  }
});
</code>```

The generated token : eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJfaWQiOjEsImVtYWlsIjoia2FzaGlmcm9zaGVuN0BnbWFpbC5jb20iLCJuYW1lIjoiQXJ5YSBTdGFyayIsImV4cCI6MTQ5OTg0NjEzOSwiaWF0IjoxNDk5MjQxMzM5fQ.-CCQwiadozSOuuIk9fil4aJh8D38NwgKYP3HpvClyKw

But I still get a 401. The jwt token is there in the front-end. I verified through a console.log. Can someone please help me solve this.

答:
```<code>const Jwt=require('jsonwebtoken');

function generateToken(rows,callback){
    let tokenData={ _id: 1,
    email: rows.email,
    name: rows.username
    }
    return Jwt.sign(tokenData,"YOUR-SECRET-KEY",{ expiresIn: 60 * 60 },function(err,token){
        if(err) callback(err);
        else callback(null,token);
})
}
</code>```

Send this token to the client.
When receiving the token in the headers from the client. You need to verify that token using Jwt verify method. Your auth middleware should take the token from the headers and verify it.

```<code>function auth(req,res,callback){
    let token=req.headers.authorization;
    Jwt.verify(token,"YOUR-SECRET-KEY",function(err,decodedData){
        if(err)
            callback(err); // you can send your custom error too
        else
            callback(null,decodedData);
        }
    )

}
</code>```

Body:
I am using JWT for authenticating requests for the back-end api and it results in a unexpected error.

const generateJwt = function(rows) {
var expiry = new Date();
expiry.setDate(expiry.getDate() + 7);

return jwt.sign({
    _id: 1,
    email: rows.email,
    name: rows.username,
    exp: parseInt(expiry.getTime() / 1000),
}, "MY_SECRET"); // DO NOT KEEP YOUR SECRET IN THE CODE!

};

I am using the above code to generate the jwt and it generates successfully.

var jwt = require('express-jwt');
var auth = jwt({
secret: 'MY_SECRET',
userProperty: 'payload'
});

var router = express.Router();

router.get('/list',auth, controller.getMerchantList);

after a user is logged in I return the jwt token and I send the token when the client makes calls to the back-end.

$http.get('/api/merchant/list',{
  headers: {
    Authorization: 'Bearer '+ authentication.getToken()
  }
});

The generated token : eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJfaWQiOjEsImVtYWlsIjoia2FzaGlmcm9zaGVuN0BnbWFpbC5jb20iLCJuYW1lIjoiQXJ5YSBTdGFyayIsImV4cCI6MTQ5OTg0NjEzOSwiaWF0IjoxNDk5MjQxMzM5fQ.-CCQwiadozSOuuIk9fil4aJh8D38NwgKYP3HpvClyKw

But I still get a 401. The jwt token is there in the front-end. I verified through a console.log. Can someone please help me solve this.

Body:
const Jwt=require('jsonwebtoken');

function generateToken(rows,callback){
    let tokenData={ _id: 1,
    email: rows.email,
    name: rows.username
    }
    return Jwt.sign(tokenData,"YOUR-SECRET-KEY",{ expiresIn: 60 * 60 },function(err,token){
        if(err) callback(err);
        else callback(null,token);
})
}

Send this token to the client.
When receiving the token in the headers from the client. You need to verify that token using Jwt verify method. Your auth middleware should take the token from the headers and verify it.

function auth(req,res,callback){
    let token=req.headers.authorization;
    Jwt.verify(token,"YOUR-SECRET-KEY",function(err,decodedData){
        if(err)
            callback(err); // you can send your custom error too
        else
            callback(null,decodedData);
        }
    )

}


问:
Add key values dynamically to nested object in Javascript
This might be a duplicate of this but did not get proper solution over there. I have object as below,

```<code>var replyDataObj = {

                  "department": {
                    "name": getCache("departmentName")
                  },
                  "subject": replyEmailSubject,
                  "payload": {
                    "email": {
                      "contents": {
                        "content": [
                          {
                            "type": "html",
                            "value": replyEmailContent
                          }
                        ]
                      },
                      "emailAddresses": {
                        "from": fromEmailId,
                        "to": {
                          "address": [
                            toEmailId
                          ]
                        }
                      }
                    }
                  }
            }
</code>```

I want to add following key values to 'emailAddresses' key dynamically depending upon whether cc field is present or not,

```<code>"cc": {
         "address": [
           ccEmailId
          ]
      }
</code>```

So it will look like,

```<code>var replyDataObj = {

              "department": {
                "name": getCache("departmentName")
              },
              "subject": replyEmailSubject,
              "payload": {
                "email": {
                  "contents": {
                    "content": [
                      {
                        "type": "html",
                        "value": replyEmailContent
                      }
                    ]
                  },
                  "emailAddresses": {
                    "from": fromEmailId,
                    "to": {
                      "address": [
                        toEmailId
                      ],
                    "cc": {
                      "address": [
                         ccEmailId
                        ]
                      }
                    }
                  }
                }
              }
        }
</code>```

I tried to add this using object[key] as below, object.key but no luck

```<code>replyDataObj[payload][emailAddresses][cc]={
     "address": [
       ccEmailId
      ]
  }
</code>```

I tried multiple ways and searched a lot but did not get the solution. Any help in this regard will be greatly appreciated. Thank you.

答:
As answered by @K.Kirsz, I was missing strings inside [] (quotes). Also added missing 'email' key to solve my issue.</p>

```<code>replyDataObj['payload']['email']['emailAddresses']['cc']={
 "address": [
   ccEmailId
  ]
}
</code>```

Body:
This might be a duplicate of this but did not get proper solution over there. I have object as below,

var replyDataObj = {

                  "department": {
                    "name": getCache("departmentName")
                  },
                  "subject": replyEmailSubject,
                  "payload": {
                    "email": {
                      "contents": {
                        "content": [
                          {
                            "type": "html",
                            "value": replyEmailContent
                          }
                        ]
                      },
                      "emailAddresses": {
                        "from": fromEmailId,
                        "to": {
                          "address": [
                            toEmailId
                          ]
                        }
                      }
                    }
                  }
            }

I want to add following key values to 'emailAddresses' key dynamically depending upon whether cc field is present or not,

"cc": {
         "address": [
           ccEmailId
          ]
      }

So it will look like,

var replyDataObj = {

              "department": {
                "name": getCache("departmentName")
              },
              "subject": replyEmailSubject,
              "payload": {
                "email": {
                  "contents": {
                    "content": [
                      {
                        "type": "html",
                        "value": replyEmailContent
                      }
                    ]
                  },
                  "emailAddresses": {
                    "from": fromEmailId,
                    "to": {
                      "address": [
                        toEmailId
                      ],
                    "cc": {
                      "address": [
                         ccEmailId
                        ]
                      }
                    }
                  }
                }
              }
        }

I tried to add this using object[key] as below, object.key but no luck

replyDataObj[payload][emailAddresses][cc]={
     "address": [
       ccEmailId
      ]
  }

I tried multiple ways and searched a lot but did not get the solution. Any help in this regard will be greatly appreciated. Thank you.

Body:
As answered by @K.Kirsz, I was missing strings inside [] (quotes). Also added missing 'email' key to solve my issue.

replyDataObj['payload']['email']['emailAddresses']['cc']={
 "address": [
   ccEmailId
  ]
}