问:
Unable set inputAccessoryView toolbar in Pickerview
in swift 3, i am unable set toolbar in pickerview like

pickerFilter?.inputAccessoryView = barAccessory

error is that inputAccessoryView is get-only property.

and When i am addsubview in Pickerview. toolbar is shown but done button not clickable

any solution?

答:
```<code>let flexiblespace = UIBarButtonItem(barButtonSystemItem:.flexibleSpace , target: nil, action: nil)

    let btnDone = UIBarButtonItem(barButtonSystemItem: .done, target: self, action: #selector(self.donePresed))
    let barAccessory = UIToolbar(frame: CGRect(x: 0, y: 0, width: viewPicker.frame.size.width, height: 44))
    barAccessory.barStyle = .default
    barAccessory.isTranslucent = true
    barAccessory.items = [flexiblespace,btnDone]

    viewPicker.addSubview(pickerDrpDown!)
    viewPicker.addSubview(barAccessory)
</code>```


来源: stackexchange

问:
Using EXSLT in Xalan
i use Xalan as XLST-Processor inside the application server wildfly. Everything works fine so far, but when I try to use date and time functions from exlst, i got NoClassDefFoundError and I don't know why.

The definition is:

```<code><xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:datetime="http://exslt.org/dates-and-times" version="1.0"">
</code>```

When I try to use the year-function datetime:year i got the error. Any Ideas why the class can not be found?
Thank you!

答:
```<code><xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:date="http://exslt.org/dates-and-times"">
</code>```

In the docs here they, are always using "date" and not "datetime"

ContentLicense: CC BY-SA 3.0

Title: Using EXSLT in Xalan

Body:
i use Xalan as XLST-Processor inside the application server wildfly. Everything works fine so far, but when I try to use date and time functions from exlst, i got NoClassDefFoundError and I don't know why.

The definition is:

<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:datetime="http://exslt.org/dates-and-times" version="1.0"">

When I try to use the year-function datetime:year i got the error. Any Ideas why the class can not be found?
Thank you!

Body:
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:date="http://exslt.org/dates-and-times"">

In the docs here they, are always using "date" and not "datetime"


问:
How to use ssh for gitlab scheduled jobs
We recently changed our repo to use SSH and now our scheduled jobs wont run
This is the error we are seeing

```<code>Running with gitlab-runner 10.2.0 (0a75cdd1)
  on ff (4b9268cd)
Using Shell executor...
Running on pro1.staging.cardstream.net...
Cloning repository...
Cloning into '/home/gitlab-runner/builds/4b9268cd/0/Graham/QA_TEST'...
fatal: repository 'http://gitlab-ci-token:xxxxxxxxxxxxxxxxxxxx@dev.cardstream.com/Graham/QA_TEST.git/' not found
ERROR: Job failed: exit status 1
</code>```

I would be grateful if someone could shed some light on this

Thanks

答:
It seems that I have misunderstood after being misled by various internet postings.

It not possible to have gitlab use ssh when cloning a project within a job

Body:
We recently changed our repo to use SSH and now our scheduled jobs wont run
This is the error we are seeing

Running with gitlab-runner 10.2.0 (0a75cdd1)
  on ff (4b9268cd)
Using Shell executor...
Running on pro1.staging.cardstream.net...
Cloning repository...
Cloning into '/home/gitlab-runner/builds/4b9268cd/0/Graham/QA_TEST'...
fatal: repository 'http://gitlab-ci-token:xxxxxxxxxxxxxxxxxxxx@dev.cardstream.com/Graham/QA_TEST.git/' not found
ERROR: Job failed: exit status 1

I would be grateful if someone could shed some light on this

Thanks


问:
UIButton with a single rounded corner
I would like to know how can I create something that looks like what the Twitter guys put in their UITableView.

The screenshot is the following:

What I am referring to are the four-cells-in-one that looks so good to summarise things up.
Do you have any clue? I though about UIBezierPath but I can't achieve that.

My idea is to create 4 png files and then apply those images to 4 buttons and drop them in a cell. I can't use Photoshop, really. I'm so denied.

Thank you for any suggestions/hunches you can give to me

答: The easiest way is indeed to use PNG images and a UIButton with a buttonType of UIButtonTypeCustom. Have a look at Opacity, a cheaper and simpler alternative to Photoshop with great support for iOS - I couldn't live without it!

ContentLicense: CC BY-SA 2.5

Title: UIButton with a single rounded corner


问:
How to set onClick on Notification(Firebase)
I want to set onclick on notification to go to specific activity that i getting from backend.(FireBase). At present when i clicking on notification it open application launcher activity. </p>

答:
if you are sending {"notification":""} data from back end android will show a notification in the notification tray automatically(only if you  integrated FCM sdk).

If you want to take control over the notification,don't send notification object from backend,send only data object(if you are sending notification from firebase console for testing,notification object will be there by default)

Now onMessageReceived() method will be executed whenever you send notification without notification object

```<code>    @Override
    public void onMessageReceived(RemoteMessage remoteMessage) {
        String data=remoteMessage.getData();
        //parse data and show notification
        showNotification(parsedMessageData);
    }

    private void sendNotification(String message) {
        Intent intent = new Intent(this, MainActivity.class);
        intent.putExtra("showNotification", true);
        intent.putExtra("params", params);
        if (page != null && page.equals(VIEW_INDENT)) {
            intent.putExtra("page", HomeNavigationController.DISPLAY_INDENT_TAG);
        }else if(page != null && page.equals(PAYMENT_SUMMERY)){
            intent.putExtra("page", HomeNavigationController.DISPLAY_PAYMENT_SUMMERY_TAG);
            intent.putExtra("month",paymentParams.getMonth());
            intent.putExtra("year",paymentParams.getYear());
            intent.putExtra("slotId",paymentParams.getSlotId());
        }
        else {
            intent.putExtra("page", HomeNavigationController.PRODUCT_LIST_TAG);
        }

        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        PendingIntent pendingIntent = PendingIntent.getActivity(this, 0 /* Request code */, intent,
                PendingIntent.FLAG_ONE_SHOT);

        Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
        NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
                .setSmallIcon(R.drawable.farm_taaza_logo)
                .setContentTitle("Sample Notification")
                .setStyle(new NotificationCompat.BigTextStyle().bigText(message))
                .setContentText(message)
                .setAutoCancel(true)
                .setSound(defaultSoundUri)
                .setContentIntent(pendingIntent);

        NotificationManager notificationManager =
                (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

        notificationManager.notify(0 /* ID of notification */, notificationBuilder.build());
    }
</code>```

Main Activity will be started with the passed arguments as putExtra and from there you can route to the corresponding Activity according to the parameteres.

Body:
if you are sending {"notification":""} data from back end android will show a notification in the notification tray automatically(only if you  integrated FCM sdk).

If you want to take control over the notification,don't send notification object from backend,send only data object(if you are sending notification from firebase console for testing,notification object will be there by default)

Now onMessageReceived() method will be executed whenever you send notification without notification object

    @Override
    public void onMessageReceived(RemoteMessage remoteMessage) {
        String data=remoteMessage.getData();
        //parse data and show notification
        showNotification(parsedMessageData);
    }

    private void sendNotification(String message) {
        Intent intent = new Intent(this, MainActivity.class);
        intent.putExtra("showNotification", true);
        intent.putExtra("params", params);
        if (page != null && page.equals(VIEW_INDENT)) {
            intent.putExtra("page", HomeNavigationController.DISPLAY_INDENT_TAG);
        }else if(page != null && page.equals(PAYMENT_SUMMERY)){
            intent.putExtra("page", HomeNavigationController.DISPLAY_PAYMENT_SUMMERY_TAG);
            intent.putExtra("month",paymentParams.getMonth());
            intent.putExtra("year",paymentParams.getYear());
            intent.putExtra("slotId",paymentParams.getSlotId());
        }
        else {
            intent.putExtra("page", HomeNavigationController.PRODUCT_LIST_TAG);
        }

        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        PendingIntent pendingIntent = PendingIntent.getActivity(this, 0 /* Request code */, intent,
                PendingIntent.FLAG_ONE_SHOT);

        Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
        NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
                .setSmallIcon(R.drawable.farm_taaza_logo)
                .setContentTitle("Sample Notification")
                .setStyle(new NotificationCompat.BigTextStyle().bigText(message))
                .setContentText(message)
                .setAutoCancel(true)
                .setSound(defaultSoundUri)
                .setContentIntent(pendingIntent);

        NotificationManager notificationManager =
                (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

        notificationManager.notify(0 /* ID of notification */, notificationBuilder.build());
    }

Main Activity will be started with the passed arguments as putExtra and from there you can route to the corresponding Activity according to the parameteres.


问:
How can I get the returned value from the child_process.exec in javascript?
I tried the following code, it shows the res is undefined.
How can I return the stdout?</p>

```<code>function run_shell_command(command)
{
    var res
    exec(command, function(err,stdout,stderr){
     if(err) {
        console.log('shell error:'+stderr);
    } else {
        console.log('shell successful');
    }
    res = stdout
    // console.log(stdout)
    });
    return res
}
</code>```

答:
Your function looks asynchrone, so to get your response outside run_shell_command, you have to use a callback  function like this :

```<code>function run_shell_command(command, callback) {
    exec(command, function (err, stdout, stderr) {
        if (err) {
            callback(stderr, null);
        } else {
            callback(null, stdout);
        }
    });
}

run_shell_command(command, function (err, res) {
    if (err) {
        // Do something with your error
    }
    else {
        console.log(res);
    }
});
</code>```

You also can simplify your run_shell_command function like this :

```<code>function run_shell_command(command, callback) {
    exec(command, callback);
}
</code>```

Hope it helps.

Body:
I tried the following code, it shows the res is undefined.
How can I return the stdout?

function run_shell_command(command)
{
    var res
    exec(command, function(err,stdout,stderr){
     if(err) {
        console.log('shell error:'+stderr);
    } else {
        console.log('shell successful');
    }
    res = stdout
    // console.log(stdout)
    });
    return res
}

Body:
Your function looks asynchrone, so to get your response outside run_shell_command, you have to use a callback  function like this :

function run_shell_command(command, callback) {
    exec(command, function (err, stdout, stderr) {
        if (err) {
            callback(stderr, null);
        } else {
            callback(null, stdout);
        }
    });
}

run_shell_command(command, function (err, res) {
    if (err) {
        // Do something with your error
    }
    else {
        console.log(res);
    }
});

You also can simplify your run_shell_command function like this :

function run_shell_command(command, callback) {
    exec(command, callback);
}

Hope it helps.


问:
Read all data from STDIN in a batch script
I'm trying to write a SVN post-lock script on windows.I want to use a batch script to call a python script and pass REPO, USER and paths of locked files as its args.

It's said in the .tmpl file that both REPO and USER are predefined arguments and locked paths are passed via STDIN, so I tried this in my .bat file:

```<code>@echo off
set REPOS=%1
set USER=%2
set /p files=

C:\Python27\python.exe C:\test.py %REPOS% %USER% %files%
</code>```

It works fine if I lock a single file. But if I lock multiple files with a single svn lock command, I can only get the first path with 'set /p files='.

How can I get a full list of locked paths with batch script? Thank you for your help!

答:
The Python process will inherit the stdin of its parent process
(the shell running the batch script)
so just defer the task of reading it to your Python program instead —
where it will be much easier to do.</p>

Body:
I'm trying to write a SVN post-lock script on windows.I want to use a batch script to call a python script and pass REPO, USER and paths of locked files as its args.

It's said in the .tmpl file that both REPO and USER are predefined arguments and locked paths are passed via STDIN, so I tried this in my .bat file:

@echo off
set REPOS=%1
set USER=%2
set /p files=

C:\Python27\python.exe C:\test.py %REPOS% %USER% %files%

It works fine if I lock a single file. But if I lock multiple files with a single svn lock command, I can only get the first path with 'set /p files='.

How can I get a full list of locked paths with batch script? Thank you for your help!


问:
Apple Live Photos Metadata
When I export a live photo from the photos app on my mac, it creates two separate files: a jpg and a mov. The jpg comes with all its exif data, while the mov file seems always off by five hours.

More concretely, I used exiftool -option filename. These were the results for the jpg (the yyyy-mm-dd was the same for all, so I'm just including the time output).

```<code>DateTimeOriginal 10:24:38
GPSDateTime 15:24:38Z
MediaCreateDate none
FileModifyDate 15:47:46-05:00
ModifyDate 10:24:38
</code>```

These were the results for the mov.

```<code>DateTimeOriginal none
GPSDateTime none
MediaCreateDate 15:24:38
FileModifyDate 15:47:29-05:00
ModifyDate 15:24:40
</code>```

The time it should display is DateTimeOriginal of the jpg. It looks like MediaCreateDate of the mov is off by five hours, due to perhaps a timezone-related glitch.

Anyway, the reason I'm asking the question is that I want to transition from using Apple photos to a plain folder tree in dropbox. The problem is having a good naming scheme to keep things sorted. I googled a bit and using Hazel (plus the script below) works just fine, if it weren't for the mov files of live photos. to sort all my photos (and live photos) with a decent naming scheme.

How can I tweak the script below to get the correct name for the mov files?

Or, alternatively

How can I use Hazel to tell each mov file to have the DateTimeOriginal of the jpg with the same name?

By this last thing I mean having a script which if fed a mov file looks for a jpg of the same name and uses its DateTimeOriginal.

By the way, the second answer here (Apple Live Photo file format) seems to explain how Photos keeps track of the metadata for the mov file, but I have no idea how to use it.

I actually found two scripts. The first here (https://www.macstories.net/reviews/better-dropbox-camera-uploads-with-camerasync/).

```<code><?php
date_default_timezone_set("Europe/Rome");
$date = exif_read_data($argv[1],"EXIF");
$date = $date["DateTimeOriginal"];
$time = date_parse_from_format("Y:m:d H:i:s",$date);
$time = mktime($time["hour"],$time["minute"],$time["second"],$time["month"],$time["day"],$time["year"]);
touch($argv[1],$time,$time);
?>
</code>```

The second (https://www.noodlesoft.com/forums/viewtopic.php?f=4&t=2218) is

```<code>exiftool -P -d '%Y.%m.%d at %H.%M.%S' \
   '-filename<${FileModifyDate;}.%e' \
    '-filename<${GPSDateTime;}.%e' \
    '-filename<${MediaCreateDate;}.%e' \
    '-filename<${ModifyDate;}.%e' \
    '-filename<${DateTimeOriginal;}.%e' \
    "$1"
</code>```

I previously asked this on apple.stackexchange but got no attention. https://apple.stackexchange.com/questions/236377/live-photos-metadata

答:
Also weighing in on this old question:

When working with live photos as separated JPG and MOV files, the metadata will allow you to link the files.  The MOV file has an EXIF tag called ContentIdentifier that appears to be identical to the tag Apple_0x0011 in the MakerNotes EXIF tag of the JPG file.

Using exiftool:

$ exiftool -u -s IMG_8403.JPG | grep Apple_0x0011
Apple_0x0011                    : C09DCB26-D321-4254-9F68-2E2E7FA16155
$ exiftool -ContentIdentifier IMG_8403.MOV
Content Identifier              : C09DCB26-D321-4254-9F68-2E2E7FA16155

Title: Apple Live Photos Metadata

Body:
When I export a live photo from the photos app on my mac, it creates two separate files: a jpg and a mov. The jpg comes with all its exif data, while the mov file seems always off by five hours.

More concretely, I used exiftool -option filename. These were the results for the jpg (the yyyy-mm-dd was the same for all, so I'm just including the time output).

DateTimeOriginal 10:24:38
GPSDateTime 15:24:38Z
MediaCreateDate none
FileModifyDate 15:47:46-05:00
ModifyDate 10:24:38

These were the results for the mov.

DateTimeOriginal none
GPSDateTime none
MediaCreateDate 15:24:38
FileModifyDate 15:47:29-05:00
ModifyDate 15:24:40

The time it should display is DateTimeOriginal of the jpg. It looks like MediaCreateDate of the mov is off by five hours, due to perhaps a timezone-related glitch.

Anyway, the reason I'm asking the question is that I want to transition from using Apple photos to a plain folder tree in dropbox. The problem is having a good naming scheme to keep things sorted. I googled a bit and using Hazel (plus the script below) works just fine, if it weren't for the mov files of live photos. to sort all my photos (and live photos) with a decent naming scheme.

How can I tweak the script below to get the correct name for the mov files?

Or, alternatively

How can I use Hazel to tell each mov file to have the DateTimeOriginal of the jpg with the same name?

By this last thing I mean having a script which if fed a mov file looks for a jpg of the same name and uses its DateTimeOriginal.

By the way, the second answer here (Apple Live Photo file format) seems to explain how Photos keeps track of the metadata for the mov file, but I have no idea how to use it.

I actually found two scripts. The first here (https://www.macstories.net/reviews/better-dropbox-camera-uploads-with-camerasync/).

<?php
date_default_timezone_set("Europe/Rome");
$date = exif_read_data($argv[1],"EXIF");
$date = $date["DateTimeOriginal"];
$time = date_parse_from_format("Y:m:d H:i:s",$date);
$time = mktime($time["hour"],$time["minute"],$time["second"],$time["month"],$time["day"],$time["year"]);
touch($argv[1],$time,$time);
?>

The second (https://www.noodlesoft.com/forums/viewtopic.php?f=4&t=2218) is

exiftool -P -d '%Y.%m.%d at %H.%M.%S' \
   '-filename<${FileModifyDate;}.%e' \
    '-filename<${GPSDateTime;}.%e' \
    '-filename<${MediaCreateDate;}.%e' \
    '-filename<${ModifyDate;}.%e' \
    '-filename<${DateTimeOriginal;}.%e' \
    "$1"

I previously asked this on apple.stackexchange but got no attention. https://apple.stackexchange.com/questions/236377/live-photos-metadata


问:
Pivot Tables and eloquent Laravel 5.5
this is maybe the hardest problem I'm facing since I use laravel and I hope some of you might help me to solve it.

So, I have the following schema in my database:

Games

id_game

Players

id_player

Role_Players

id_role
description

Games_players

role_id
game_id
player_id

Now, I have a many to many relationships with games and players and the following model

```<code> class Games {

    public function players {

     return $this->belongsToMany(Players::class, Games_players,  id_game, id_player)

   }
}
</code>```

This will return all the players associated with games, but how can I return the role of the players in this game? I know that I have an object $games->players->pivot where I can add the column role_id, but how can I get for example the description using eloquent? I'm struggling to get this work.

I will appreciate any help.

Thanks.

D

答:
You can create a model for your pivot table with its own relations and work off of that. So a model for Games_players will have a relationship to roles, players and games, and vice versa. </p>

<p>These relationships do not have to replace your current manyToMany relationships, they can both be there at the same time. </p>

Title: Pivot Tables and eloquent Laravel 5.5

Body:
this is maybe the hardest problem I'm facing since I use laravel and I hope some of you might help me to solve it.

So, I have the following schema in my database:

Games

id_game

Players

id_player

Role_Players

id_role
description

Games_players

role_id
game_id
player_id

Now, I have a many to many relationships with games and players and the following model

 class Games {

    public function players {

     return $this->belongsToMany(Players::class, Games_players,  id_game, id_player)

   }
}

This will return all the players associated with games, but how can I return the role of the players in this game? I know that I have an object $games->players->pivot where I can add the column role_id, but how can I get for example the description using eloquent? I'm struggling to get this work.

I will appreciate any help.

Thanks.

D

Body:
You can create a model for your pivot table with its own relations and work off of that. So a model for Games_players will have a relationship to roles, players and games, and vice versa.

These relationships do not have to replace your current manyToMany relationships, they can both be there at the same time.


问:
pandas dataframe to json python 3
I have a pandas data frame which has 3 series:

```<code>  import pandas as pd
  import json
  import xml.etree.ElementTree as ET

  df1 = pd.read_excel("C:\\Users\\Desktop\\xml.xlsx")
  df1['response'] = df1['response'].astype(str)

  tree = ET.parse(df1.response[1]) #This does not work
</code>```

The series in the data frame are:

```<code>  userid, appid, response
</code>```

The problem that the "response" is a xml document. I need to convert the entire thing into JSON. That means, something like this:

```<code>  "userid" : "21",
  "appid"  : "40",
  "response" : {"xml document as json"}
</code>```

The step in which I am having problem is to convert the xml into json and then mapping it to the userid.

Sample XML:

```<code> <transactionControl>
<userRefNumber>Credit Report Example</userRefNumber>
<subscriber>
    <industryCode>Z</industryCode>
    <memberCode>03919359</memberCode>
    <inquirySubscriberPrefixCode>1704</inquirySubscriberPrefixCode>
</subscriber>
<options>
    <country>us</country>
    <language>en</language>
</options>
<tracking>
    <transactionTimeStamp>2014-08-02T04:27:02.808-05:00</transactionTimeStamp>
</tracking>
</code>```

答:
I believe you need convert strings to jsons by json.loads:

```<code>df1['response'] = df1['response'].astype(str).apply(pd.io.json.loads)
</code>```

Or use:

```<code>import ast
df1['response'] = df1['response'].astype(str).apply(ast.literal_eval)
</code>```

Title: pandas dataframe to json python 3

Body:
I have a pandas data frame which has 3 series:

  import pandas as pd
  import json
  import xml.etree.ElementTree as ET

  df1 = pd.read_excel("C:\\Users\\Desktop\\xml.xlsx")
  df1['response'] = df1['response'].astype(str)

  tree = ET.parse(df1.response[1]) #This does not work

The series in the data frame are:

  userid, appid, response

The problem that the "response" is a xml document. I need to convert the entire thing into JSON. That means, something like this:

  "userid" : "21",
  "appid"  : "40",
  "response" : {"xml document as json"}

The step in which I am having problem is to convert the xml into json and then mapping it to the userid.

Sample XML:

 <transactionControl>
<userRefNumber>Credit Report Example</userRefNumber>
<subscriber>
    <industryCode>Z</industryCode>
    <memberCode>03919359</memberCode>
    <inquirySubscriberPrefixCode>1704</inquirySubscriberPrefixCode>
</subscriber>
<options>
    <country>us</country>
    <language>en</language>
</options>
<tracking>
    <transactionTimeStamp>2014-08-02T04:27:02.808-05:00</transactionTimeStamp>
</tracking>

Body:
I believe you need convert strings to jsons by json.loads:

df1['response'] = df1['response'].astype(str).apply(pd.io.json.loads)

Or use:

import ast
df1['response'] = df1['response'].astype(str).apply(ast.literal_eval)


问:
Codeigniter mysql DESCRIBE
I'm a bit new to codeigniter and I'm trying to run this simple query:

```<code>DESCRIBE `table_name`;
</code>```

I tried this:

```<code>$sql = 'DESCRIBE ?';
$desc = $this->db->query($sql, $table)->result();
</code>```

Which creates this query:

```<code>DESCRIBE 'table_name';
</code>```

As you can see, the wrong quotes are being outputted when I bind the $table variable; they are value quotes ('), not table quotes (`). Am I doing this wrong?

thank you!

答:
CodeIgniter's query bindings will escape things for you.  It assumes that the data is a value, not a table name.

You're gunna have to escape the value yourself.

```<code>$table = $this->db->escape_str($table);
$sql = "DESCRIBE `$table`";
$desc = $this->db->query($sql)->result();
</code>```

Title: Codeigniter mysql DESCRIBE

Body:
I'm a bit new to codeigniter and I'm trying to run this simple query:

DESCRIBE `table_name`;

I tried this:

$sql = 'DESCRIBE ?';
$desc = $this->db->query($sql, $table)->result();

Which creates this query:

DESCRIBE 'table_name';

As you can see, the wrong quotes are being outputted when I bind the $table variable; they are value quotes ('), not table quotes (`). Am I doing this wrong?

thank you!

Body:
CodeIgniter's query bindings will escape things for you.  It assumes that the data is a value, not a table name.

You're gunna have to escape the value yourself.

$table = $this->db->escape_str($table);
$sql = "DESCRIBE `$table`";
$desc = $this->db->query($sql)->result();


问:
Caffe test net with images as labels
Question

I tried to create a CNN where I am using images as labels, with values between 0 and 1. After some training my net has a loss of round about 23. Now I want to see the results. For this purpose I am using this python script:

```<code>import caffe
import numpy as np
from PIL import Image

net = caffe.Net('D:/caffe/net.prototxt',
            'D:/caffe/net_iter_35000.caffemodel',
            caffe.TEST)

# load input and configure preprocessing
transformer = caffe.io.Transformer({'data': net.blobs['data'].data.shape})

transformer.set_mean('data', np.load('train_mean.npy').mean(1).mean(1))
transformer.set_transpose('data', (2,0,1))
transformer.set_channel_swap('data', (2,1,0))
transformer.set_raw_scale('data', 255.0)

#note we can change the batch size on-the-fly
#since we classify only one image, we change batch size from 10 to 1
net.blobs['data'].reshape(1,3,360,360)

#load the image in the data layer
im = caffe.io.load_image('train/img0.png')
net.blobs['data'].data[...] = transformer.preprocess('data', im)

#compute
out = net.forward()

result = out['conv7'][0][0]
</code>```

Now I am expecting the values  of result to approximatly be between 0 and 1. But in reality result.max() returns 5.92 and result.min() returns -4315.5.

Is there a mistake in the python script or are this values normal for a loss of 23?

Additional Infos

My train_test.prototxt:

```<code>layer {
  name: "mynet"
  type: "Data"
  top: "data0"
  top: "label0"
  include {
    phase: TRAIN
  }
  transform_param {
    mean_file: "train_mean.binaryproto"
    scale: 0.00390625
  }
  data_param {
    source: "train_lmdb"
    batch_size: 32
    backend: LMDB
  }
}

layer {
  name: "mynetlabel"
  type: "Data"
  top: "data1"
  top: "label1"
  include {
    phase: TRAIN
  }
  transform_param {
    scale: 0.00390625
  }
  data_param {
    source: "train_label_lmdb_2"
    batch_size: 32
    backend: LMDB
  }
}

layer {
  name: "mnist"
  type: "Data"
  top: "data0"
  top: "label0"
  include {
    phase: TEST
  }
  transform_param {
    mean_file: "train_mean.binaryproto"
    scale: 0.00390625
  }
  data_param {
    source: "val_lmdb"
    batch_size: 16
    backend: LMDB
  }
}
layer {
  name: "mnistlabel"
  type: "Data"
  top: "data1"
  top: "label1"
  include {
    phase: TEST
  }
  transform_param {
    scale: 0.00390625
  }
  data_param {
    source: "val_label_lmdb_2"
    batch_size: 16
    backend: LMDB
  }
}
.
.
.
layer {
  name: "conv7"
  type: "Convolution"
  bottom: "conv6"
  top: "conv7"
  param {
    lr_mult: 5.0
    decay_mult: 1.0
  }
  param {
    lr_mult: 10.0
    decay_mult: 0.0
  }
  convolution_param {
    num_output: 1
    pad: 0
    kernel_size: 1
    weight_filler {
      type: "gaussian"
      std: 0.00999999977648
    }
    bias_filler {
      type: "constant"
    }
  }
}

layer {
  name: "accuracy"
  type: "Accuracy"
  bottom: "conv7"
  bottom: "data1"
  top: "accuracy"
  include {
    phase: TEST
  }
}

layer {
  name: "loss"
  type: "SigmoidCrossEntropyLoss"
  bottom: "conv7"
  bottom: "data1"
  top: "loss"
}
</code>```

My net.prototxt:

```<code>layer {
  name: "data"
  type: "Input"
  top: "data"
  input_param { shape: { dim: 50 dim: 3 dim: 360 dim: 360 } }
  transform_param {
    scale: 0.00390625
  }
}
.
.
.
layer {
  name: "conv7"
  type: "Convolution"
  bottom: "conv6"
  top: "conv7"
  param {
    lr_mult: 5.0
    decay_mult: 1.0
  }
  param {
    lr_mult: 10.0
    decay_mult: 0.0
  }
  convolution_param {
    num_output: 1
    pad: 0
    kernel_size: 1
    weight_filler {
      type: "gaussian"
      std: 0.00999999977648
    }
    bias_filler {
      type: "constant"
    }
  }
}
</code>```

答:
Your train_val.prototxt uses "SigmoidWithCrossEntropy", as the name of this layer suggests, it comprises (internally) of a "Sigmoid" layer and a cross entropy loss. Therefore, when deploying your net you should replace this layer with a "Sigmoid" layer in your net.prototxt file.

See this answer for more details.

PS,

Using "Accuracy" layer for single binary output is not supported in caffe: "Accuracy" layer assumes the dimension of your prediction equals number of classes (good for "SoftmaxWithLoss"). In your case you have two labels {0, 1} but dim of output is only 1. See this answer for more details.

Title: Caffe test net with images as labels

Body:
Question

I tried to create a CNN where I am using images as labels, with values between 0 and 1. After some training my net has a loss of round about 23. Now I want to see the results. For this purpose I am using this python script:

import caffe
import numpy as np
from PIL import Image

net = caffe.Net('D:/caffe/net.prototxt',
            'D:/caffe/net_iter_35000.caffemodel',
            caffe.TEST)

# load input and configure preprocessing
transformer = caffe.io.Transformer({'data': net.blobs['data'].data.shape})

transformer.set_mean('data', np.load('train_mean.npy').mean(1).mean(1))
transformer.set_transpose('data', (2,0,1))
transformer.set_channel_swap('data', (2,1,0))
transformer.set_raw_scale('data', 255.0)

#note we can change the batch size on-the-fly
#since we classify only one image, we change batch size from 10 to 1
net.blobs['data'].reshape(1,3,360,360)

#load the image in the data layer
im = caffe.io.load_image('train/img0.png')
net.blobs['data'].data[...] = transformer.preprocess('data', im)

#compute
out = net.forward()

result = out['conv7'][0][0]

Now I am expecting the values  of result to approximatly be between 0 and 1. But in reality result.max() returns 5.92 and result.min() returns -4315.5.

Is there a mistake in the python script or are this values normal for a loss of 23?

Additional Infos

My train_test.prototxt:

layer {
  name: "mynet"
  type: "Data"
  top: "data0"
  top: "label0"
  include {
    phase: TRAIN
  }
  transform_param {
    mean_file: "train_mean.binaryproto"
    scale: 0.00390625
  }
  data_param {
    source: "train_lmdb"
    batch_size: 32
    backend: LMDB
  }
}

layer {
  name: "mynetlabel"
  type: "Data"
  top: "data1"
  top: "label1"
  include {
    phase: TRAIN
  }
  transform_param {
    scale: 0.00390625
  }
  data_param {
    source: "train_label_lmdb_2"
    batch_size: 32
    backend: LMDB
  }
}

layer {
  name: "mnist"
  type: "Data"
  top: "data0"
  top: "label0"
  include {
    phase: TEST
  }
  transform_param {
    mean_file: "train_mean.binaryproto"
    scale: 0.00390625
  }
  data_param {
    source: "val_lmdb"
    batch_size: 16
    backend: LMDB
  }
}
layer {
  name: "mnistlabel"
  type: "Data"
  top: "data1"
  top: "label1"
  include {
    phase: TEST
  }
  transform_param {
    scale: 0.00390625
  }
  data_param {
    source: "val_label_lmdb_2"
    batch_size: 16
    backend: LMDB
  }
}
.
.
.
layer {
  name: "conv7"
  type: "Convolution"
  bottom: "conv6"
  top: "conv7"
  param {
    lr_mult: 5.0
    decay_mult: 1.0
  }
  param {
    lr_mult: 10.0
    decay_mult: 0.0
  }
  convolution_param {
    num_output: 1
    pad: 0
    kernel_size: 1
    weight_filler {
      type: "gaussian"
      std: 0.00999999977648
    }
    bias_filler {
      type: "constant"
    }
  }
}

layer {
  name: "accuracy"
  type: "Accuracy"
  bottom: "conv7"
  bottom: "data1"
  top: "accuracy"
  include {
    phase: TEST
  }
}

layer {
  name: "loss"
  type: "SigmoidCrossEntropyLoss"
  bottom: "conv7"
  bottom: "data1"
  top: "loss"
}

My net.prototxt:

layer {
  name: "data"
  type: "Input"
  top: "data"
  input_param { shape: { dim: 50 dim: 3 dim: 360 dim: 360 } }
  transform_param {
    scale: 0.00390625
  }
}
.
.
.
layer {
  name: "conv7"
  type: "Convolution"
  bottom: "conv6"
  top: "conv7"
  param {
    lr_mult: 5.0
    decay_mult: 1.0
  }
  param {
    lr_mult: 10.0
    decay_mult: 0.0
  }
  convolution_param {
    num_output: 1
    pad: 0
    kernel_size: 1
    weight_filler {
      type: "gaussian"
      std: 0.00999999977648
    }
    bias_filler {
      type: "constant"
    }
  }
}


问:
Convert all data frame character columns to factors
Given a (pre-existing) data frame that has columns of various types, what is the simplest way to convert all its character columns to factors, without affecting any columns of other types?

Here's an example data.frame:

```<code>df <- data.frame(A = factor(LETTERS[1:5]),
                 B = 1:5, C = as.logical(c(1, 1, 0, 0, 1)),
                 D = letters[1:5],
                 E = paste(LETTERS[1:5], letters[1:5]),
                 stringsAsFactors = FALSE)
df
#   A B     C D   E
# 1 A 1  TRUE a A a
# 2 B 2  TRUE b B b
# 3 C 3 FALSE c C c
# 4 D 4 FALSE d D d
# 5 E 5  TRUE e E e
str(df)
# 'data.frame':  5 obs. of  5 variables:
#  $ A: Factor w/ 5 levels "A","B","C","D",..: 1 2 3 4 5
#  $ B: int  1 2 3 4 5
#  $ C: logi  TRUE TRUE FALSE FALSE TRUE
#  $ D: chr  "a" "b" "c" "d" ...
#  $ E: chr  "A a" "B b" "C c" "D d" ...
</code>```

I know I can do:

```<code>df$D <- as.factor(df$D)
df$E <- as.factor(df$E)
</code>```

Is there a way to automate this process a bit more?

答:
The easiest way would be to use the code given below. It would automate the whole process of converting all the variables as factors in a dataframe in R. it worked perfectly fine for me. food_cat here is the dataset which I am using. Change it to the one which you are working on.</p>

```<code>    for(i in 1:ncol(food_cat)){

food_cat[,i] <- as.factor(food_cat[,i])

}
</code>```

Body:
Given a (pre-existing) data frame that has columns of various types, what is the simplest way to convert all its character columns to factors, without affecting any columns of other types?

Here's an example data.frame:

df <- data.frame(A = factor(LETTERS[1:5]),
                 B = 1:5, C = as.logical(c(1, 1, 0, 0, 1)),
                 D = letters[1:5],
                 E = paste(LETTERS[1:5], letters[1:5]),
                 stringsAsFactors = FALSE)
df
#   A B     C D   E
# 1 A 1  TRUE a A a
# 2 B 2  TRUE b B b
# 3 C 3 FALSE c C c
# 4 D 4 FALSE d D d
# 5 E 5  TRUE e E e
str(df)
# 'data.frame':  5 obs. of  5 variables:
#  $ A: Factor w/ 5 levels "A","B","C","D",..: 1 2 3 4 5
#  $ B: int  1 2 3 4 5
#  $ C: logi  TRUE TRUE FALSE FALSE TRUE
#  $ D: chr  "a" "b" "c" "d" ...
#  $ E: chr  "A a" "B b" "C c" "D d" ...

I know I can do:

df$D <- as.factor(df$D)
df$E <- as.factor(df$E)

Is there a way to automate this process a bit more?

Body:
The easiest way would be to use the code given below. It would automate the whole process of converting all the variables as factors in a dataframe in R. it worked perfectly fine for me. food_cat here is the dataset which I am using. Change it to the one which you are working on.

    for(i in 1:ncol(food_cat)){

food_cat[,i] <- as.factor(food_cat[,i])

}


问:
Java - Search and Delete an object from Arraylist
so I have class Customer and class Bank , a bank class has methods of adding Customer to an arraylist of Customers , and also must have a method to search a Customer in an arraylist and delete it (Remove from arraylist) , How can I do it?

Bank class -

```<code>private ArrayList<Customer> customers = new ArrayList<>();

public void addCustomer(String name){

    Customer customer = new Customer(name);
    customers.add(customer);
    System.out.println("new customer " + customer.getName() + " added");
}

public void deleteAccount(String name){

}
</code>```

Customer class -

```<code>private String name;
private double balance;

public Customer(String name) {
    this.name = name;
}

public String getName() {
    return name;
}

@Override
public String toString() {
    return "Customer " +
            "name :'" + name + '\'' +
            '}';
}
</code>```

Main -

```<code>public static void deleteAccount(){
    System.out.println("Enter the name you want to delete");
    String name = scanner.nextLine();
    scanner.nextLine();
    bank.deleteAccount(name);
}
</code>```

As you can see, the main class has method which takes input type String from user and then calles Bank class's method of deleteAccount with that input , but I don't know how to proceed with the deleteAccount method, how to make it work ?

I need something that firstly checks if the user input is in the Arraylist, and then remove it from there if there is.

I do realize that input is String and Arraylist is Customer instances , but Customer only takes String name in constractor, so can I make it work this way?

答:
I suggest to use the HashMap object instead of an ArrayList. A HashMap maps a set of keys (costumer names in your case) to a set of objects (the costumer)

```<code>HashMap<String,Customer> customers = new HashMap<String,Customer>();
</code>```

In addCustomer you can do
this.customers.put(name,customer)
and in delete account you can do
this.customers.remove(name)

Otherwise you can iterate over the list as suggested by Timothy, but this is more natural and more efficient

Body:
so I have class Customer and class Bank , a bank class has methods of adding Customer to an arraylist of Customers , and also must have a method to search a Customer in an arraylist and delete it (Remove from arraylist) , How can I do it?

Bank class -

private ArrayList<Customer> customers = new ArrayList<>();

public void addCustomer(String name){

    Customer customer = new Customer(name);
    customers.add(customer);
    System.out.println("new customer " + customer.getName() + " added");
}

public void deleteAccount(String name){

}

Customer class -

private String name;
private double balance;

public Customer(String name) {
    this.name = name;
}

public String getName() {
    return name;
}

@Override
public String toString() {
    return "Customer " +
            "name :'" + name + '\'' +
            '}';
}

Main -

public static void deleteAccount(){
    System.out.println("Enter the name you want to delete");
    String name = scanner.nextLine();
    scanner.nextLine();
    bank.deleteAccount(name);
}

As you can see, the main class has method which takes input type String from user and then calles Bank class's method of deleteAccount with that input , but I don't know how to proceed with the deleteAccount method, how to make it work ?

I need something that firstly checks if the user input is in the Arraylist, and then remove it from there if there is.

I do realize that input is String and Arraylist is Customer instances , but Customer only takes String name in constractor, so can I make it work this way?

Body:
I suggest to use the HashMap object instead of an ArrayList. A HashMap maps a set of keys (costumer names in your case) to a set of objects (the costumer)

HashMap<String,Customer> customers = new HashMap<String,Customer>();

In addCustomer you can do
this.customers.put(name,customer)
and in delete account you can do
this.customers.remove(name)

Otherwise you can iterate over the list as suggested by Timothy, but this is more natural and more efficient


问:
How to comma separate the values of an array for display
I have searched the PHP.net site and originally thought of some use for the list() function but doesn't seem to accomplish the goal:

I have an unknown number of values stored in a single array

$array1 = array(1,2,3,4,5);

or

$array1 = array(1,2,3);

I want to be able to echo (or print_r) the values contained within an array to screen and separated only by commas and spacing.

For example:

the 'idea' is to have echo $array1 to display:

1,2,3

from the second example above.

答:
http://us.php.net/manual/en/function.implode.php</p>

```<code>echo implode(", ", $array);
</code>```

Body:
http://us.php.net/manual/en/function.implode.php

echo implode(", ", $array);


问:
For loop stops execution of a batch-file
I try to make a Batch file, in this batch file I need to move all of my old folders to a Backup folder.

If a execute this command directly it work :

```<code>for /f %a in ('dir /b D:\app\*_2*') do move D:\app\%a D:\app\Backup\
</code>```

But if I use it in a batch, the batch close itself and don't perform the rest of the script.

Any idea?

答:
This problem is caused by parameter substitution in batch files. To have %a passed to the for command in a batch script, you have to escape the % character using %%.

```<code>for /f %%a in ('dir /b D:\app\*_2*') do move D:\app\%%a D:\app\Backup\
</code>```

See also: https://ss64.com/nt/for.html

Body:
I try to make a Batch file, in this batch file I need to move all of my old folders to a Backup folder.

If a execute this command directly it work :

for /f %a in ('dir /b D:\app\*_2*') do move D:\app\%a D:\app\Backup\

But if I use it in a batch, the batch close itself and don't perform the rest of the script.

Any idea?

Body:
This problem is caused by parameter substitution in batch files. To have %a passed to the for command in a batch script, you have to escape the % character using %%.

for /f %%a in ('dir /b D:\app\*_2*') do move D:\app\%%a D:\app\Backup\

See also: https://ss64.com/nt/for.html


答:
deletion Java 8:

```<code>  Optional<Customer> customerToDelete = customers.stream().filter(cust->cust.getName().equals(name)).findFirst();

  if(customerToDelete.isPresent()){
    customers.remove(customers);
  }else{
    System.out.println("Customer does not exist");
  }
</code>```

Btw. I think you should check at "addCustomer" if a customer with the given name already exists...
something like

```<code> customers.stream().filter(cust->cust.getName().equals(name)).count()
</code>```

should do the trick

Title: Java - Search and Delete an object from Arraylist

Body:
deletion Java 8:

  Optional<Customer> customerToDelete = customers.stream().filter(cust->cust.getName().equals(name)).findFirst();

  if(customerToDelete.isPresent()){
    customers.remove(customers);
  }else{
    System.out.println("Customer does not exist");
  }

Btw. I think you should check at "addCustomer" if a customer with the given name already exists...
something like

 customers.stream().filter(cust->cust.getName().equals(name)).count()

should do the trick


问:
How do I check checkbox state in C# Mac

I want to check my checkbox if checked. Windows forms it's ".Checked".
What code works similar with C#, working in Visual Studio for mac?
</p>

```<code>if (IgnoreErrorChk."Checked") {
    //ignore empty
    } else {
       throw new Exception("column exists already!"); }
</code>```

<p>The code asks for the checkbox, when the checkbox is checked, the programm will ignore errors while reading the csv into a mysql database.
If the columnname is already given, he will ignore the column and go to the next.
</p>

答:
A "Check Box Button" is a NSButton with the type set to switch.

You can check is it is "on" via:

```<code>yourNSButtonInstance.State == NSCellStateValue.On
</code>```

NSCellStateValue:

```<code>public enum NSCellStateValue : long
{
    Mixed = -1L,
    Off,
    On
}
</code>```

Title: How do I check checkbox state in C# Mac

Body:
I want to check my checkbox if checked. Windows forms it's ".Checked".
What code works similar with C#, working in Visual Studio for mac?

if (IgnoreErrorChk."Checked") {
    //ignore empty
    } else {
       throw new Exception("column exists already!"); }

The code asks for the checkbox, when the checkbox is checked, the programm will ignore errors while reading the csv into a mysql database.
If the columnname is already given, he will ignore the column and go to the next.

Body:
A "Check Box Button" is a NSButton with the type set to switch.

You can check is it is "on" via:

yourNSButtonInstance.State == NSCellStateValue.On

NSCellStateValue:

public enum NSCellStateValue : long
{
    Mixed = -1L,
    Off,
    On
}


问:
How can I print each value in a list without shortening the list in python?
What I am trying to do is this:

```<code>Str = "yes"
lst = ["e1", "e2", "e3", "y1", "y2", "y3", "s1", "s2", "s3"]
</code>```

I want to be able to print out each item in the list that has a character in Str. So for example I want it to return this:

```<code>["y1", "y2", "y3", "e1", "e2", "e3", "s1", "s2", "s3"]
</code>```

Since that is the order of Str. I have this so far:

```<code>newlst = []
while lst != []:
if Str[0] in text[0]:
    newlst += text[0]
    lst = lst[1:]
    Str = Str[1:]
else:
   lst = lst[1:]
</code>```

My problem is that it only gives me:

```<code>["y1", "y2", "y3"]
</code>```

It's because the list is now []. Is there any way to do this without shortening the list? So keeping it the same but just extracting the values in list that contain Str[n]?

答:
You could also group the strings with a dictionary, easier with a defaultdict:

```<code>from collections import defaultdict

my_string = "yes"
my_list = ["e1", "e2", "e3", "y1", "y2", "y3", "s1", "s2", "s3"]

d = defaultdict(list)
for string in my_list:
    key = string[0]
    d[key].append(string)

>>> print(dict(d))
{'e': ['e1', 'e2', 'e3'], 's': ['s1', 's2', 's3'], 'y': ['y1', 'y2', 'y3']}
</code>```

Then simply run through the ordering of my_string and concatenate the resulting lists with itertools.chain.from_iterable():

```<code>>>> import itertools
>>> lsts = [d[key] for key in my_string]
>>> print(lsts)
[['y1', 'y2', 'y3'], ['e1', 'e2', 'e3'], ['s1', 's2', 's3']]
>>> print(list(itertools.chain.from_iterable(lsts)))
['y1', 'y2', 'y3', 'e1', 'e2', 'e3', 's1', 's2', 's3']
</code>```

Or:

```<code>>>> print([item for sublist in lsts for item in sublist])
['y1', 'y2', 'y3', 'e1', 'e2', 'e3', 's1', 's2', 's3']
</code>```

Body:
What I am trying to do is this:

Str = "yes"
lst = ["e1", "e2", "e3", "y1", "y2", "y3", "s1", "s2", "s3"]

I want to be able to print out each item in the list that has a character in Str. So for example I want it to return this:

["y1", "y2", "y3", "e1", "e2", "e3", "s1", "s2", "s3"]

Since that is the order of Str. I have this so far:

newlst = []
while lst != []:
if Str[0] in text[0]:
    newlst += text[0]
    lst = lst[1:]
    Str = Str[1:]
else:
   lst = lst[1:]

My problem is that it only gives me:

["y1", "y2", "y3"]

It's because the list is now []. Is there any way to do this without shortening the list? So keeping it the same but just extracting the values in list that contain Str[n]?

Body:
You could also group the strings with a dictionary, easier with a defaultdict:

from collections import defaultdict

my_string = "yes"
my_list = ["e1", "e2", "e3", "y1", "y2", "y3", "s1", "s2", "s3"]

d = defaultdict(list)
for string in my_list:
    key = string[0]
    d[key].append(string)

>>> print(dict(d))
{'e': ['e1', 'e2', 'e3'], 's': ['s1', 's2', 's3'], 'y': ['y1', 'y2', 'y3']}

Then simply run through the ordering of my_string and concatenate the resulting lists with itertools.chain.from_iterable():

>>> import itertools
>>> lsts = [d[key] for key in my_string]
>>> print(lsts)
[['y1', 'y2', 'y3'], ['e1', 'e2', 'e3'], ['s1', 's2', 's3']]
>>> print(list(itertools.chain.from_iterable(lsts)))
['y1', 'y2', 'y3', 'e1', 'e2', 'e3', 's1', 's2', 's3']

Or:

>>> print([item for sublist in lsts for item in sublist])
['y1', 'y2', 'y3', 'e1', 'e2', 'e3', 's1', 's2', 's3']


问:
Class is never used for the CursorAdapter and can not resolve symbol for the CursorAdapter class in the Main activity
This is the code for the CursorAdapter

```<code>public class RemindersSimpleCursorAdapter extends SimpleCursorAdapter {
public RemindersSimpleCursorAdapter (Context context, int layout, Cursor c, String[]
    from, int[] to, int flags) {
    super(context, layout, c, from, to, flags);
}
</code>```

and the class name is greyed out

in the main class

```<code>private ListView mListview;
private RemindersDbAdapter mDbAdapter;
private RemindersSimpleCursorAdapter mCursorAdapter;
</code>```

the CursorAdapter class name is now in red.

Please help?

答:
Do import:-

```<code>import com.your-package.RemindersSimpleCursorAdapter
</code>```

Or put that in the same package by adding:-

```<code>package com.your-package
</code>```

Body:
This is the code for the CursorAdapter

public class RemindersSimpleCursorAdapter extends SimpleCursorAdapter {
public RemindersSimpleCursorAdapter (Context context, int layout, Cursor c, String[]
    from, int[] to, int flags) {
    super(context, layout, c, from, to, flags);
}

and the class name is greyed out

in the main class

private ListView mListview;
private RemindersDbAdapter mDbAdapter;
private RemindersSimpleCursorAdapter mCursorAdapter;

the CursorAdapter class name is now in red.

Please help?

Body:
Do import:-

import com.your-package.RemindersSimpleCursorAdapter

Or put that in the same package by adding:-

package com.your-package


问:
Access QML root object from C++ QML type
I have a custom QML type written in C++, the classname is MyCustomType and it's located in the files mycustomtype.h and mycustomtype.cpp.

In the main.cpp file the QML type is made available:

```<code>qmlRegisterType<MyCustomType>("MyCustomType", 1, 0, "MyCustomType");

QQmlApplicationEngine engine;
engine.load(QUrl(QStringLiteral("../qml/main.qml")));
</code>```

In the main.cpp file I can get access to the engine's root object like this:

```<code>rootObject = static_cast<QQuickWindow *> (engine.rootObjects().first());
</code>```

My issue is that I need access to that rootObject from within the MyCustomType class in the mycustomtype.cpp file. Is that possible?

The only way I could think of was to pass the rootObject to the constructor. But since the MyCustomType is instatiated in the QML document, and not in C++ code, this solution won't work.

Any ideas?

答:
Method 1: Passing the root object

You can use setContextProperty to make a variable globally available in QML:

```<code>engine.rootContext ().setContextProperty("rootObject", QVariant::fromValue(engine.rootObjects().first()));
</code>```

Now you can access the root object in QML using rootObject and pass it to MyCustomType during construction.

Method 2: Make the root object statically available

You can make the root object statically available. One clean solution is to create a singleton class with all your global data members.

Body:
I have a custom QML type written in C++, the classname is MyCustomType and it's located in the files mycustomtype.h and mycustomtype.cpp.

In the main.cpp file the QML type is made available:

qmlRegisterType<MyCustomType>("MyCustomType", 1, 0, "MyCustomType");

QQmlApplicationEngine engine;
engine.load(QUrl(QStringLiteral("../qml/main.qml")));

In the main.cpp file I can get access to the engine's root object like this:

rootObject = static_cast<QQuickWindow *> (engine.rootObjects().first());

My issue is that I need access to that rootObject from within the MyCustomType class in the mycustomtype.cpp file. Is that possible?

The only way I could think of was to pass the rootObject to the constructor. But since the MyCustomType is instatiated in the QML document, and not in C++ code, this solution won't work.

Any ideas?

Body:
Method 1: Passing the root object

You can use setContextProperty to make a variable globally available in QML:

engine.rootContext ().setContextProperty("rootObject", QVariant::fromValue(engine.rootObjects().first()));

Now you can access the root object in QML using rootObject and pass it to MyCustomType during construction.

Method 2: Make the root object statically available

You can make the root object statically available. One clean solution is to create a singleton class with all your global data members.


问:
asp.net custom HttpHandler and URL routing
I want handle the requests to my application "http://example.com/whateverpath" by a custom HttpHandler but the return things depending of the value of "whateverpath".

So users accessing "http://example.com/path1" will get different response than users accessing "http://example.com/path2", but both request must be handled in the same HttpHandler. The idea is find "whateverpath" in a database and depending of the result, return the response content.

I hear about URL routing and I already have a custom Http handler working, but can I combine both technique to get what I need?

I will appreciate any comment respect this issue.

Cheers
Frank Abel

答:
So you have a class that implements IHttpHandler called: MyHandler and it's in the namespace Example, you need to make the following entries in the site's Web.Config in the httpHandlers section:

```<code><httpHandlers>
  <add verb="*" path="*" type="Example.MyHandler"/>
</httpHandlers>
</code>```

Since this redirects all URLs for your web site/application to your handler you have to consider how to serve static content (imgs, scripts, style sheets etc).  One way is to store such static content in a consistent URL like http://example.com/static/..., you can then set your handlers as such:

```<code><httpHandlers>
  <add verb="*" path="*" type="Example.MyHandler"/>
  <add verb="GET,HEAD" path="static/*" type="System.Web.StaticFileHandler" />
</httpHandlers>
</code>```

For your local dev webserver (embedded in Visual Studio) this is all that's needed.  For IIS, you also need to tell IIS how to deal with these URLS (since the server first analyses a request to decide where to send it - including whether to send it to ASP.NET or some other extension).

Open: IIS Manager ->

Section: Websites ->

Right click on your website ->

Option: Properties ->

Tab: Home Directoy ->

Button: [Configuration...] ->

Tab: Mappings ->

Section: "Wildcard application maps (order of implementation):" ->

Button: [Insert...] ->

Executable: "C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\aspnet_isapi.dll" (or whichever version of the .NET  runtime your handler uses) ->

Uncheck "Verify that file exists" ->

Button: [OK]

Now both IIS and ASP.NET know how to deal with your URLS.

The above approach means when requesting static files, ASP.NET is actually serving the files, not IIS - which leads to a few disadvantages (discussed here).  You can override this behaviour (disable wildcard mapping from the static directory) by switching the directory to an application (in IIS Manager), removing the wildcard mapping statement (added above) and switching it back from an application.  Voilà - static files are handled by IIS without pestering your ASP.NET.

Body:
So you have a class that implements IHttpHandler called: MyHandler and it's in the namespace Example, you need to make the following entries in the site's Web.Config in the httpHandlers section:

<httpHandlers>
  <add verb="*" path="*" type="Example.MyHandler"/>
</httpHandlers>

Since this redirects all URLs for your web site/application to your handler you have to consider how to serve static content (imgs, scripts, style sheets etc).  One way is to store such static content in a consistent URL like http://example.com/static/..., you can then set your handlers as such:

<httpHandlers>
  <add verb="*" path="*" type="Example.MyHandler"/>
  <add verb="GET,HEAD" path="static/*" type="System.Web.StaticFileHandler" />
</httpHandlers>

For your local dev webserver (embedded in Visual Studio) this is all that's needed.  For IIS, you also need to tell IIS how to deal with these URLS (since the server first analyses a request to decide where to send it - including whether to send it to ASP.NET or some other extension).

Open: IIS Manager ->

Section: Websites ->

Right click on your website ->

Option: Properties ->

Tab: Home Directoy ->

Button: [Configuration...] ->

Tab: Mappings ->

Section: "Wildcard application maps (order of implementation):" ->

Button: [Insert...] ->

Executable: "C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\aspnet_isapi.dll" (or whichever version of the .NET  runtime your handler uses) ->

Uncheck "Verify that file exists" ->

Button: [OK]

Now both IIS and ASP.NET know how to deal with your URLS.

The above approach means when requesting static files, ASP.NET is actually serving the files, not IIS - which leads to a few disadvantages (discussed here).  You can override this behaviour (disable wildcard mapping from the static directory) by switching the directory to an application (in IIS Manager), removing the wildcard mapping statement (added above) and switching it back from an application.  Voilà - static files are handled by IIS without pestering your ASP.NET.


问:
Give a toggle button the color "#FF5D0000" in the main window
I want to give mij text on my button a customized color in the MainWindow.xaml.cs

Normally you give the color in the cs file by this way to the  command:

```<code>ToggleButton.Foreground = Brushes.Green;
</code>```

But I want to give the hexnumber

I've already tried something like this :

```<code>SolidColorBrush Owncolor = (SolidColorBrush)(new BrushConverter().ConvertFrom("#FF5D0000"));
ToggleButton.Foreground = Brushes.Owncolor;
</code>```

答:
Usually in WPF you tend to use styles defined in XAML to change how controls looks. However, using the BrushConverter works if you absolutely have to use the hexadecimal syntax in codebehind. I'd consider building a new SolidColorBrush with Color.FromArgb easier, but that also works.

As for how to use styles and XAML properly, you should probably read some tutorials or books. WPF is quite a different beast than Windows Forms or a lot of older UI frameworks, so there's some re-learning required.

The simplest way of achieving what you want (a different text colour when the button is pressed) would be the following style:

```<code><Style TargetType="ToggleButton">
    <Setter Property="Foreground" Value="#FF5D0000"/>
    <Style.Triggers>
        <Trigger Property="IsPressed" Value="True">
            <Setter Property="Foreground" Value="Green"/>
        </Trigger>
    </Style.Triggers>
</Style>
</code>```

When placed in the Resources of your Window it would apply to all ToggleButtons in that window.

Body:
I want to give mij text on my button a customized color in the MainWindow.xaml.cs

Normally you give the color in the cs file by this way to the  command:

ToggleButton.Foreground = Brushes.Green;

But I want to give the hexnumber

I've already tried something like this :

SolidColorBrush Owncolor = (SolidColorBrush)(new BrushConverter().ConvertFrom("#FF5D0000"));
ToggleButton.Foreground = Brushes.Owncolor;

Body:
Usually in WPF you tend to use styles defined in XAML to change how controls looks. However, using the BrushConverter works if you absolutely have to use the hexadecimal syntax in codebehind. I'd consider building a new SolidColorBrush with Color.FromArgb easier, but that also works.

As for how to use styles and XAML properly, you should probably read some tutorials or books. WPF is quite a different beast than Windows Forms or a lot of older UI frameworks, so there's some re-learning required.

The simplest way of achieving what you want (a different text colour when the button is pressed) would be the following style:

<Style TargetType="ToggleButton">
    <Setter Property="Foreground" Value="#FF5D0000"/>
    <Style.Triggers>
        <Trigger Property="IsPressed" Value="True">
            <Setter Property="Foreground" Value="Green"/>
        </Trigger>
    </Style.Triggers>
</Style>

When placed in the Resources of your Window it would apply to all ToggleButtons in that window.


问:
Searching in database not working | PHP HTML5 CSS MySQL
I'm making an database driven site for a school project.
(Keep in mind I didn't stick to the copyright rules since it's a private website
which will be shut down after).

1: I've connected my database via a file named 'verbinding.php' (I'm Dutch, it would be 'connection.php' in English)

```<code><?php
$verbinding = mysqli_connect('localhost','*********','**********','**********');
?>
</code>```

2: I've made a file in which I have coded my database plus a form.

```<code><!DOCTYPE html>
<html lang="nl">
    <head>
    <meta charset="UTF-8">
    <link rel="STYLESHEET" href="dieren.css" type="text/css" />
        <title> PO dierentuin </title>
    </head>
    <?php include 'verbinding.php'
    ?>

    <body>
<div id="zoekvenster">
    <p>Zoek door onze database als een varkentje met een heel goed neusje</p>
<form  method="post" action="zoeken.php"  id="zoekbox">
      Zoekwoord <input  type="text" name="zoekwoord"><br>
      <label><input type="radio" name="categorie" value="animalnumber" id=Cat_1>Diernummer</label><br>
      <label><input type="radio" name="categorie" value="species" id=Cat_2>Diersoort</label><br>
      <label><input type="radio" name="categorie" value="stay" id=Cat_3>Verblijf</label><br>
      <label><input type="radio" name="categorie" value="gender" id=Cat_4>Geslacht</label><br>
      <label><input type="radio" name="categorie" value="place of birth" id=Cat_5>Nationaliteit</label><br>
      <input  type="submit" name="submit" value="Zoeken">
</form>
</div>
<h2>All animals we have</h2>
<div id="inleiding">
<?php
  $sqlquery = "SELECT * FROM Dierentuin";
  $resultaat = mysqli_query($verbinding, $sqlquery);
  $queryResultaat = mysqli_num_rows($resultaat);
echo"
  <table border='1'>
<tr>
<th>Animalnumber</th>
<th>Species</th>
<th>Race</th>
<th>Date of birth</th>
<th>Voeding</th>
<th>Stay</th>
<th>Mass</th>
<th>Gender</th>
<th>Place of birth</th>
</tr>";

  if ($queryResultaat > 0) {
      while ($row = mysqli_fetch_assoc($resultaat)) {
          echo "<tr>";
          echo "<td>".$row['Diernr']."</td>";
          echo "<td>".$row['Soort']."</td>";
          echo "<td>".$row['Ras']."</td>";
          echo "<td>".$row['Leeftijd']."</td>";
          echo "<td>".$row['Voeding']."</td>";
          echo "<td>".$row['Verblijf']."</td>";
          echo "<td>".$row['Gewicht_in_kg']."</td>";
          echo "<td>".$row['M/V']."</td>";
          echo "<td>".$row['Nationaliteit']."</td>";
          echo "</tr>";
      }
      echo "</table>";
  } else {
      echo "Something went wrong";
  }
?>
<br>
<br>
<br>
</div>
        <footer>
        <p>This assignment was produced by Tieme and Marijn. 5VWO Marne College.</p>
        </footer>

    </body>
</html>
</code>```

3: I also have the file 'zoeken.php' which will be referred as 'search.php' since zoeken is Dutch for search.

```<code><?php
include('verbinding.php');
$zoekwoord = $_POST["zoekwoord"];
$categorie = $_POST["categorie"];
echo $categorie;
echo $zoekwoord;
$query = ("SELECT * FROM dierentuin WHERE $categorie is '$zoekwoord'");
$resultaat = mysqli_query($verbinding, $query);
  if ($resultaat > 0) {
      while ($row = mysqli_fetch_assoc($resultaat)) {
          echo ".'$row'['animalnumber'].";
          echo "Het werkt iniedergeval";
      }
  } else {
      echo "Something went wrong";
  }
</code>```

Only, if you look in the form in the second file, you'll notice there is one textbox, and some radio's. Let's say, I fill in 'Congo' in place of birth, and check the radiobox Place of Birth, a query should be made in which I see only the animals born in the Congo.

If I do this on my website, no matter what I fill in it goes to the 'else' in the third file, and it says 'Something went wrong'

Does anyone knows what I'm doing wrong?

答:
("SELECT * FROM dierentuin WHERE $categorie is '$zoekwoord'");
You are comparing variable with variable.

It should be like that

SELECT * FROM dierentuin WHERE DBfieldname = "$variable_name" and   DBfieldname2 = "$variable_name2");

ContentLicense: CC BY-SA 4.0

Body:
I'm making an database driven site for a school project.
(Keep in mind I didn't stick to the copyright rules since it's a private website
which will be shut down after).

1: I've connected my database via a file named 'verbinding.php' (I'm Dutch, it would be 'connection.php' in English)

<?php
$verbinding = mysqli_connect('localhost','*********','**********','**********');
?>

2: I've made a file in which I have coded my database plus a form.

<!DOCTYPE html>

    <meta charset="UTF-8">
    <link rel="STYLESHEET" href="dieren.css" type="text/css" />
        <title> PO dierentuin </title>

    <?php include 'verbinding.php'
    ?>

Zoek door onze database als een varkentje met een heel goed neusje

<form  method="post" action="zoeken.php"  id="zoekbox">
      Zoekwoord <input  type="text" name="zoekwoord">

      <input type="radio" name="categorie" value="animalnumber" id=Cat_1>Diernummer

      <input type="radio" name="categorie" value="species" id=Cat_2>Diersoort

      <input type="radio" name="categorie" value="stay" id=Cat_3>Verblijf

      <input type="radio" name="categorie" value="gender" id=Cat_4>Geslacht

      <input type="radio" name="categorie" value="place of birth" id=Cat_5>Nationaliteit

      <input  type="submit" name="submit" value="Zoeken">
</form>

All animals we have

<?php
  $sqlquery = "SELECT * FROM Dierentuin";
  $resultaat = mysqli_query($verbinding, $sqlquery);
  $queryResultaat = mysqli_num_rows($resultaat);
echo"

Animalnumber
Species
Race
Date of birth
Voeding
Stay
Mass
Gender
Place of birth

";

  if ($queryResultaat > 0) {
      while ($row = mysqli_fetch_assoc($resultaat)) {
          echo "
";
          echo "".$row['Diernr']."	";
          echo "".$row['Soort']."	";
          echo "".$row['Ras']."	";
          echo "".$row['Leeftijd']."	";
          echo "".$row['Voeding']."	";
          echo "".$row['Verblijf']."	";
          echo "".$row['Gewicht_in_kg']."	";
          echo "".$row['M/V']."	";
          echo "".$row['Nationaliteit']."	";
          echo "
";
      }
      echo "
";
  } else {
      echo "Something went wrong";
  }
?>

This assignment was produced by Tieme and Marijn. 5VWO Marne College.

3: I also have the file 'zoeken.php' which will be referred as 'search.php' since zoeken is Dutch for search.

<?php
include('verbinding.php');
$zoekwoord = $_POST["zoekwoord"];
$categorie = $_POST["categorie"];
echo $categorie;
echo $zoekwoord;
$query = ("SELECT * FROM dierentuin WHERE $categorie is '$zoekwoord'");
$resultaat = mysqli_query($verbinding, $query);
  if ($resultaat > 0) {
      while ($row = mysqli_fetch_assoc($resultaat)) {
          echo ".'$row'['animalnumber'].";
          echo "Het werkt iniedergeval";
      }
  } else {
      echo "Something went wrong";
  }

Only, if you look in the form in the second file, you'll notice there is one textbox, and some radio's. Let's say, I fill in 'Congo' in place of birth, and check the radiobox Place of Birth, a query should be made in which I see only the animals born in the Congo.

If I do this on my website, no matter what I fill in it goes to the 'else' in the third file, and it says 'Something went wrong'

Does anyone knows what I'm doing wrong?


问:
Comparison Error While Converting C# to VB.NET
I am in the process of converting some c# code to that of VB.NET...I am running into error at the following

C#

```<code>if (bytes[i - 1] == ' ')
{
  returnValue.Append("=20");
}
else if (bytes[i - 1] == '\t')
{
  returnValue.Append("=09");
}
</code>```

VB.NET

```<code>If bytes(i - 1) = " "C Then <==error Operator "=" is not defined for types 'Byte' and 'Char'

   returnValue.Append("=20")
ElseIf bytes(i - 1) = ControlChars.Tab Then <==error Operator "=" is not defined for types 'Byte' and 'Char'
   returnValue.Append("=09")
End If
</code>```

答:
I believe the actual problems lies with the initial comparison.  You are trying to compare a byte to a char.  Try converting the byte to a char first.

```<code>if char(bytes(i - 1)) = " "C Then
</code>```

Body:
I am in the process of converting some c# code to that of VB.NET...I am running into error at the following

C#

if (bytes[i - 1] == ' ')
{
  returnValue.Append("=20");
}
else if (bytes[i - 1] == '\t')
{
  returnValue.Append("=09");
}

VB.NET

If bytes(i - 1) = " "C Then <==error Operator "=" is not defined for types 'Byte' and 'Char'

   returnValue.Append("=20")
ElseIf bytes(i - 1) = ControlChars.Tab Then <==error Operator "=" is not defined for types 'Byte' and 'Char'
   returnValue.Append("=09")
End If

Body:
I believe the actual problems lies with the initial comparison.  You are trying to compare a byte to a char.  Try converting the byte to a char first.

if char(bytes(i - 1)) = " "C Then


问:
Can you clear liquibase checksums for a given file only?
Running

```<code>liquibase --url=jdbc:oracle:thin:@localhost:1521/XE --
driver=oracle.jdbc.OracleDriver --changeLogFile=db.changelog-next.xml --
username=owner --password=xxxx --logLevel=info clearCheckSums
</code>```

clears ALL checksums from the database. Is there a way to clear only the checksums for changesets in db.changelog-next.xml.

Thanks

答:
If you are using a Maven plugin for Liquibase, you may have something like this on your pom.xml file, where you use clearCheckSum as a parameter for each execution(you may want to split the files as I did in here):

```<code>        <build>
            <plugins>
                <plugin>
                    <!--NOTE: clearCheckSums=true attribute will make the changesets run only once.
                        The runOnChange attribute added to changesets will not work as originally intended.-->
                    <groupId>org.liquibase</groupId>
                    <artifactId>liquibase-maven-plugin</artifactId>
                    <version>${database.liquibase.version}</version>
                    <executions>
                        <execution>
                            <id>admin-schema-database-update</id>
                            <phase>process-resources</phase>
                            <configuration>
                                <changeLogFile>admin-schema.db.changelog-master.xml</changeLogFile>
                                <driver>${database.driver}</driver>
                                <contexts>${database.liquibasecontext}</contexts>
                                <url>${database.server.url}</url>
                                <username>${database.adminschema.username}</username>
                                <password>${database.adminschema.password}</password>
                                <promptOnNonLocalDatabase>false</promptOnNonLocalDatabase>
                                <outputDefaultSchema>true</outputDefaultSchema>
                                <verbose>true</verbose>
                                <logging>${database.liquibase.logging}</logging>
                                <propertyFileWillOverride>false</propertyFileWillOverride>
                                <clearCheckSums>${liquibase.clearCheckSums}</clearCheckSums>
                            </configuration>
                            <goals>
                                <goal>update</goal>
                            </goals>
                        </execution>
                        <execution>
                            <id>user-schema-database-update</id>
                            <phase>process-resources</phase>
                            <configuration>
                                <changeLogFile>user-schema.db.changelog-master.xml</changeLogFile>
                                <driver>${database.driver}</driver>
                                <contexts>${database.liquibasecontext}</contexts>
                                <url>${database.server.url}</url>
                                <username>${database.username}</username>
                                <password>${database.password}</password>
                                <promptOnNonLocalDatabase>false</promptOnNonLocalDatabase>
                                <outputDefaultSchema>true</outputDefaultSchema>
                                <verbose>true</verbose>
                                <logging>${database.liquibase.logging}</logging>
                                <propertyFileWillOverride>false</propertyFileWillOverride>
                                <clearCheckSums>${liquibase.clearCheckSums}</clearCheckSums>
                            </configuration>
                            <goals>
                                <goal>update</goal>
                            </goals>
                        </execution>
                    </executions>
                    <dependencies>
                        <dependency>
                            <groupId>org.liquibase.ext</groupId>
                            <artifactId>liquibase-mssql</artifactId>
                            <version>1.3.0</version>
                        </dependency>
                        <dependency>
                            <groupId>org.liquibase.ext</groupId>
                            <artifactId>liquibase-oracle</artifactId>
                            <version>3.1</version>
                        </dependency>
                    </dependencies>
                </plugin>
            </plugins>

            <resources>
                <resource>
                    <directory>src/main/resources</directory>
                    <filtering>true</filtering>
                    <includes>
                        <include>**/*.xml</include>
                        <include>**/*.csv</include>
                        <include>**/*.sql</include>
                    </includes>
                </resource>
                <resource>
                    <directory>src/main/resources</directory>
                    <filtering>false</filtering>
                    <excludes>
                        <exclude>**/*.xml</exclude>
                        <exclude>**/*.csv</exclude>
                        <exclude>**/*.sql</exclude>
                    </excludes>
                </resource>
            </resources>
        </build>
</code>```

You can always use the parameterized build with Maven, adding default values as:

```<code><properties>
    <liquibase.clearCheckSums>true</liquibase.clearCheckSums>
    <database.username>userSchema</database.username>
    <database.password>myUserPassword</database.password>
    <database.adminschema.username>adminSchema</database.adminschema.username>
    <database.adminschema.password>myAdminPassword</database.adminschema.password>
    <database.liquibasecontext>!IntegrationTesting</database.liquibasecontext>
</properties>
</code>```

Body:
Running

liquibase --url=jdbc:oracle:thin:@localhost:1521/XE --
driver=oracle.jdbc.OracleDriver --changeLogFile=db.changelog-next.xml --
username=owner --password=xxxx --logLevel=info clearCheckSums

clears ALL checksums from the database. Is there a way to clear only the checksums for changesets in db.changelog-next.xml.

Thanks

Body:
If you are using a Maven plugin for Liquibase, you may have something like this on your pom.xml file, where you use clearCheckSum as a parameter for each execution(you may want to split the files as I did in here):

        <build>
            <plugins>
                <plugin>
                    <!--NOTE: clearCheckSums=true attribute will make the changesets run only once.
                        The runOnChange attribute added to changesets will not work as originally intended.-->
                    <groupId>org.liquibase</groupId>
                    <artifactId>liquibase-maven-plugin</artifactId>
                    <version>${database.liquibase.version}</version>
                    <executions>
                        <execution>
                            <id>admin-schema-database-update</id>
                            <phase>process-resources</phase>
                            <configuration>
                                <changeLogFile>admin-schema.db.changelog-master.xml</changeLogFile>
                                <driver>${database.driver}</driver>
                                <contexts>${database.liquibasecontext}</contexts>
                                <url>${database.server.url}</url>
                                <username>${database.adminschema.username}</username>
                                <password>${database.adminschema.password}</password>
                                <promptOnNonLocalDatabase>false</promptOnNonLocalDatabase>
                                <outputDefaultSchema>true</outputDefaultSchema>
                                <verbose>true</verbose>
                                <logging>${database.liquibase.logging}</logging>
                                <propertyFileWillOverride>false</propertyFileWillOverride>
                                <clearCheckSums>${liquibase.clearCheckSums}</clearCheckSums>
                            </configuration>
                            <goals>
                                <goal>update</goal>
                            </goals>
                        </execution>
                        <execution>
                            <id>user-schema-database-update</id>
                            <phase>process-resources</phase>
                            <configuration>
                                <changeLogFile>user-schema.db.changelog-master.xml</changeLogFile>
                                <driver>${database.driver}</driver>
                                <contexts>${database.liquibasecontext}</contexts>
                                <url>${database.server.url}</url>
                                <username>${database.username}</username>
                                <password>${database.password}</password>
                                <promptOnNonLocalDatabase>false</promptOnNonLocalDatabase>
                                <outputDefaultSchema>true</outputDefaultSchema>
                                <verbose>true</verbose>
                                <logging>${database.liquibase.logging}</logging>
                                <propertyFileWillOverride>false</propertyFileWillOverride>
                                <clearCheckSums>${liquibase.clearCheckSums}</clearCheckSums>
                            </configuration>
                            <goals>
                                <goal>update</goal>
                            </goals>
                        </execution>
                    </executions>
                    <dependencies>
                        <dependency>
                            <groupId>org.liquibase.ext</groupId>
                            <artifactId>liquibase-mssql</artifactId>
                            <version>1.3.0</version>
                        </dependency>
                        <dependency>
                            <groupId>org.liquibase.ext</groupId>
                            <artifactId>liquibase-oracle</artifactId>
                            <version>3.1</version>
                        </dependency>
                    </dependencies>
                </plugin>
            </plugins>

            <resources>
                <resource>
                    <directory>src/main/resources</directory>
                    <filtering>true</filtering>
                    <includes>
                        <include>**/*.xml</include>
                        <include>**/*.csv</include>
                        <include>**/*.sql</include>
                    </includes>
                </resource>
                <resource>
                    <directory>src/main/resources</directory>
                    <filtering>false</filtering>
                    <excludes>
                        <exclude>**/*.xml</exclude>
                        <exclude>**/*.csv</exclude>
                        <exclude>**/*.sql</exclude>
                    </excludes>
                </resource>
            </resources>
        </build>

You can always use the parameterized build with Maven, adding default values as:

<properties>
    <liquibase.clearCheckSums>true</liquibase.clearCheckSums>
    <database.username>userSchema</database.username>
    <database.password>myUserPassword</database.password>
    <database.adminschema.username>adminSchema</database.adminschema.username>
    <database.adminschema.password>myAdminPassword</database.adminschema.password>
    <database.liquibasecontext>!IntegrationTesting</database.liquibasecontext>
</properties>


问:
How to use paramiko to transfer files between two remote servers?
Please let me know how do I use paramiko module to transfer files between two remote hosts.

I have seen that 'get' method will get the files from remote host to local host.
'put' method will put the local files to some remote host.

Is there any method that combines 'get' and 'put' methods i.e.get files from remote host and put it in remote host. This request will get initiated from localhost.

答:
Paramiko.sftp_client.SFTPClient provides SFTP (Secure File Transfer Protocol) features to move files between computers. After starting an sftp session via

ssh = client.open_sftp(),

you can access all of these methods.

If you just want to move files on the remote host, then you can use "local" file transfer methods with shutil. Hope that helped!


问:
Error when install picamera on python 3.5.2 windows 10
I tried to install the picamera to my python 3.5 on windows 10 with pip 9.

Also,i looked online and know that i need to install pyyaml and i did. Its really strange, some suggestion is that the pip need to be the same location as setup.py? which is even more confusing. Anyway, below is what i did, hope it help.

Excuted command:

```<code>pip install --user picamera
</code>```

Command Output:

```<code>Collecting picamera
  Using cached picamera-1.13.tar.gz
Building wheels for collected packages: picamera
  Running setup.py bdist_wheel for picamera: started
  Running setup.py bdist_wheel for picamera: finished with status 'error'
  Complete output from command C:\Users\Dell\AppData\Local\Programs\Python\Python35\python.exe -u -c "import setuptools, tokenize;__file__='C:\\Users\\Dell\\AppData\\Local\\Temp\\pycharm-packaging\\picamera\\setup.py';f=getattr(tokenize, 'open', open)(__file__);code=f.read().replace('\r\n', '\n');f.close();exec(compile(code, __file__, 'exec'))" bdist_wheel -d C:\Users\Dell\AppData\Local\Temp\tmpfj3othpnpip-wheel- --python-tag cp35:
  running bdist_wheel
  running build
  running build_py
  creating build
  creating build\lib
  creating build\lib\picamera
  copying picamera\array.py -> build\lib\picamera
  copying picamera\bcm_host.py -> build\lib\picamera
  copying picamera\camera.py -> build\lib\picamera
  copying picamera\color.py -> build\lib\picamera
  copying picamera\display.py -> build\lib\picamera
  copying picamera\encoders.py -> build\lib\picamera
  copying picamera\exc.py -> build\lib\picamera
  copying picamera\frames.py -> build\lib\picamera
  copying picamera\mmal.py -> build\lib\picamera
  copying picamera\mmalobj.py -> build\lib\picamera
  copying picamera\renderers.py -> build\lib\picamera
  copying picamera\streams.py -> build\lib\picamera
  copying picamera\__init__.py -> build\lib\picamera
  running egg_info
  writing picamera.egg-info\PKG-INFO
  writing requirements to picamera.egg-info\requires.txt
  writing dependency_links to picamera.egg-info\dependency_links.txt
  writing top-level names to picamera.egg-info\top_level.txt
  warning: manifest_maker: standard file '-c' not found

  reading manifest file 'picamera.egg-info\SOURCES.txt'
  reading manifest template 'MANIFEST.in'
  no previously-included directories found matching 'debian'
  no previously-included directories found matching 'docs'
  writing manifest file 'picamera.egg-info\SOURCES.txt'
  warning: build_py: byte-compiling is disabled, skipping.

  installing to build\bdist.win-amd64\wheel
  running install
  Traceback (most recent call last):
    File "C:\Users\Dell\AppData\Local\Temp\pycharm-packaging\picamera\setup.py", line 101, in run
      with io.open('/proc/cpuinfo', 'r') as cpuinfo:
  FileNotFoundError: [Errno 2] No such file or directory: '/proc/cpuinfo'

  During handling of the above exception, another exception occurred:

  Traceback (most recent call last):
    File "<string>", line 1, in <module>
    File "C:\Users\Dell\AppData\Local\Temp\pycharm-packaging\picamera\setup.py", line 145, in <module>
      main()
    File "C:\Users\Dell\AppData\Local\Temp\pycharm-packaging\picamera\setup.py", line 140, in main
      cmdclass             = {'install': CustomInstallCommand},
    File "C:\Users\Dell\AppData\Local\Programs\Python\Python35\lib\distutils\core.py", line 148, in setup
      dist.run_commands()
    File "C:\Users\Dell\AppData\Local\Programs\Python\Python35\lib\distutils\dist.py", line 955, in run_commands
      self.run_command(cmd)
    File "C:\Users\Dell\AppData\Local\Programs\Python\Python35\lib\distutils\dist.py", line 974, in run_command
      cmd_obj.run()
    File "C:\Users\Dell\AppData\Roaming\Python\Python35\site-packages\wheel\bdist_wheel.py", line 240, in run
      self.run_command('install')
    File "C:\Users\Dell\AppData\Local\Programs\Python\Python35\lib\distutils\cmd.py", line 313, in run_command
      self.distribution.run_command(command)
    File "C:\Users\Dell\AppData\Local\Programs\Python\Python35\lib\distutils\dist.py", line 974, in run_command
      cmd_obj.run()
    File "C:\Users\Dell\AppData\Local\Temp\pycharm-packaging\picamera\setup.py", line 113, in run
      raise ValueError('Unable to open /proc/cpuinfo')
  ValueError: Unable to open /proc/cpuinfo

  ----------------------------------------
  Running setup.py clean for picamera
Failed to build picamera
Installing collected packages: picamera
  Running setup.py install for picamera: started
    Running setup.py install for picamera: finished with status 'error'
    Complete output from command C:\Users\Dell\AppData\Local\Programs\Python\Python35\python.exe -u -c "import setuptools, tokenize;__file__='C:\\Users\\Dell\\AppData\\Local\\Temp\\pycharm-packaging\\picamera\\setup.py';f=getattr(tokenize, 'open', open)(__file__);code=f.read().replace('\r\n', '\n');f.close();exec(compile(code, __file__, 'exec'))" install --record C:\Users\Dell\AppData\Local\Temp\pip-x3ancwkq-record\install-record.txt --single-version-externally-managed --compile --user --prefix=:
    running install
    Traceback (most recent call last):
      File "C:\Users\Dell\AppData\Local\Temp\pycharm-packaging\picamera\setup.py", line 101, in run
        with io.open('/proc/cpuinfo', 'r') as cpuinfo:
    FileNotFoundError: [Errno 2] No such file or directory: '/proc/cpuinfo'

    During handling of the above exception, another exception occurred:

    Traceback (most recent call last):
      File "<string>", line 1, in <module>
      File "C:\Users\Dell\AppData\Local\Temp\pycharm-packaging\picamera\setup.py", line 145, in <module>
        main()
      File "C:\Users\Dell\AppData\Local\Temp\pycharm-packaging\picamera\setup.py", line 140, in main
        cmdclass             = {'install': CustomInstallCommand},
      File "C:\Users\Dell\AppData\Local\Programs\Python\Python35\lib\distutils\core.py", line 148, in setup
        dist.run_commands()
      File "C:\Users\Dell\AppData\Local\Programs\Python\Python35\lib\distutils\dist.py", line 955, in run_commands
        self.run_command(cmd)
      File "C:\Users\Dell\AppData\Local\Programs\Python\Python35\lib\distutils\dist.py", line 974, in run_command
        cmd_obj.run()
      File "C:\Users\Dell\AppData\Local\Temp\pycharm-packaging\picamera\setup.py", line 113, in run
        raise ValueError('Unable to open /proc/cpuinfo')
    ValueError: Unable to open /proc/cpuinfo

    ----------------------------------------

  Failed building wheel for picamera
Command "C:\Users\Dell\AppData\Local\Programs\Python\Python35\python.exe -u -c "import setuptools, tokenize;__file__='C:\\Users\\Dell\\AppData\\Local\\Temp\\pycharm-packaging\\picamera\\setup.py';f=getattr(tokenize, 'open', open)(__file__);code=f.read().replace('\r\n', '\n');f.close();exec(compile(code, __file__, 'exec'))" install --record C:\Users\Dell\AppData\Local\Temp\pip-x3ancwkq-record\install-record.txt --single-version-externally-managed --compile --user --prefix=" failed with error code 1 in C:\Users\Dell\AppData\Local\Temp\pycharm-packaging\picamera\
</code>```

Error occured:

```<code>FileNotFoundError: [Errno 2] No such file or directory: '/proc/cpuinfo'
</code>```

Tried to install it with pycharm and still no luck

答:
FileNotFoundError: [Errno 2] No such file or directory: '/proc/cpuinfo'

Cause the file only exists in the linux or unix-like System , not in the Windows system or the mac System.That's why you can't intall successfully.

Body:
I tried to install the picamera to my python 3.5 on windows 10 with pip 9.

Also,i looked online and know that i need to install pyyaml and i did. Its really strange, some suggestion is that the pip need to be the same location as setup.py? which is even more confusing. Anyway, below is what i did, hope it help.

Excuted command:

pip install --user picamera

Command Output:

Collecting picamera
  Using cached picamera-1.13.tar.gz
Building wheels for collected packages: picamera
  Running setup.py bdist_wheel for picamera: started
  Running setup.py bdist_wheel for picamera: finished with status 'error'
  Complete output from command C:\Users\Dell\AppData\Local\Programs\Python\Python35\python.exe -u -c "import setuptools, tokenize;__file__='C:\\Users\\Dell\\AppData\\Local\\Temp\\pycharm-packaging\\picamera\\setup.py';f=getattr(tokenize, 'open', open)(__file__);code=f.read().replace('\r\n', '\n');f.close();exec(compile(code, __file__, 'exec'))" bdist_wheel -d C:\Users\Dell\AppData\Local\Temp\tmpfj3othpnpip-wheel- --python-tag cp35:
  running bdist_wheel
  running build
  running build_py
  creating build
  creating build\lib
  creating build\lib\picamera
  copying picamera\array.py -> build\lib\picamera
  copying picamera\bcm_host.py -> build\lib\picamera
  copying picamera\camera.py -> build\lib\picamera
  copying picamera\color.py -> build\lib\picamera
  copying picamera\display.py -> build\lib\picamera
  copying picamera\encoders.py -> build\lib\picamera
  copying picamera\exc.py -> build\lib\picamera
  copying picamera\frames.py -> build\lib\picamera
  copying picamera\mmal.py -> build\lib\picamera
  copying picamera\mmalobj.py -> build\lib\picamera
  copying picamera\renderers.py -> build\lib\picamera
  copying picamera\streams.py -> build\lib\picamera
  copying picamera\__init__.py -> build\lib\picamera
  running egg_info
  writing picamera.egg-info\PKG-INFO
  writing requirements to picamera.egg-info\requires.txt
  writing dependency_links to picamera.egg-info\dependency_links.txt
  writing top-level names to picamera.egg-info\top_level.txt
  warning: manifest_maker: standard file '-c' not found

  reading manifest file 'picamera.egg-info\SOURCES.txt'
  reading manifest template 'MANIFEST.in'
  no previously-included directories found matching 'debian'
  no previously-included directories found matching 'docs'
  writing manifest file 'picamera.egg-info\SOURCES.txt'
  warning: build_py: byte-compiling is disabled, skipping.

  installing to build\bdist.win-amd64\wheel
  running install
  Traceback (most recent call last):
    File "C:\Users\Dell\AppData\Local\Temp\pycharm-packaging\picamera\setup.py", line 101, in run
      with io.open('/proc/cpuinfo', 'r') as cpuinfo:
  FileNotFoundError: [Errno 2] No such file or directory: '/proc/cpuinfo'

  During handling of the above exception, another exception occurred:

  Traceback (most recent call last):
    File "<string>", line 1, in <module>
    File "C:\Users\Dell\AppData\Local\Temp\pycharm-packaging\picamera\setup.py", line 145, in <module>
      main()
    File "C:\Users\Dell\AppData\Local\Temp\pycharm-packaging\picamera\setup.py", line 140, in main
      cmdclass             = {'install': CustomInstallCommand},
    File "C:\Users\Dell\AppData\Local\Programs\Python\Python35\lib\distutils\core.py", line 148, in setup
      dist.run_commands()
    File "C:\Users\Dell\AppData\Local\Programs\Python\Python35\lib\distutils\dist.py", line 955, in run_commands
      self.run_command(cmd)
    File "C:\Users\Dell\AppData\Local\Programs\Python\Python35\lib\distutils\dist.py", line 974, in run_command
      cmd_obj.run()
    File "C:\Users\Dell\AppData\Roaming\Python\Python35\site-packages\wheel\bdist_wheel.py", line 240, in run
      self.run_command('install')
    File "C:\Users\Dell\AppData\Local\Programs\Python\Python35\lib\distutils\cmd.py", line 313, in run_command
      self.distribution.run_command(command)
    File "C:\Users\Dell\AppData\Local\Programs\Python\Python35\lib\distutils\dist.py", line 974, in run_command
      cmd_obj.run()
    File "C:\Users\Dell\AppData\Local\Temp\pycharm-packaging\picamera\setup.py", line 113, in run
      raise ValueError('Unable to open /proc/cpuinfo')
  ValueError: Unable to open /proc/cpuinfo

  ----------------------------------------
  Running setup.py clean for picamera
Failed to build picamera
Installing collected packages: picamera
  Running setup.py install for picamera: started
    Running setup.py install for picamera: finished with status 'error'
    Complete output from command C:\Users\Dell\AppData\Local\Programs\Python\Python35\python.exe -u -c "import setuptools, tokenize;__file__='C:\\Users\\Dell\\AppData\\Local\\Temp\\pycharm-packaging\\picamera\\setup.py';f=getattr(tokenize, 'open', open)(__file__);code=f.read().replace('\r\n', '\n');f.close();exec(compile(code, __file__, 'exec'))" install --record C:\Users\Dell\AppData\Local\Temp\pip-x3ancwkq-record\install-record.txt --single-version-externally-managed --compile --user --prefix=:
    running install
    Traceback (most recent call last):
      File "C:\Users\Dell\AppData\Local\Temp\pycharm-packaging\picamera\setup.py", line 101, in run
        with io.open('/proc/cpuinfo', 'r') as cpuinfo:
    FileNotFoundError: [Errno 2] No such file or directory: '/proc/cpuinfo'

    During handling of the above exception, another exception occurred:

    Traceback (most recent call last):
      File "<string>", line 1, in <module>
      File "C:\Users\Dell\AppData\Local\Temp\pycharm-packaging\picamera\setup.py", line 145, in <module>
        main()
      File "C:\Users\Dell\AppData\Local\Temp\pycharm-packaging\picamera\setup.py", line 140, in main
        cmdclass             = {'install': CustomInstallCommand},
      File "C:\Users\Dell\AppData\Local\Programs\Python\Python35\lib\distutils\core.py", line 148, in setup
        dist.run_commands()
      File "C:\Users\Dell\AppData\Local\Programs\Python\Python35\lib\distutils\dist.py", line 955, in run_commands
        self.run_command(cmd)
      File "C:\Users\Dell\AppData\Local\Programs\Python\Python35\lib\distutils\dist.py", line 974, in run_command
        cmd_obj.run()
      File "C:\Users\Dell\AppData\Local\Temp\pycharm-packaging\picamera\setup.py", line 113, in run
        raise ValueError('Unable to open /proc/cpuinfo')
    ValueError: Unable to open /proc/cpuinfo

    ----------------------------------------

  Failed building wheel for picamera
Command "C:\Users\Dell\AppData\Local\Programs\Python\Python35\python.exe -u -c "import setuptools, tokenize;__file__='C:\\Users\\Dell\\AppData\\Local\\Temp\\pycharm-packaging\\picamera\\setup.py';f=getattr(tokenize, 'open', open)(__file__);code=f.read().replace('\r\n', '\n');f.close();exec(compile(code, __file__, 'exec'))" install --record C:\Users\Dell\AppData\Local\Temp\pip-x3ancwkq-record\install-record.txt --single-version-externally-managed --compile --user --prefix=" failed with error code 1 in C:\Users\Dell\AppData\Local\Temp\pycharm-packaging\picamera\

Error occured:

FileNotFoundError: [Errno 2] No such file or directory: '/proc/cpuinfo'

Tried to install it with pycharm and still no luck