问:
How to change btn color in Bootstrap
Is there a way to change all .btn properties in Bootstrap? I have tried below ones, but still sometimes it shows the default blue color (say after clicking and removing the mouse etc). How can I change the entire theme altogether?

```<code>.btn-primary, .btn-primary:hover, .btn-primary:active, .btn-primary:visited {
    background-color: #8064A2;
}
</code>```

答:
Just create your own button on:

http://blog.koalite.com/bbg/

add the CSS at the end off your boottrap.min.css

Cheers

Title: How to change btn color in Bootstrap

Body:
Is there a way to change all .btn properties in Bootstrap? I have tried below ones, but still sometimes it shows the default blue color (say after clicking and removing the mouse etc). How can I change the entire theme altogether?

.btn-primary, .btn-primary:hover, .btn-primary:active, .btn-primary:visited {
    background-color: #8064A2;
}


来源: stackexchange

问:
Local Notification banner shows different text than what i set in alert action property
Here is my code to set local notifications for Event but it shows different text for different iphones like , for some iPhone it shows "Slide for more" and for some it shows "Touch to open" where as i set "view details" message: </p>

```<code>UILocalNotification* localNotification = [[UILocalNotification alloc] init];

localNotification.fireDate = fireDate;

localNotification.alertTitle = self.titleCell.propertyValue;

localNotification.alertBody =  self.titleCell.propertyValue;

localNotification.alertAction = @"view details";
</code>```

答:
```<code>-(void)application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification *)notification {

    UIAlertView *notificationAlert = [[UIAlertView alloc] initWithTitle:@"Notification"    message:@"This local notification"
    delegate:nil cancelButtonTitle:@"Ok" otherButtonTitles:nil, nil];

    [notificationAlert show];//use latest alert action

}
</code>```

yourControler.m

```<code>-(IBAction)startLocalNotification {  // Bind this method to UIButton action
NSLog(@"startLocalNotification");

UILocalNotification *notification = [[UILocalNotification alloc] init];
notification.fireDate = [NSDate dateWithTimeIntervalSinceNow:7];
notification.alertBody = @"This is local notification!";
notification.timeZone = [NSTimeZone defaultTimeZone];
notification.soundName = UILocalNotificationDefaultSoundName;
notification.applicationIconBadgeNumber = 10;

[[UIApplication sharedApplication] scheduleLocalNotification:notification];
}
</code>```

you need register for local notification

```<code>if ([UIApplication instancesRespondToSelector:@selector(registerUserNotificationSettings:)]){

[application registerUserNotificationSettings [UIUserNotificationSettings settingsForTypes:UIUserNotificationTypeAlert|UIUserNotificationTypeBadge|UIUserNotificationTypeSound categories:nil]];
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Here is my code to set local notifications for Event but it shows different text for different iphones like , for some iPhone it shows "Slide for more" and for some it shows "Touch to open" where as i set "view details" message:

UILocalNotification* localNotification = [[UILocalNotification alloc] init];

localNotification.fireDate = fireDate;

localNotification.alertTitle = self.titleCell.propertyValue;

localNotification.alertBody =  self.titleCell.propertyValue;

localNotification.alertAction = @"view details";

Body:
-(void)application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification *)notification {

    UIAlertView *notificationAlert = [[UIAlertView alloc] initWithTitle:@"Notification"    message:@"This local notification"
    delegate:nil cancelButtonTitle:@"Ok" otherButtonTitles:nil, nil];

    [notificationAlert show];//use latest alert action

}

yourControler.m

-(IBAction)startLocalNotification {  // Bind this method to UIButton action
NSLog(@"startLocalNotification");

UILocalNotification *notification = [[UILocalNotification alloc] init];
notification.fireDate = [NSDate dateWithTimeIntervalSinceNow:7];
notification.alertBody = @"This is local notification!";
notification.timeZone = [NSTimeZone defaultTimeZone];
notification.soundName = UILocalNotificationDefaultSoundName;
notification.applicationIconBadgeNumber = 10;

[[UIApplication sharedApplication] scheduleLocalNotification:notification];
}

you need register for local notification

if ([UIApplication instancesRespondToSelector:@selector(registerUserNotificationSettings:)]){

[application registerUserNotificationSettings [UIUserNotificationSettings settingsForTypes:UIUserNotificationTypeAlert|UIUserNotificationTypeBadge|UIUserNotificationTypeSound categories:nil]];
}


问:
SQL Prepared Statement & returning type
I have just created a method in my class file, were I insert data into my sql database.

1) Are these prepared statements correct?
2) I need to return a type car for the method (Where could this be done)?
.....As the error I get at the moment is the method must return a type Car (Car is the name of the class file)

```<code>public Car addVehicle(String aLicense, int aJourneys, String aUsername, String aPassword) {
    Car c = new Car();
    try {

        Class.forName("com.mysql.jdbc.Driver");
        Connection conn = DriverManager.getConnection(url + dbName, userName, password);
        statement = conn.createStatement();
        String query = " insert into eflow.registration (cLicense, cJourneys, cUsername, cPassword)"
                + " values (?, ?, ?, ?)";

        PreparedStatement preparedStmt = conn.prepareStatement(query);
        preparedStmt.setString(1, aLicense);
        preparedStmt.setInt(2, aJourneys);
        preparedStmt.setString(3, aUsername);
        preparedStmt.setString(4, aPassword);

        preparedStmt.execute();

        conn.close();

    } catch (Exception e) {
        System.err.println("Got an exception!");
        System.err.println(e.getMessage());

    }
    return c;

}
</code>```

Calling the method returns an error that the method is not applicable for arguments

```<code>//int addingID = Integer.parseInt(enteringID.getText());
                String addingReg = enteringReg.getText();
                int addingJourneys = Integer.parseInt(enteringJourneys.getText());
                String addingUsername = enteringUsername.getText();
                @SuppressWarnings("deprecation")
                String addingPassword = enteringPassword.getText();
                Car newCar = new Car(addingReg, addingJourneys, addingUsername, addingPassword);
                int addStatus = myCar.addVehicle(newCar);
                if (addStatus == 1) {
                    JOptionPane.showMessageDialog(null, "Vehicle Added");
                    enteringID.setText("(eg. 1-999)");
                    enteringReg.setText("(eg. - 162-MH-749)");
                    enteringJourneys.setText("(eg. 7)");
                    enteringUsername.setText("(eg. - username@domain.com)");
                    enteringPassword.setText("");
                }

                else {
                    JOptionPane.showMessageDialog(null, "Error, Please Try Again");
                }
            } catch (Exception f) {
                JOptionPane.showMessageDialog(null, "Error, Please Try Again");
            }
        }
    });
</code>```

答:
Separate the logic!

Use this class to retrieve connection where you need it:

```<code>public class DatabaseConnection
{
    private static final String CONN_URL = "some connection url";
    private static Connection instance = null;

    static
    {
        try
        {
            Class.forName("com.mysql.jdbc.Driver");
        }
        catch (ClassNotFoundException e)
        {
            e.printStackTrace();
        }
    }

    public static synchronized Connection getInstance() throws SQLException
    {
        if (instance == null)
        {
            instance = DriverManager.getConnection(CONN_URL);
        }
        return instance;
    }
}
</code>```

Use it in your function like this:

```<code>public Car addVehicle(String aLicense, int aJourneys, String aUsername, String aPassword)
{
    String sql = "insert into eflow.registration (cLicense, cJourneys, cUsername, cPassword) values (?, ?, ?, ?)";

    try (Connection conn = DatabaseConnection.getInstance(); PreparedStatement prepStatement = conn.prepareStatement(sql))
    {
        Car successfulAdd = new Car();

        prepStatement.setString(1, aLicense);
        prepStatement.setInt(2, aJourneys);
        prepStatement.setString(3, aUsername);
        prepStatement.setString(4, aPassword);

        if (prepStatement.execute())
        {
            return successfulAdd;
        }
    }
    catch (SQLException e)
    {
        e.printStackTrace();
    }
    return null;
}
</code>```

Title: SQL Prepared Statement & returning type

Body:
I have just created a method in my class file, were I insert data into my sql database.

1) Are these prepared statements correct?
2) I need to return a type car for the method (Where could this be done)?
.....As the error I get at the moment is the method must return a type Car (Car is the name of the class file)

public Car addVehicle(String aLicense, int aJourneys, String aUsername, String aPassword) {
    Car c = new Car();
    try {

        Class.forName("com.mysql.jdbc.Driver");
        Connection conn = DriverManager.getConnection(url + dbName, userName, password);
        statement = conn.createStatement();
        String query = " insert into eflow.registration (cLicense, cJourneys, cUsername, cPassword)"
                + " values (?, ?, ?, ?)";

        PreparedStatement preparedStmt = conn.prepareStatement(query);
        preparedStmt.setString(1, aLicense);
        preparedStmt.setInt(2, aJourneys);
        preparedStmt.setString(3, aUsername);
        preparedStmt.setString(4, aPassword);

        preparedStmt.execute();

        conn.close();

    } catch (Exception e) {
        System.err.println("Got an exception!");
        System.err.println(e.getMessage());

    }
    return c;

}

Calling the method returns an error that the method is not applicable for arguments

//int addingID = Integer.parseInt(enteringID.getText());
                String addingReg = enteringReg.getText();
                int addingJourneys = Integer.parseInt(enteringJourneys.getText());
                String addingUsername = enteringUsername.getText();
                @SuppressWarnings("deprecation")
                String addingPassword = enteringPassword.getText();
                Car newCar = new Car(addingReg, addingJourneys, addingUsername, addingPassword);
                int addStatus = myCar.addVehicle(newCar);
                if (addStatus == 1) {
                    JOptionPane.showMessageDialog(null, "Vehicle Added");
                    enteringID.setText("(eg. 1-999)");
                    enteringReg.setText("(eg. - 162-MH-749)");
                    enteringJourneys.setText("(eg. 7)");
                    enteringUsername.setText("(eg. - username@domain.com)");
                    enteringPassword.setText("");
                }

                else {
                    JOptionPane.showMessageDialog(null, "Error, Please Try Again");
                }
            } catch (Exception f) {
                JOptionPane.showMessageDialog(null, "Error, Please Try Again");
            }
        }
    });

Body:
Separate the logic!

Use this class to retrieve connection where you need it:

public class DatabaseConnection
{
    private static final String CONN_URL = "some connection url";
    private static Connection instance = null;

    static
    {
        try
        {
            Class.forName("com.mysql.jdbc.Driver");
        }
        catch (ClassNotFoundException e)
        {
            e.printStackTrace();
        }
    }

    public static synchronized Connection getInstance() throws SQLException
    {
        if (instance == null)
        {
            instance = DriverManager.getConnection(CONN_URL);
        }
        return instance;
    }
}

Use it in your function like this:

public Car addVehicle(String aLicense, int aJourneys, String aUsername, String aPassword)
{
    String sql = "insert into eflow.registration (cLicense, cJourneys, cUsername, cPassword) values (?, ?, ?, ?)";

    try (Connection conn = DatabaseConnection.getInstance(); PreparedStatement prepStatement = conn.prepareStatement(sql))
    {
        Car successfulAdd = new Car();

        prepStatement.setString(1, aLicense);
        prepStatement.setInt(2, aJourneys);
        prepStatement.setString(3, aUsername);
        prepStatement.setString(4, aPassword);

        if (prepStatement.execute())
        {
            return successfulAdd;
        }
    }
    catch (SQLException e)
    {
        e.printStackTrace();
    }
    return null;
}


问:
How to programatically change BDE 'INIT' settings
In Inno setup, I set SHAREDMEMLOCATION and SHAREDMEMSIZE as a registry key for BDE

```<code>; BDE Memory Hacks
Root:HKLM; Subkey: "SOFTWARE\Wow6432Node\Borland\Database Engine\Settings\SYSTEM\INIT"; ValueType: string; ValueName: "SHAREDMEMLOCATION"; ValueData: "0x5000";
Root:HKLM; Subkey: "SOFTWARE\Wow6432Node\Borland\Database Engine\Settings\SYSTEM\INIT"; ValueType: string; ValueName: "SHAREDMEMSIZE"; ValueData: "4096";
</code>```

I'm assuming there's either something I don't know about how BDE works or how the windows registry works. I've found some info to which I'm supposed to do BDE stuff through the BDE api but I can't seem to find a lot of info/libraries to do that.

答:
The place for the SHAREDMEMLOCATION and SHAREDMEMSIZE registry values, in a non-virtualized registry, should be HKEY_LOCAL_MACHINE\SOFTWARE\Borland\Database Engine\Settings\SYSTEM\INIT.

Does your InnoSetup script work, if you remove the "Wow6432Node" part?

See
Inno-Setup doesn't allow access to all registry keys, why?

And "Registry Virtualization" on MSDN https://msdn.microsoft.com/en-us/library/windows/desktop/aa965884(v=vs.85).aspx

You should be able to set the registry values from your BDE application, the settings just go to a Wow6432Node thingy if UAC is turned on.

Body:
In Inno setup, I set SHAREDMEMLOCATION and SHAREDMEMSIZE as a registry key for BDE

; BDE Memory Hacks
Root:HKLM; Subkey: "SOFTWARE\Wow6432Node\Borland\Database Engine\Settings\SYSTEM\INIT"; ValueType: string; ValueName: "SHAREDMEMLOCATION"; ValueData: "0x5000";
Root:HKLM; Subkey: "SOFTWARE\Wow6432Node\Borland\Database Engine\Settings\SYSTEM\INIT"; ValueType: string; ValueName: "SHAREDMEMSIZE"; ValueData: "4096";

I'm assuming there's either something I don't know about how BDE works or how the windows registry works. I've found some info to which I'm supposed to do BDE stuff through the BDE api but I can't seem to find a lot of info/libraries to do that.


问:
How can I get the file system type using API in OSX/macOS?
Now I'm using statfs to get the file system type. I thought that the value of f_type from the returned struct statfs is one of those define in enum fs_type_num from http://opensource.apple.com/source/xnu/xnu-3248.60.10/bsd/vfs/vfs_conf.c

Until macOS 10.12 the value of f_type from struct statfs was 17 for HFS/HFS+. On macOS 10.12 the value is 23, and I don't see this value defined in enum fs_type_num.

It's there a file where the possible values of f_type from struct statfs are defined?

Or, it's there a better API to get the file system type?

答:
Here's what worked for me.

First of all include mount.h.

#include <sys/mount.h>

Then the following will give you the type, subtype and type name.

```<code>struct statfs output;
statfs("/", &output);
NSLog(@"Type: %u", output.f_type);
NSLog(@"Subtype: %u", output.f_fssubtype);
NSLog(@"Type name: %s", output.f_fstypename);
</code>```

This works across macOS and iOS.

And for anyone that's curious here's the results I got across a handful of devices.

macOS on 10.12.3

Type: 23

Subtype: 1

Type name: hfs

iPhone on 10.2.1

Type: 23

Subtype: 3

Type name: hfs

iPad on 10.3

Type: 22

Subtype: 1

Type name: apfs

Body:
Here's what worked for me.

First of all include mount.h.

#include <sys/mount.h>

Then the following will give you the type, subtype and type name.

struct statfs output;
statfs("/", &output);
NSLog(@"Type: %u", output.f_type);
NSLog(@"Subtype: %u", output.f_fssubtype);
NSLog(@"Type name: %s", output.f_fstypename);

This works across macOS and iOS.

And for anyone that's curious here's the results I got across a handful of devices.

macOS on 10.12.3

Type: 23

Subtype: 1

Type name: hfs

iPhone on 10.2.1

Type: 23

Subtype: 3

Type name: hfs

iPad on 10.3

Type: 22

Subtype: 1

Type name: apfs


问:
How to update a table with joining two other tables
We have three tables here, Session table which is connected to Green_fact table with Session_id field. Time_session table is the third table which is made of SessionDate from Session table with a primary key for every single day.

How can I populate the Date_ID field in Green_fact table.
the code below is what I think use, but it doesn't work properly

```<code>update green_fact
   inner join "SESSION" on green_fact."SESSION_ID" = "SESSION"."SessionID"
   inner join "TIME_SESSION" on "TIME_SESSION"."SESSION_DATE" = "SESSION"."SessionDate"
   set green_fact."DATE_ID" = "TIME_SESSION"."ID" where green_fact."SESSION_ID" = "SESSION"."SessionID";
</code>```

答:
In Oracle you can either update a table or an updatetable query, i.e. UPDATE tablename SET ... or UPDATE (SELECT ... FROM ...) SET ....

```<code>update
(
  select gf.date_id, time_session.id as time_session_id
  from green_fact gf
  inner join session s on gf.session_id = s.sessionid
  inner join time_session ts on ts.session_date = s.sessiondate
)
set date_id = time_session_id;
</code>```

This will work, provided the DBMS sees it guaranteed that the query produces one row only per green_fact record (which it should, because of the primary and foreign keys).

Body:
We have three tables here, Session table which is connected to Green_fact table with Session_id field. Time_session table is the third table which is made of SessionDate from Session table with a primary key for every single day.

How can I populate the Date_ID field in Green_fact table.
the code below is what I think use, but it doesn't work properly

update green_fact
   inner join "SESSION" on green_fact."SESSION_ID" = "SESSION"."SessionID"
   inner join "TIME_SESSION" on "TIME_SESSION"."SESSION_DATE" = "SESSION"."SessionDate"
   set green_fact."DATE_ID" = "TIME_SESSION"."ID" where green_fact."SESSION_ID" = "SESSION"."SessionID";

Body:
In Oracle you can either update a table or an updatetable query, i.e. UPDATE tablename SET ... or UPDATE (SELECT ... FROM ...) SET ....

update
(
  select gf.date_id, time_session.id as time_session_id
  from green_fact gf
  inner join session s on gf.session_id = s.sessionid
  inner join time_session ts on ts.session_date = s.sessiondate
)
set date_id = time_session_id;

This will work, provided the DBMS sees it guaranteed that the query produces one row only per green_fact record (which it should, because of the primary and foreign keys).


问:
How to convert firebase timestamp into date and time
I have tried to get date and time from firebase timestamp as follows:

```<code> Date date=new Date(timestamp*1000);
 SimpleDateFormat sfd = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");
 sfd.format(date);
</code>```

but I'm getting results like:

```<code>:02-02-48450 04:21:54
:06-02-48450 10:09:45
:07-02-48450 00:48:35
</code>```

as you can see the year is not as we live.

So, please help me to fix this.

答:
According to Firebase documentation, the types that are available JSON are:

String

Long

Double

Boolean

Map<String, Object>

List<Object>

Quoting another Stack Overflow post, I suggest you use JSON date string format yyyy-MM-dd'T'HH:mm:ss.SSSZ instead of epoch timestamp.

Comparing 1335205543511 to 2012-04-23T18:25:43.511Z, you can noticed that:

It's human readable but also succinct

It sorts correctly

It includes fractional seconds, which can help re-establish chronology

It conforms to ISO 8601

ISO 8601 has been well-established internationally for more than a decade and is endorsed by W3C, RFC3339, and XKCD

ContentLicense: CC BY-SA 4.0

Body:
I have tried to get date and time from firebase timestamp as follows:

 Date date=new Date(timestamp*1000);
 SimpleDateFormat sfd = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");
 sfd.format(date);

but I'm getting results like:

:02-02-48450 04:21:54
:06-02-48450 10:09:45
:07-02-48450 00:48:35

as you can see the year is not as we live.

So, please help me to fix this.


问:
Adding decimals to rangeslider
This is the function I'm using for making the range slider:

```<code>function rangeSlider(id, onDrag) {

    var range = document.getElementById(id),
        dragger = range.children[0],
        draggerWidth = 20, // width of your dragger
        down = false,
        rangeWidth, rangeLeft;

    dragger.style.width = draggerWidth + 'px';
    dragger.style.left = -draggerWidth + 'px';
    dragger.style.marginLeft = (draggerWidth / 2) + 'px';

    range.addEventListener("mousedown", function(e) {
        rangeWidth = this.offsetWidth;
        rangeLeft = this.offsetLeft;
        down = true;
        updateDragger(e);
        return false;
    });

    document.addEventListener("mousemove", function(e) {
        updateDragger(e);
    });

    document.addEventListener("mouseup", function() {
        down = false;
    });

    function updateDragger(e) {
        if (down && e.pageX >= rangeLeft && e.pageX <= (rangeLeft + rangeWidth)) {
            dragger.style.left = e.pageX - rangeLeft - draggerWidth + 'px';
            if (typeof onDrag == "function") onDrag(Math.round(((e.pageX - rangeLeft) / rangeWidth) * 100));
        }
    }

}

// Run!

rangeSlider('range-slider-1', function(value) {
    document.getElementById('test-result').innerHTML = value + '%';
});

rangeSlider('range-slider-2', function(value) {
    document.getElementById('test-result').innerHTML = value + '%';
});
</code>```

JSBIN: http://jsbin.com/yuvekecodo/edit?html,js,output

How can I have the output in decimals?

For example if I set the range from 10 - 100 I want it to be able to have the decimals. 10.01, 10.02, 10.03 ~ 99.97. 99.98, 99.99, etc.

What is the best way to achieve this?

Thanks guys, I'm loosing my mind over this for days.

Cheers.

Thanksl

答:
Please try this may help to get 2 digit decimal point values:

```<code>if (typeof onDrag == "function") onDrag(parseFloat(((e.pageX - rangeLeft) / rangeWidth) * 100).toFixed(2));
</code>```

Use it for like:

```<code> function updateDragger(e) {
    if (down && e.pageX >= rangeLeft && e.pageX <= (rangeLeft + rangeWidth)) {
        dragger.style.left = e.pageX - rangeLeft - draggerWidth + 'px';
        var startpnt=10,endpnt=50,baseval_percent,baseval;
        baseval_percent = ((e.pageX - rangeLeft) / rangeWidth) * 100;
        baseval = (endpnt-startpnt)*baseval_percent/100;
        baseval = baseval+startpnt;
      if (typeof onDrag == "function") onDrag(parseFloat(baseval).toFixed(2));
    }
}
</code>```

Title: Adding decimals to rangeslider

Body:
This is the function I'm using for making the range slider:

function rangeSlider(id, onDrag) {

    var range = document.getElementById(id),
        dragger = range.children[0],
        draggerWidth = 20, // width of your dragger
        down = false,
        rangeWidth, rangeLeft;

    dragger.style.width = draggerWidth + 'px';
    dragger.style.left = -draggerWidth + 'px';
    dragger.style.marginLeft = (draggerWidth / 2) + 'px';

    range.addEventListener("mousedown", function(e) {
        rangeWidth = this.offsetWidth;
        rangeLeft = this.offsetLeft;
        down = true;
        updateDragger(e);
        return false;
    });

    document.addEventListener("mousemove", function(e) {
        updateDragger(e);
    });

    document.addEventListener("mouseup", function() {
        down = false;
    });

    function updateDragger(e) {
        if (down && e.pageX >= rangeLeft && e.pageX <= (rangeLeft + rangeWidth)) {
            dragger.style.left = e.pageX - rangeLeft - draggerWidth + 'px';
            if (typeof onDrag == "function") onDrag(Math.round(((e.pageX - rangeLeft) / rangeWidth) * 100));
        }
    }

}

// Run!

rangeSlider('range-slider-1', function(value) {
    document.getElementById('test-result').innerHTML = value + '%';
});

rangeSlider('range-slider-2', function(value) {
    document.getElementById('test-result').innerHTML = value + '%';
});

JSBIN: http://jsbin.com/yuvekecodo/edit?html,js,output

How can I have the output in decimals?

For example if I set the range from 10 - 100 I want it to be able to have the decimals. 10.01, 10.02, 10.03 ~ 99.97. 99.98, 99.99, etc.

What is the best way to achieve this?

Thanks guys, I'm loosing my mind over this for days.

Cheers.

Thanksl

Body:
Please try this may help to get 2 digit decimal point values:

if (typeof onDrag == "function") onDrag(parseFloat(((e.pageX - rangeLeft) / rangeWidth) * 100).toFixed(2));

Use it for like:

 function updateDragger(e) {
    if (down && e.pageX >= rangeLeft && e.pageX <= (rangeLeft + rangeWidth)) {
        dragger.style.left = e.pageX - rangeLeft - draggerWidth + 'px';
        var startpnt=10,endpnt=50,baseval_percent,baseval;
        baseval_percent = ((e.pageX - rangeLeft) / rangeWidth) * 100;
        baseval = (endpnt-startpnt)*baseval_percent/100;
        baseval = baseval+startpnt;
      if (typeof onDrag == "function") onDrag(parseFloat(baseval).toFixed(2));
    }
}


问:
Converting a list of tuple of 2+ elements to a dictionary
I have a list of tuples which have more that 2 elements where the first element of each tuple is a number which is unique across all the tuples. How can I convert that list of tuples into a dictionary where a key is the 1st element of each tuple?

I know I can use dict(mylist) but it works only for 2-element tuples.

答:
Use CoryKramer's answer if you are using Python 2, avoid the explicit indexing in favor of Extended Iterable Unpacking if you are using Python 3.</p>

```<code>>>> lst = [(1, 'a', 'b'), (2, 'c', 'd')]
>>> {key:tuple(rest) for key, *rest in lst}
{1: ('a', 'b'), 2: ('c', 'd')}
</code>```

Body:
Use CoryKramer's answer if you are using Python 2, avoid the explicit indexing in favor of Extended Iterable Unpacking if you are using Python 3.

>>> lst = [(1, 'a', 'b'), (2, 'c', 'd')]
>>> {key:tuple(rest) for key, *rest in lst}
{1: ('a', 'b'), 2: ('c', 'd')}


问:
Playing a Facebook video in WPF
My application is making API calls to Facebook and returning video URLs, for example:

https://video.xx.fbcdn.net/v/t43.1792-2/17641656_1853451031583994_2664925858824716288_n.mp4?efg=eyJybHIiOjI1OTIsInJsYSI6MTAyNCwidmVuY29kZV90YWciOiJzdmVfaGQifQ%3D%3D&rl=2592&vabr=1728&oh=d503ccbcfe165a8cfc0436fb0a07078e&oe=58E04780

The video uses the H.264 codec.

Is there a way I can get this video to play from the URL in WPF without having to download the video locally?

答:
Give a try on WebBrowser control.

In xaml:

```<code><WebBrowser Name="wbSample"></WebBrowser>
</code>```

In CodeBehind:

```<code>wbSample.Navigate("<<your url>>");
</code>```

Hope that helps.

Title: Playing a Facebook video in WPF

Body:
Give a try on WebBrowser control.

In xaml:

<WebBrowser Name="wbSample"></WebBrowser>

In CodeBehind:

wbSample.Navigate("<<your url>>");

Hope that helps.


问:
Design interrogation on proper use of the "side effect" notion of ngrx/effects
I'm writing this to know if I get it right or not.

On examples found online, the pattern usually goes like this (example here on add/delete actions on the state and on a remote database) :

effects.ts :

```<code>@Effect()
add$ = this.action$
  .ofType(ADD)
  .switchMap((action: Action) => {
     return this.http.put(...)
       .map( response => response.json() )
       .map( response => Observable.of({ type: ADD_SUCCESS, payload: action.payload }))
       .catch( response => Observable.of({ type: ADD_FAIL, payload: response.status }))
</code>```

reducer.ts

```<code>...
switch (action.type){
  case 'ADD_SUCCESS':
     ...
     return new_state;
  case 'ADD_FAIL':
     return state;
}
</code>```

It works, but the speed of execution as felt by the user depends on how fast the network is. So I came up with a pattern that bets on the high probability that no error will be returned from the API:

reducer.ts

```<code>...
switch (action.type){
  case 'ADD':
     ... // make the adequate addition
     return new_state;
  case 'ADD_FAIL':
     ... // delete the addition previously made
     return new_state;
}
</code>```

effects.ts :

```<code>@Effect()
add$ = this.action$
  .ofType(ADD)
  .switchMap((action: Action) => {
     return this.http.put(...)
       .map( response => response.json() )
       .catch( response => Observable.of({ type: ADD_FAIL, payload: action.payload }))
</code>```

In this pattern, the action of saving to database really is a "side effect". In the unlikely but possible case where the API return an error, then a second action is taken to undo the first action.

But I haven't found yet this design in the examples given online: Since I'm an amateur dev, I wonder if I missed something that makes it wrong/dangerous/inefficient in the end.

答:
I wouldn't say there is anything wrong/dangerous/inefficient about it.  Everything is subjective to your program requirements.  If you are dealing with really slow networks, then that needs to be taken into account.

But then in that situation, if a problem goes wrong, then user won't know about it until the Action completes anyway.  With the scenario of a really slow network and having both SUCCESS and FAIL Actions, then the user is more confident in the data they have because a SUCCESS action had to fire.  If you bypass the SUCCESS action, then the user could be working away and not know that their data is incorrect until the FAIL action occurs. The result may be minor, or it may interrupt the user workflow.

Now, in general, the time it takes to submit a put or post request and get a response should be rather short.  And your SUCCESS or FAIL actions should not be so large that they take a long time to compute.

Take for example a checkout system.  A user goes to checkout and posts to the server.  You don't want to route to a confirmation page until you know whether the post was successful or not.  So having separate SUCCESS and FAIL actions are necessary in that situation.

I think it provides the best user experience to be make sure the data they see is accurate and not rolling back changes after a failure.  If the user posts or puts something to the server, the SUCCESS action should then add it to the application state and not before then and also possible user notification.  A FAIL action would handle user notification, potential logging, etc depending upon the application.

Another example:  Say a user is editing an online profile.  If they click 'Save' then you want the user to be notified upon a successful save on the server.  That way they don't navigate away from the page thinking 'I hope it saved, I didn't get a response.'

I would say in most scenarios it is appropriate to have both a SUCCESS and FAIL actions.  But like I said, everything is subjective to your application and what is acceptable to your users, in your environment.

Hope that helps.

Body:
I'm writing this to know if I get it right or not.

On examples found online, the pattern usually goes like this (example here on add/delete actions on the state and on a remote database) :

effects.ts :

@Effect()
add$ = this.action$
  .ofType(ADD)
  .switchMap((action: Action) => {
     return this.http.put(...)
       .map( response => response.json() )
       .map( response => Observable.of({ type: ADD_SUCCESS, payload: action.payload }))
       .catch( response => Observable.of({ type: ADD_FAIL, payload: response.status }))

reducer.ts

...
switch (action.type){
  case 'ADD_SUCCESS':
     ...
     return new_state;
  case 'ADD_FAIL':
     return state;
}

It works, but the speed of execution as felt by the user depends on how fast the network is. So I came up with a pattern that bets on the high probability that no error will be returned from the API:

reducer.ts

...
switch (action.type){
  case 'ADD':
     ... // make the adequate addition
     return new_state;
  case 'ADD_FAIL':
     ... // delete the addition previously made
     return new_state;
}

effects.ts :

@Effect()
add$ = this.action$
  .ofType(ADD)
  .switchMap((action: Action) => {
     return this.http.put(...)
       .map( response => response.json() )
       .catch( response => Observable.of({ type: ADD_FAIL, payload: action.payload }))

In this pattern, the action of saving to database really is a "side effect". In the unlikely but possible case where the API return an error, then a second action is taken to undo the first action.

But I haven't found yet this design in the examples given online: Since I'm an amateur dev, I wonder if I missed something that makes it wrong/dangerous/inefficient in the end.


问:
What does it mean: "the ContentControl does not use the DataTemplate automatically."?
I am struggling to get my datatemplate binding to work; I explicitly bind my DataTemplate to a datatype

```<code><DataTemplate DataType="{x:Type local:ExcelReportVM}">
    <local:ExcelReport DoubleClickHandler="{Binding}">
        <local:ExcelReport.RowColorConverter>
            <local:ReportRowColorConverter/>
        </local:ExcelReport.RowColorConverter>
    </local:ExcelReport>
</DataTemplate>
</code>```

However, I found that even though my control.DataContext is ExcelReportVM, the above DataTemplate is simply not applied.

Then I read in MSDN that

if you are binding a ContentControl to a collection of Task objects,
  the ContentControl does not use the DataTemplate automatically. This
  is because the binding on a ContentControl needs more information to
  distinguish whether you want to bind to an entire collection or the
  individual objects. If your ContentControl is tracking the selection
  of an ItemsControl type, you can set the Path property of the
  ContentControl binding to "/" to indicate that you are interested in
  the current item. For an example, see How to: Bind to a Collection and
  Display Information Based on Selection. Otherwise, you need to specify
  the DataTemplate explicitly by setting the ContentTemplate property.

The explanation sounds very abstract and I have no idea what it is talking about after reading it a few times. Anyone care to explain it with a proper example?

答:
The implicit DataTemplate is applied if you set or bind the Content property of a ContentControl to an instance of an ExcelReportVM object:

```<code><ContentControl x:Name="control" />
</code>```

```<code>content.Content = new ExcelReportVM();
</code>```

Body:
I am struggling to get my datatemplate binding to work; I explicitly bind my DataTemplate to a datatype

<DataTemplate DataType="{x:Type local:ExcelReportVM}">
    <local:ExcelReport DoubleClickHandler="{Binding}">
        <local:ExcelReport.RowColorConverter>
            <local:ReportRowColorConverter/>
        </local:ExcelReport.RowColorConverter>
    </local:ExcelReport>
</DataTemplate>

However, I found that even though my control.DataContext is ExcelReportVM, the above DataTemplate is simply not applied.

Then I read in MSDN that

if you are binding a ContentControl to a collection of Task objects,
  the ContentControl does not use the DataTemplate automatically. This
  is because the binding on a ContentControl needs more information to
  distinguish whether you want to bind to an entire collection or the
  individual objects. If your ContentControl is tracking the selection
  of an ItemsControl type, you can set the Path property of the
  ContentControl binding to "/" to indicate that you are interested in
  the current item. For an example, see How to: Bind to a Collection and
  Display Information Based on Selection. Otherwise, you need to specify
  the DataTemplate explicitly by setting the ContentTemplate property.

The explanation sounds very abstract and I have no idea what it is talking about after reading it a few times. Anyone care to explain it with a proper example?

Body:
The implicit DataTemplate is applied if you set or bind the Content property of a ContentControl to an instance of an ExcelReportVM object:

<ContentControl x:Name="control" />

content.Content = new ExcelReportVM();


问:
Execute the output of previous command line
I need to execute the result of a previous command, but I don't know how I can process.

I have a first command that returns an instruction to log in to the server and then I want to execute it just after.

my-first-command returns: docker login ...

For example:

> my-first-comnand | execute the result of my-first-command

答:
This should do it I believe.

my-first-command | bash


问:
How can I remove a dependency between two gesture recognizers?
I'm using the code below for testing a solution to long press issues in a WKWebView.

I know how to create a dependency between two gesture recognizer but how can I remove it?

```<code>if (gestureRecognizer.state == UIGestureRecognizerStateBegan) {

    // Break

    [gestureRecognizer requireGestureRecognizerToFail:otherGestureRecognizer];
}
else {

    // Fix

    // ...
}
</code>```

Assuming something like:

```<code>[gestureRecognizer shouldntRequireGestureRecognizerToFail:otherGestureRecognizer];
</code>```

or

```<code>[gestureRecognizer removeDependencies];
</code>```

答:
It should be like this</p>

```<code>    for (id gestureRecognizer in self.view.gestureRecognizers){

        //Compare and Remove which gesture you want
        if ([gestureRecognizer isKindOfClass:[UILongPressGestureRecognizer class]])
        {

        [self.view removeGestureRecognizer:gestureRecognizer];

        }
        else if ([gestureRecognizer isKindOfClass:[UITapGestureRecognizer class]]) {

        }

    }
</code>```

Body:
I'm using the code below for testing a solution to long press issues in a WKWebView.

I know how to create a dependency between two gesture recognizer but how can I remove it?

if (gestureRecognizer.state == UIGestureRecognizerStateBegan) {

    // Break

    [gestureRecognizer requireGestureRecognizerToFail:otherGestureRecognizer];
}
else {

    // Fix

    // ...
}

Assuming something like:

[gestureRecognizer shouldntRequireGestureRecognizerToFail:otherGestureRecognizer];

or

[gestureRecognizer removeDependencies];

Body:
It should be like this

    for (id gestureRecognizer in self.view.gestureRecognizers){

        //Compare and Remove which gesture you want
        if ([gestureRecognizer isKindOfClass:[UILongPressGestureRecognizer class]])
        {

        [self.view removeGestureRecognizer:gestureRecognizer];

        }
        else if ([gestureRecognizer isKindOfClass:[UITapGestureRecognizer class]]) {

        }

    }


问:
Run two websites with one laravel installation
How we can use multiple applications with one Laravel installation.

For example:
www.apple.com
www.orange.com

both website will use ONE CORE laravel installation with separate database and all other separate stuff.

Is that possible?
If yes then how?

Also I have done the same thing for CodeIgniter but not sure how i can do with
laravel.

答: You can use this package https://github.com/nWidart/laravel-modules to better organize your code into it's separate websites within the same laravel base code. E.g. you can have Website1 and Website2 modules that has their own Controllers, Models, Views, database migrations, etc. </p>


问:
Android: animated custom views

EDIT 2: new official training guide

The Developers site released a training guide for UI related stuff, this is the index:

Animations Overview

Property Animation Overview

Animate drawable graphics

Reveal or hide a view using animation

Move a View with Animation

Move views using a fling animation

Enlarge a view using a zoom animation

Animate movement using spring physics

Auto animate layout updates

Animate layout changes using a transition

Create a custom transition animation

Start an activity using an animation

If you are interested in any of these, this is the link:
https://developer.android.com/training/animation/

EDIT: Answers sum up

I found 5 ways to animate in Android:

Animate the properties of a View with Property Animation to smoothly change rotation, alpha, scale etc.

Frame Animations (AnimationDrawable): change the pictures quickly, so that it looks animated

Design the images with vectors (VectorDrawable) and animate them by editing them over time with AnimatedVectorDrawable.

Override onDraw() on a View and perform Custom Drawing by painting in the canvas.

Use Lottie, what reproduces animations from After Effects. Many animations available at LottieFiles.

However, Android provides some built-in tools too, such as Scenes (that let you animate the transition among several layouts that share the Views), Shared elements (that lets you make the ilussion of passing a View from one Activity to another one) etc.

Many (if not all) of these features were added in API 21, click here here for more information.

Here are some interesting articles/blogs on animation:

A subcategory on a Google made website called material.io: Creative customization.

How we design a beautiful animation: train animation with animated vectors.

How Android Transitions work.

Animating to infinity: bluetooth animation with vectors

Frame Animations in Android: filling up a heart by images rotation.

Last, a couple interesting tools:

Mac tool to record Android screen on GitHub.

Video to GIF converter online.

Note

I am aware Android provides transformations such as scale, alpha, rotate, translation etc.

Examples

There are 2 examples I would like to look at and compare.

1 - Custom View animations

For example, filling up a glass of water or drawing a path.

2 - Complex View animations

For instance, StackExchange App for Android, login screen animation (couldn't find a video on it, also, didn't check if behaves the same in iOS).

Question

For the first example, I can't think of any other way than playing GIFs, or manually changing images after little time periods.

I do not think this is the case, that's why I would like to ask, (1) do you know how it's done?

Regarding the second example, only one idea came to my mind, and that's setting a Path and moving the View accordingly by passing it somehow after animate(). (2) Is this possible?

Apart from the mentioned above, (3) do you know of other techniques to play animations? (Such as Scene transitions - mentioned in an answer-)

Please share! Thank you.

答:
I would like to suggest a library I've written a while ago (published recently), which allows you to create custom views and add animations to them.

You can find it here and a very simple demo here.
While my demos frankly aren't that impressive, they demonstrate the power of the library and most importantly how to use it.

It works with Android's TimeInterpolator and any of its children (as-well as custom ones).

The animations are drawn entirely using Canvas, the only difference here is that you can get an animated value, which changes according to the TimeInterpolator as a function of time.

You can add as many animations as you would like to your View, control them independently of each-other. And on top of that, you are not limited to drawing non-animation things. There's a dedicated method for that (onDrawStatics).

Title: Android: animated custom views


问:
Chrome modal dialogs don't appear - locks up window
For about the last four months, when using Chrome, any page that opens a modal dialog box, the dialog doesn't appear - but Chrome behaves as though it is there and is unresponsive - it just beeps waiting for the dialog box to be closed.

It doesn't matter if it is a web page - eg Google Calendar, or even the folder selection dialog when saving a bookmark.

I'm using Chrome Version 57.0.2987.110 (64-bit) on Windows 10 Professional Build 15063.

I have tried everything to fix this, but I think there is a DLL or Windows update or another app that introduced this problem.  I first tried disabling all add-ins.  I can't actually delete any add-ins as the add-in delete option throws a modal dialog which never appears and locks up Chrome.  I can't properly uninstall Chrome as the uninstall also throws a Chrome modal dialog which gives the same error.  I've totally uninstalled Chrome manually, deleted every file in Program Files (32 and 64 bit) under Google, deleted very registry entry with Google as a part of the name or value.  I've searched the user files and deleted what I could find.

But after all this, I reinstall and the issue is back.  In use Chrome on several machines, so it's definitely something on this one machine - not a setting or add-in that is common between all machines when I log in to Chrome and synchronise settings.

The only step left is to reinstall Windows, which I'd like to avoid.  Anyone got any ideas?

答:
Found the very simple solution. Go to Advanced settings, under System, turn off Use Hardware Acceleration when available.

I found this the day after I refreshed ie essentially reinstalled Windows.

I had tried everything else with no improvement.


问:
how to make two divs next to each other
unfortunately i dont know how to make these divs(Boxes) next to each other like the picture and put the images of the cars like the image , can anyone please help me

if there is a way with tables or divs please help me to do it

here is the image

答:
.block1{
  background: red;
  height: 150px;
  padding-top: 30%;
}

.block2{
  background: green;
  height: 150px;
  padding-top: 30%;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>
<script src="http://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>

<div class="col-xs-12 text-center">
<div class="col-xs-6">
<div class="block1">
  text
</div>
</div>

<div class="col-xs-6">
<div class="block2">
  text
</div>
</div>
</div></code>```

Title: how to make two divs next to each other

Body:
.block1{
  background: red;
  height: 150px;
  padding-top: 30%;
}

.block2{
  background: green;
  height: 150px;
  padding-top: 30%;
}

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>
<script src="http://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>

<div class="col-xs-12 text-center">
<div class="col-xs-6">
<div class="block1">
  text
</div>
</div>

<div class="col-xs-6">
<div class="block2">
  text
</div>
</div>
</div>


问:
What will be the C# equivalent of this php code?
Here is the PHP code that decrypts the content of $data:

```<code>$data='DwRktl1y8st4k11pSxy2tE9kJMiNlIgV6Gu9ekY8ia2QtoGbdiaiemHeQJ+2MGTZmRKM0IGsiXQyqvXLx/t47FcXmwzZPayS3i6mmYD+qFibbcmA5lGI1uIjT7FSgLM9Xi9QBnTMjIwIEmv6tQaKGGTbhwvUuaP7hek57Xnlk+9CCarkkDlGLed5y+6GedXED0KgMcW1rqXLH7EQub+KzQ==';
$crypttext = base64_decode($data);
$iv_size = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_256, MCRYPT_MODE_ECB);
$iv = mcrypt_create_iv($iv_size, MCRYPT_RAND);
$decrypttext = mcrypt_decrypt(MCRYPT_RIJNDAEL_256, 'AbcNtByIGI1BpgcsAG8GZl8pdwwxyz', $crypttext, MCRYPT_MODE_ECB, $iv);
</code>```

I tried this is .net but it didn't work :

```<code> string data = "DwRktl1y8st4k11pSxy2tE9kJMiNlIgV6Gu9ekY8ia2QtoGbdiaiemHeQJ+2MGTZmRKM0IGsiXQyqvXLx/t47FcXmwzZPayS3i6mmYD+qFibbcmA5lGI1uIjT7FSgLM9Xi9QBnTMjIwIEmv6tQaKGGTbhwvUuaP7hek57Xnlk+9CCarkkDlGLed5y+6GedXED0KgMcW1rqXLH7EQub+KzQ==";

  byte[] arrb = Convert.FromBase64String(data);
  string decodedString = Encoding.UTF8.GetString(arrb);

   const string key = "AbcNtByIGI1BpgcsAG8GZl8pdwwxyz";

   RijndaelManaged aes = new RijndaelManaged();
   aes.KeySize = 256;
   aes.BlockSize = 256;
   aes.Padding = PaddingMode.None;
   aes.Mode = CipherMode.ECB;
   aes.GenerateIV();
   ICryptoTransform decryptor = aes.CreateDecryptor(Encoding.UTF8.GetBytes(key), aes.IV);
   MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(decodedString.Trim()));
   CryptoStream cs = new CryptoStream(ms, decryptor, CryptoStreamMode.Read);

 StreamReader sr = new StreamReader(cs);
 user_data = sr.ReadToEnd();
</code>```

I get the exception "the length of the data to decrypt is invalid".
Can anyone suggest where I might be going wrong ?

答: Not a full solution, but you should get rid of decodedString.  data holds base64 encoded encrypted binary data.  arrb holds 160 bytes of encrypted binary data.  arrb is what you need to pass to your decryption, don't do the conversion from binary to string then string to binary, that loses information.</p>

Body:
Here is the PHP code that decrypts the content of $data:

$data='DwRktl1y8st4k11pSxy2tE9kJMiNlIgV6Gu9ekY8ia2QtoGbdiaiemHeQJ+2MGTZmRKM0IGsiXQyqvXLx/t47FcXmwzZPayS3i6mmYD+qFibbcmA5lGI1uIjT7FSgLM9Xi9QBnTMjIwIEmv6tQaKGGTbhwvUuaP7hek57Xnlk+9CCarkkDlGLed5y+6GedXED0KgMcW1rqXLH7EQub+KzQ==';
$crypttext = base64_decode($data);
$iv_size = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_256, MCRYPT_MODE_ECB);
$iv = mcrypt_create_iv($iv_size, MCRYPT_RAND);
$decrypttext = mcrypt_decrypt(MCRYPT_RIJNDAEL_256, 'AbcNtByIGI1BpgcsAG8GZl8pdwwxyz', $crypttext, MCRYPT_MODE_ECB, $iv);

I tried this is .net but it didn't work :

 string data = "DwRktl1y8st4k11pSxy2tE9kJMiNlIgV6Gu9ekY8ia2QtoGbdiaiemHeQJ+2MGTZmRKM0IGsiXQyqvXLx/t47FcXmwzZPayS3i6mmYD+qFibbcmA5lGI1uIjT7FSgLM9Xi9QBnTMjIwIEmv6tQaKGGTbhwvUuaP7hek57Xnlk+9CCarkkDlGLed5y+6GedXED0KgMcW1rqXLH7EQub+KzQ==";

  byte[] arrb = Convert.FromBase64String(data);
  string decodedString = Encoding.UTF8.GetString(arrb);

   const string key = "AbcNtByIGI1BpgcsAG8GZl8pdwwxyz";

   RijndaelManaged aes = new RijndaelManaged();
   aes.KeySize = 256;
   aes.BlockSize = 256;
   aes.Padding = PaddingMode.None;
   aes.Mode = CipherMode.ECB;
   aes.GenerateIV();
   ICryptoTransform decryptor = aes.CreateDecryptor(Encoding.UTF8.GetBytes(key), aes.IV);
   MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(decodedString.Trim()));
   CryptoStream cs = new CryptoStream(ms, decryptor, CryptoStreamMode.Read);

 StreamReader sr = new StreamReader(cs);
 user_data = sr.ReadToEnd();

I get the exception "the length of the data to decrypt is invalid".
Can anyone suggest where I might be going wrong ?


问:
Does anyone know what is wrong with my formula in cell E17?

The code could not work well. I do not understand what the mistake is. I wrote a formula in cell E17 and dragged it down to E22, but the formula does not work at all.

答:
Use the forth criterion,  Also use MATCH instead of the nested if.</p>

```<code>=VLOOKUP(C17,$B$4:$G$7,MATCH(D17,$B$3:$G$3,0),FALSE)
</code>```

Body:
Use the forth criterion,  Also use MATCH instead of the nested if.

=VLOOKUP(C17,$B$4:$G$7,MATCH(D17,$B$3:$G$3,0),FALSE)


问:
Add Buttons to TAB Bar
I have an iphone app with tab bar controller and nav controller,when going to one page i need to change tab bar contents and add two buttons.

Is it possible?Help is highly appreciated.

Thanks,
Companion

答: check out "Managing Tabs at Runtime" in http://developer.apple.com/library/ios/#featuredarticles/ViewControllerPGforiPhoneOS/TabBarControllers/TabBarControllers.html%23//apple_ref/doc/uid/TP40007457-CH102-SW1</p>

ContentLicense: CC BY-SA 2.5

Title: Add Buttons to TAB Bar


问:
Missing Gradle in Android SDK (using cordova + ionic)
Yep, i searched about this but nothing, just things about the ANDROID_HOME path, but in my case i don't think this is the real problem. When i try to do ionic build android i get this error:

Error: Could not find gradle wrapper within android sdk. Might need to update yo
  ur Android SDK.
  Looked here: C:\Android\sdk\tools\templates\gradle\wrapper

And found that in C:\Android\sdk\tools i dont have "templates" folder, just this:

I see gradle wrapper only in this path C:\Android\sdk\temp\ToolPackage.old01\templates\gradle\wrapper

Why i don't have Gradle in my sdk folder? i am missing something? in SDK manager i have this installed:

Thanks in advance

答:
go to https://developer.android.com/studio/index.html
cheak Download Option and download tools only
extact file and copy the templates folder
and paste in C:\Users(yourunername)\AppData\Local\Android\sdk\tools</p>


问:
Using sigwait with std::thread and pipe
Consider a parallel program that consists of a number of worker threads. These threads have a poll-loop on some file descriptors. The program is supposed to run until ctrl-c is hit / the process receives a SIGINT. The program should never wake up unnecessarily.

I have devised the following combination of sigwait, std::thread, pipe and pthread_sigmask. Note that in the actual application, there are more file descriptors, hence I am not using atomics for shutting down the threads.

```<code>#include <thread>
#include <iostream>
#include <cstdlib>
#include <csignal>

extern "C" {
#include <unistd.h>
#include <fcntl.h>
#include <pthread.h>
#include <poll.h>
}

int fds[2];

void thread_run() {
    struct pollfd pfd = {fds[0], POLLIN, 0};
    int ret = poll(&pfd, 1, -1);
    if (ret != 1) std::terminate();
    if (!pfd.revents & POLLIN) std::abort();
}

int main()
{
    int ret = pipe(fds);
    if (ret) std::abort();

    sigset_t ss;
    sigemptyset(&ss);
    sigaddset(&ss, SIGINT);

    ret = pthread_sigmask(SIG_BLOCK, &ss, NULL);
    if (ret) std::abort();

    std::thread t(thread_run);

    int sig;
    ret = sigwait(&ss, &sig);
    if (ret) std::abort();

    char b = 0;
    ret = write(fds[1], &b, 1);
    if (ret != 1) std::abort();

    t.join();

    close(fds[0]);
    close(fds[1]);
}
</code>```

The program appears to work without any issues.

Is this approach conforming or am I overlooking any caveats?

Are there any specific error cases that might occur in regular operation
and can be handled more gracefully?

Would the program be still correct if i swap std::thread-creation and pthread_sigmask?

答:
This is a standard recommended approach and it works well. See examples section in pthread_sigmask.

Cannot spot any.

It would not be correct. Most signals are process-specific, which means they get delivered to any thread in the process that does not block that signal. Hence, that signal must be blocked in all threads but the one that handles the signal.

You may like to use std::abort call for unexpected situations. std::terminate is called by the C++ runtime when exception handling fails.

Title: Using sigwait with std::thread and pipe

Body:
Consider a parallel program that consists of a number of worker threads. These threads have a poll-loop on some file descriptors. The program is supposed to run until ctrl-c is hit / the process receives a SIGINT. The program should never wake up unnecessarily.

I have devised the following combination of sigwait, std::thread, pipe and pthread_sigmask. Note that in the actual application, there are more file descriptors, hence I am not using atomics for shutting down the threads.

#include <thread>
#include <iostream>
#include <cstdlib>
#include <csignal>

extern "C" {
#include <unistd.h>
#include <fcntl.h>
#include <pthread.h>
#include <poll.h>
}

int fds[2];

void thread_run() {
    struct pollfd pfd = {fds[0], POLLIN, 0};
    int ret = poll(&pfd, 1, -1);
    if (ret != 1) std::terminate();
    if (!pfd.revents & POLLIN) std::abort();
}

int main()
{
    int ret = pipe(fds);
    if (ret) std::abort();

    sigset_t ss;
    sigemptyset(&ss);
    sigaddset(&ss, SIGINT);

    ret = pthread_sigmask(SIG_BLOCK, &ss, NULL);
    if (ret) std::abort();

    std::thread t(thread_run);

    int sig;
    ret = sigwait(&ss, &sig);
    if (ret) std::abort();

    char b = 0;
    ret = write(fds[1], &b, 1);
    if (ret != 1) std::abort();

    t.join();

    close(fds[0]);
    close(fds[1]);
}

The program appears to work without any issues.

Is this approach conforming or am I overlooking any caveats?

Are there any specific error cases that might occur in regular operation
and can be handled more gracefully?

Would the program be still correct if i swap std::thread-creation and pthread_sigmask?


问:
SQL Advice - selecting based upon column in another table
I'm having a bit of headache with some SQL I'm trying to write. Basically, there's 2 tables that have the following fields (only relevant ones to SQL displayed):

Invoices

```<code> accno (fk, linked to id on accounts)
</code>```

Accounts

```<code> id (pk)
 allocateduser
</code>```

Basically, my SQL needs to return all invoices for which account has their current logged in name as the AllocatedUser, which is stored in a Session. Is this simple to do?

Thanks

答:
You can look up all accounts for a user with a where statement, and link the result to the invoices table with a join.  For example:

```<code>select  *
from    invoices i
join    accounts a
on      i.accno = a.id
where   a.allocateduser = 'YourUser'
</code>```

Body:
I'm having a bit of headache with some SQL I'm trying to write. Basically, there's 2 tables that have the following fields (only relevant ones to SQL displayed):

Invoices

 accno (fk, linked to id on accounts)

Accounts

 id (pk)
 allocateduser

Basically, my SQL needs to return all invoices for which account has their current logged in name as the AllocatedUser, which is stored in a Session. Is this simple to do?

Thanks

Body:
You can look up all accounts for a user with a where statement, and link the result to the invoices table with a join.  For example:

select  *
from    invoices i
join    accounts a
on      i.accno = a.id
where   a.allocateduser = 'YourUser'


问:
How to set an image path in src attribute using vue 2
İs that possible to give an attribute like that?

```<code>src="${urlPath}/img/icon-{{flight.OperatingAirline._CompanyShortName}}.png"
</code>```

doesn't works.

答:
Use :v-bind (or shortcut ":") instead of "{{ }}" : v-bind

So :src="Any javascript here !"

```<code>:src="urlPath + '/img/icon-' + flight.OperatingAirline._CompanyShortName + '.png'"
</code>```

urlPath and flight.OperatingAirline._CompanyShortName must be a javascript variable.

Body:
İs that possible to give an attribute like that?

src="${urlPath}/img/icon-{{flight.OperatingAirline._CompanyShortName}}.png"

doesn't works.

Body:
Use :v-bind (or shortcut ":") instead of "{{ }}" : v-bind

So :src="Any javascript here !"

:src="urlPath + '/img/icon-' + flight.OperatingAirline._CompanyShortName + '.png'"

urlPath and flight.OperatingAirline._CompanyShortName must be a javascript variable.


问:
C# List<T> adding inherited items
Let's say that we have 2 classes. The first one is Person

```<code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace People
{
    class Person
    {
        public string FirstName { get; set; }
        public string LastName { get; set; }
    }
}
</code>```

The second one is Teacher

```<code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace People
{
    class Teacher:Person
    {
        public string Position { get; set; }
    }
}
</code>```

And I want to add in a List the teacher

```<code>Teacher teacher = new Teacher() {FirstName="Peter", LastName="Janson",Position="boss" };
            List <Person> people= new List<Person> { };
            people.Add(teacher);
</code>```

How is it possible that I add the teacher in the list when this list is of type  and person only has FirstName and LastName properties and the "teacher" has also a Position property?

答:
This is a question about the fundamental object oriented concept called polymorphism.  A Teacher is a Person, but your list of Person instances only knows that it contains a list of Person instances; it doesn't know anything about classes that derive from Person, nor does it need to.

If you are working with elements in your list, you can determine their type, and then cast them into that type like so:

```<code>foreach (Person x in people)
{
    if (x is Teacher)
    {
        Teacher y = (Teacher) x;
    }
}
</code>```

Then you can access the properties of teacher: y.Position.

Title: C# List<T> adding inherited items

Body:
Let's say that we have 2 classes. The first one is Person

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace People
{
    class Person
    {
        public string FirstName { get; set; }
        public string LastName { get; set; }
    }
}

The second one is Teacher

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace People
{
    class Teacher:Person
    {
        public string Position { get; set; }
    }
}

And I want to add in a List the teacher

Teacher teacher = new Teacher() {FirstName="Peter", LastName="Janson",Position="boss" };
            List <Person> people= new List<Person> { };
            people.Add(teacher);

How is it possible that I add the teacher in the list when this list is of type  and person only has FirstName and LastName properties and the "teacher" has also a Position property?

Body:
This is a question about the fundamental object oriented concept called polymorphism.  A Teacher is a Person, but your list of Person instances only knows that it contains a list of Person instances; it doesn't know anything about classes that derive from Person, nor does it need to.

If you are working with elements in your list, you can determine their type, and then cast them into that type like so:

foreach (Person x in people)
{
    if (x is Teacher)
    {
        Teacher y = (Teacher) x;
    }
}

Then you can access the properties of teacher: y.Position.


问:
Invoking ranges::for_each with lambda and global function
The following code works as expected:

```<code>void foo(auto const &){}

auto const rng{ranges::view::all(v)};
ranges::for_each(rng, [](auto const & r){
    foo(r);
});
</code>```

But the following:

```<code>void foo(auto const &){}

auto const rng{ranges::view::all(v)};
ranges::for_each(rng, &foo);
</code>```

Gives the compilation error:

```<code>template argument deduction/substitution failed:
couldn't deduce template parameter 'F'
</code>```

I took a look at the source but to be honest I couldn't understand the problem.

答:
A function name doesn't represent the function; it is the overload set of the function name.

Your function

```<code>void foo(auto const &){}
</code>```

appears to be using a concepts-esque extension of the language for a terse template function.  In standard C++ it would read:

```<code>template<class T>
void foo(T const &){}
</code>```

A template function isn't a function.  It is an overload set of functions generated by that template.

An overload set of a function name is not a C++ object.  And the things you can pass to functions are C++ objects.

Now, when the overload set of a function name only names one function, the compiler automatically resolves the overload and gives you that function object.

When the overload set of a function name is converted to a pointer-to-function with a fixed signature, overload resolution kicks in and (hopefully) one is selected.

When calling for_each, however, the argument is not a specific fixed signature function pointer.  Instead it is a generic type parameter.  The compiler, at that point, has no way to resolve the overload set of the function name.  It is ambiguous which one you want.

There are two solutions.  One of them is to cast your function overload set into a specific function pointer.  This requires you are explicit.

A second one is top wrap your overload set into a single object.  You can do this with a manual function object with a template operator(), or in C++14 you can do this:

```<code>#define OVERLOADS_OF(...) \
   [](auto&&...args) \
   noexcept(noexcept(__VA_ARGS__(decltype(args)(args)...))) \
   ->decltype( __VA_ARGS__(decltype(args)(args)...) ) \
   { return __VA_ARGS__(decltype(args)(args)...); }
</code>```

which builds a stateless lambda representing the overloads of a global function name.

So:

```<code>void foo(auto const &){}

auto const rng{ranges::view::all(v)};
ranges::for_each(rng, OVERLOADS_OF(foo));
</code>```

if you want to catch fewer corner cases, a simple:

```<code>void foo(auto const &){}

auto const rng{ranges::view::all(v)};
ranges::for_each(rng, [](auto&x){foo(x);});
</code>```

also works in this specific case.

As an aside, there was a C++20 proposal to replace OVERLOADS_OF(foo) with [](auto&&...args)=>foo(decltype(args)(args)...) (generating the same effect as the macro would).  Sadly, the decltype and noexcept features where voted down.

Body:
The following code works as expected:

void foo(auto const &){}

auto const rng{ranges::view::all(v)};
ranges::for_each(rng, [](auto const & r){
    foo(r);
});

But the following:

void foo(auto const &){}

auto const rng{ranges::view::all(v)};
ranges::for_each(rng, &foo);

Gives the compilation error:

template argument deduction/substitution failed:
couldn't deduce template parameter 'F'

I took a look at the source but to be honest I couldn't understand the problem.

Body:
A function name doesn't represent the function; it is the overload set of the function name.

Your function

void foo(auto const &){}

appears to be using a concepts-esque extension of the language for a terse template function.  In standard C++ it would read:

template<class T>
void foo(T const &){}

A template function isn't a function.  It is an overload set of functions generated by that template.

An overload set of a function name is not a C++ object.  And the things you can pass to functions are C++ objects.

Now, when the overload set of a function name only names one function, the compiler automatically resolves the overload and gives you that function object.

When the overload set of a function name is converted to a pointer-to-function with a fixed signature, overload resolution kicks in and (hopefully) one is selected.

When calling for_each, however, the argument is not a specific fixed signature function pointer.  Instead it is a generic type parameter.  The compiler, at that point, has no way to resolve the overload set of the function name.  It is ambiguous which one you want.

There are two solutions.  One of them is to cast your function overload set into a specific function pointer.  This requires you are explicit.

A second one is top wrap your overload set into a single object.  You can do this with a manual function object with a template operator(), or in C++14 you can do this:

#define OVERLOADS_OF(...) \
   [](auto&&...args) \
   noexcept(noexcept(__VA_ARGS__(decltype(args)(args)...))) \
   ->decltype( __VA_ARGS__(decltype(args)(args)...) ) \
   { return __VA_ARGS__(decltype(args)(args)...); }

which builds a stateless lambda representing the overloads of a global function name.

So:

void foo(auto const &){}

auto const rng{ranges::view::all(v)};
ranges::for_each(rng, OVERLOADS_OF(foo));

if you want to catch fewer corner cases, a simple:

void foo(auto const &){}

auto const rng{ranges::view::all(v)};
ranges::for_each(rng, [](auto&x){foo(x);});

also works in this specific case.

As an aside, there was a C++20 proposal to replace OVERLOADS_OF(foo) with [](auto&&...args)=>foo(decltype(args)(args)...) (generating the same effect as the macro would).  Sadly, the decltype and noexcept features where voted down.


问:
Why am I seeing a "member is not recognized or is not accessible" error on my WPF User Control?
I've got a custom user control with a public property that I'd like to be able to set in XAML. Here it is below.

TestControl.xaml

```<code><UserControl x:Class="Scale.Controls.TestControl"
         xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
         xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
         xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
         xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
         mc:Ignorable="d"
         d:DesignHeight="300" d:DesignWidth="300">
</code>```

TestControl.xaml.cs

```<code>using System.Windows.Controls;

namespace MyProject.Controls
{
    public partial class TestControl : UserControl
    {
        public string TestMe { get; set; }
        public TestControl()
        {
            InitializeComponent();
        }
    }
}
</code>```

Then, in my MainWindow.xaml file, I try to include this:

```<code><controls:TestControl TestMe="asdf" />
</code>```

However, even though Visual Studio autocompletes the TestMe property, I then see things with a squiggly underline that says "The member "Test Me" is not recognized or is not accessible," as seen below.

I could have sworn I've done something like this before in other projects. How can I access (i.e. set) the public properties via XAML like this?

答:
Visual Studio 2017

I had exactly the same problem. It was compiling one day ... and then it wasn't. I wasn't using DependencyProperty which shouldn't be needed as above. The properties were appearing in Intellisense but gave the same message when inserted. I cleaned, built, rebuilt, restarted VS, rebooted etc. All to no avail.

Last ditch try ... I removed all the offending attributes and got a clean compile. Then I put them back and it compiled. I really wasn't expecting that. Somehow VS had gotten its knickers in a twist.

Body:
I've got a custom user control with a public property that I'd like to be able to set in XAML. Here it is below.

TestControl.xaml

<UserControl x:Class="Scale.Controls.TestControl"
         xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
         xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
         xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
         xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
         mc:Ignorable="d"
         d:DesignHeight="300" d:DesignWidth="300">

TestControl.xaml.cs

using System.Windows.Controls;

namespace MyProject.Controls
{
    public partial class TestControl : UserControl
    {
        public string TestMe { get; set; }
        public TestControl()
        {
            InitializeComponent();
        }
    }
}

Then, in my MainWindow.xaml file, I try to include this:

<controls:TestControl TestMe="asdf" />

However, even though Visual Studio autocompletes the TestMe property, I then see things with a squiggly underline that says "The member "Test Me" is not recognized or is not accessible," as seen below.

I could have sworn I've done something like this before in other projects. How can I access (i.e. set) the public properties via XAML like this?


问:
Appending to XML with XMLStreamWriter
Basically the app writes the contents of a Collection to XML. I'm using XMLStreamWriter (XMLOutputFactory.newInstance().createXMLStreamWriter(...)) for this purpose.

Works great except for the fact that I can't get how to append data to an existing file. Don't really like the idea of reading all of it first, appending the data in memory and then overwriting. Or is it the only way?

答:
If you're appending a top-level element, you can probably get away with doing what you want. e.g., If you have this file:

```<code><some_element>
  <nested_element>
    ...
  </nested_element>
</some_element>
</code>```

you can most likely get away with appending another some_element element.

However, you're obviously screwed if there's an outer-level element, and you have to append an inner-level one. For instance, suppose you want to add a some_element element to this file:

```<code><data>
  <some_element>
    <nested_element>
      ...
    </nested_element>
  </some_element>
</data>
</code>```

In general, you're far better off reparsing the document, then rewriting it. If it's small, use a DOM-based parser; it's easier. If the file is big, then use a SAX-based one.

OwnerDisplayName: gsmd

Title: Appending to XML with XMLStreamWriter

Body:
If you're appending a top-level element, you can probably get away with doing what you want. e.g., If you have this file:

<some_element>
  <nested_element>
    ...
  </nested_element>
</some_element>

you can most likely get away with appending another some_element element.

However, you're obviously screwed if there's an outer-level element, and you have to append an inner-level one. For instance, suppose you want to add a some_element element to this file:

<data>
  <some_element>
    <nested_element>
      ...
    </nested_element>
  </some_element>
</data>

In general, you're far better off reparsing the document, then rewriting it. If it's small, use a DOM-based parser; it's easier. If the file is big, then use a SAX-based one.

OwnerDisplayName: Brian Clapper


问:
How to get alert dialog with four images with selection
I want to create dialog button like attached image .
In this dialog four images will appear for selection .

```<code>String[] image = new String[]{R.mipmap.ic_launcher1, R.mipmap.ic_launcher2,R.mipmap.ic_launcher3, R.mipmap.ic_launcher4};
 AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("Choose a container size");
        builder.setItems(image, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                // the user clicked on colors[which]
            }
        });
        builder.show();
</code>```

答:
You can use Gridview inside DialogBox for displaying image with selection, please try this

Dialo box:

```<code>  final Dialog dialog = new Dialog(this);
    dialog.setContentView(R.layout.layout_dialog);

    GridView gridView = (GridView)dialog.findViewById(R.id.dialog_gv);
    gridView.setAdapter(new DialogBaseAdapter());
    dialog.setTitle("Your title");
    dialog.setCancelable(true);
    dialog.show();
</code>```

Dialog view xml

```<code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">

<GridView
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:numColumns="2"
    android:stretchMode="columnWidth"
    android:columnWidth="72dp"
    android:id="@+id/dialog_gv"
    android:horizontalSpacing="2dp"
    android:verticalSpacing="2dp"></GridView>

</LinearLayout>
</code>```

DialogBaseAdapter.class

```<code>class DialogBaseAdapter extends BaseAdapter{
    @Override
    public int getCount() {
        return 4;
    }

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

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

    @Override
    public View getView(int i, View view, ViewGroup viewGroup) {
        view = LayoutInflater.from(context).inflate(R.layout.dialog_grid_item, viewGroup,false);
        return view;
    }
}
</code>```

Dialog Grid Adapter item xml:

```<code><?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="96dp"
android:orientation="vertical">

<ImageView
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/app_header_color"
    android:src="@drawable/arrow" />

<CheckBox
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentRight="true"
    android:layout_alignParentTop="true" />
</RelativeLayout>
</code>```

Body:
I want to create dialog button like attached image .
In this dialog four images will appear for selection .

String[] image = new String[]{R.mipmap.ic_launcher1, R.mipmap.ic_launcher2,R.mipmap.ic_launcher3, R.mipmap.ic_launcher4};
 AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("Choose a container size");
        builder.setItems(image, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                // the user clicked on colors[which]
            }
        });
        builder.show();

Body:
You can use Gridview inside DialogBox for displaying image with selection, please try this

Dialo box:

  final Dialog dialog = new Dialog(this);
    dialog.setContentView(R.layout.layout_dialog);

    GridView gridView = (GridView)dialog.findViewById(R.id.dialog_gv);
    gridView.setAdapter(new DialogBaseAdapter());
    dialog.setTitle("Your title");
    dialog.setCancelable(true);
    dialog.show();

Dialog view xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">

<GridView
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:numColumns="2"
    android:stretchMode="columnWidth"
    android:columnWidth="72dp"
    android:id="@+id/dialog_gv"
    android:horizontalSpacing="2dp"
    android:verticalSpacing="2dp"></GridView>

</LinearLayout>

DialogBaseAdapter.class

class DialogBaseAdapter extends BaseAdapter{
    @Override
    public int getCount() {
        return 4;
    }

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

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

    @Override
    public View getView(int i, View view, ViewGroup viewGroup) {
        view = LayoutInflater.from(context).inflate(R.layout.dialog_grid_item, viewGroup,false);
        return view;
    }
}

Dialog Grid Adapter item xml:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="96dp"
android:orientation="vertical">

<ImageView
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/app_header_color"
    android:src="@drawable/arrow" />

<CheckBox
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentRight="true"
    android:layout_alignParentTop="true" />
</RelativeLayout>


问:
how to refresh token servicestack typescript
On servicestack it says that for regular client it should be like that but for typescript it should be somehow different. Anyone knows how to do it?</p>

```<code>var client = new JsonServiceClient(baseUrl);
client.OnAuthenticationRequired = () => {
    client.BearerToken = authClient.Send(new Authenticate()).BearerToken;
};
</code>```

答:
Support for onAuthenticationRequired and refreshToken was added to the TypeScript servicestack-client in v0.0.32 where they can be used to transparently handle 401 Unauthorized Responses and re-authenticate the JsonServiceClient from within the callback before it automatically retries the original failed request:

Transparently handle 401 Unauthorized Responses

If the server returns a 401 Unauthorized Response either because the client was Unauthenticated or the configured Bearer Token or API Key used had expired (or was invalidated), you can use onAuthenticationRequired callback to re-configure the client before automatically retrying the original request, e.g:

```<code>client.onAuthenticationRequired = async () => {
    const authClient = new JsonServiceClient(authBaseUrl);
    authClient.userName = userName;
    authClient.password = password;
    const response = await authClient.get(new Authenticate());
    client.bearerToken = response.bearerToken;
};

//Automatically retries requests returning 401 Responses with new bearerToken
var response = await client.get(new Secured());
</code>```

Automatically refresh JWT Tokens

With the Refresh Token support in JWT you can use the refreshToken property to instruct the Service Client to automatically fetch new JWT Tokens behind-the-scenes before automatically retrying failed requests due to invalid or expired JWTs, e.g:

```<code>//Authenticate to get a new Refresh Token
const authClient = new JsonServiceClient(authBaseUrl);
authClient.userName = userName;
authClient.password = password;
const authResponse = await authClient.get(new Authenticate());

//Configure client with RefreshToken
client.refreshToken = authResponse.RefreshToken;

//Clients will automatically retrieve new JWT Tokens as needed
var response = await client.get(new Secured());
</code>```

Send Refresh Tokens to an alternate server

Use the refreshTokenUri property when refresh tokens need to be sent to a different ServiceStack Server that issues new JWT Tokens, e.g:

```<code>client.refreshToken = refreshToken;
client.refreshTokenUri = authBaseUrl + "/access-token";
</code>```

Body:
On servicestack it says that for regular client it should be like that but for typescript it should be somehow different. Anyone knows how to do it?

var client = new JsonServiceClient(baseUrl);
client.OnAuthenticationRequired = () => {
    client.BearerToken = authClient.Send(new Authenticate()).BearerToken;
};

Body:
Support for onAuthenticationRequired and refreshToken was added to the TypeScript servicestack-client in v0.0.32 where they can be used to transparently handle 401 Unauthorized Responses and re-authenticate the JsonServiceClient from within the callback before it automatically retries the original failed request:

Transparently handle 401 Unauthorized Responses

If the server returns a 401 Unauthorized Response either because the client was Unauthenticated or the configured Bearer Token or API Key used had expired (or was invalidated), you can use onAuthenticationRequired callback to re-configure the client before automatically retrying the original request, e.g:

client.onAuthenticationRequired = async () => {
    const authClient = new JsonServiceClient(authBaseUrl);
    authClient.userName = userName;
    authClient.password = password;
    const response = await authClient.get(new Authenticate());
    client.bearerToken = response.bearerToken;
};

//Automatically retries requests returning 401 Responses with new bearerToken
var response = await client.get(new Secured());

Automatically refresh JWT Tokens

With the Refresh Token support in JWT you can use the refreshToken property to instruct the Service Client to automatically fetch new JWT Tokens behind-the-scenes before automatically retrying failed requests due to invalid or expired JWTs, e.g:

//Authenticate to get a new Refresh Token
const authClient = new JsonServiceClient(authBaseUrl);
authClient.userName = userName;
authClient.password = password;
const authResponse = await authClient.get(new Authenticate());

//Configure client with RefreshToken
client.refreshToken = authResponse.RefreshToken;

//Clients will automatically retrieve new JWT Tokens as needed
var response = await client.get(new Secured());

Send Refresh Tokens to an alternate server

Use the refreshTokenUri property when refresh tokens need to be sent to a different ServiceStack Server that issues new JWT Tokens, e.g:

client.refreshToken = refreshToken;
client.refreshTokenUri = authBaseUrl + "/access-token";


问:
Android Studio Project Files are Missing
I was working on app and it was opened in Android Studio. It was all perfect but when after some browsing i clicked on android studio window. it says there are no files opened.

and when I checked in file explorer, all of my project files are removed except .idea folder.I did spend a lot of days on it. I cannot let this happen to me. what possible solutions of this problem?

I tried windows folder recovery, no benefit.

答:
Before trying any thing. Back-up the project you have.

You can look through local history in Android Studio. In Android Studio -> VCS(Menu) -> Local History -> show History

Select an early restore point that includes your sources-> right mouse -> Revet

strongly I'd recommend you to use git to avoid such as situation. The code is Our Precious Don't lose it.


问:
Conditional inner join statement (VBA/SQL) to generate multiple values
I'm quite new to VBA/SQL and I'm trying to execute a conditional inner join.

I have two tables with a column in common ("CRM" and "CodeCRM") and I would like to obtain an email adress from table2 ("Desks") when something is triggered (CodeBlocage = 101) in table1 ("Flux") in order to add it to an automatic email.

```<code>Dim StrDestinataire As String
Select Case Strtable
   Case "Flux", "GAFIJOUR"

    Dim cn As ADODB.Connection
    Dim rs As ADODB.Recordset
    Dim Y As String
    Dim sSql As String

    Set cn = CurrentProject.Connection

    sSql = "Select AddMailCRM from Desks Inner Join Flux on Desks.CODECRM = Flux.CRM WHERE Flux.CODEBLOCAGE = '101'"

    Set rs = cn.Execute(sSql)

    If Not rs.BOF And Not rs.EOF Then
        Y = rs.Fields("AddMailCRM").Value
    End If

    StrDestinataire =  Y

    cn.Close
</code>```

Everything works great except that it should be returning more than one value for the email adress. Any leads?

Thank you

答:
Solved.</p>

```<code>Dim StrDestinataire As String
Select Case Strtable
   Case "Flux", "GAFIJOUR"

    Dim cn As ADODB.Connection
    Dim rs As ADODB.Recordset
    Dim Y As String
    Dim sSql As String

    Set cn = CurrentProject.Connection

    sSql = "Select AddMailCRM from Desks Inner Join Flux on Desks.CODECRM = Flux.CRM WHERE Flux.CODEBLOCAGE = '101'"

    Set rs = cn.Execute(sSql)

    If Not rs.BOF And Not rs.EOF Then
        Y = rs.Fields("AddMailCRM").Value
    End If

    StrDestinataire =  Y

    cn.Close
</code>```

Body:
I'm quite new to VBA/SQL and I'm trying to execute a conditional inner join.

I have two tables with a column in common ("CRM" and "CodeCRM") and I would like to obtain an email adress from table2 ("Desks") when something is triggered (CodeBlocage = 101) in table1 ("Flux") in order to add it to an automatic email.

Dim StrDestinataire As String
Select Case Strtable
   Case "Flux", "GAFIJOUR"

    Dim cn As ADODB.Connection
    Dim rs As ADODB.Recordset
    Dim Y As String
    Dim sSql As String

    Set cn = CurrentProject.Connection

    sSql = "Select AddMailCRM from Desks Inner Join Flux on Desks.CODECRM = Flux.CRM WHERE Flux.CODEBLOCAGE = '101'"

    Set rs = cn.Execute(sSql)

    If Not rs.BOF And Not rs.EOF Then
        Y = rs.Fields("AddMailCRM").Value
    End If

    StrDestinataire =  Y

    cn.Close

Everything works great except that it should be returning more than one value for the email adress. Any leads?

Thank you

Body:
Solved.

Dim StrDestinataire As String
Select Case Strtable
   Case "Flux", "GAFIJOUR"

    Dim cn As ADODB.Connection
    Dim rs As ADODB.Recordset
    Dim Y As String
    Dim sSql As String

    Set cn = CurrentProject.Connection

    sSql = "Select AddMailCRM from Desks Inner Join Flux on Desks.CODECRM = Flux.CRM WHERE Flux.CODEBLOCAGE = '101'"

    Set rs = cn.Execute(sSql)

    If Not rs.BOF And Not rs.EOF Then
        Y = rs.Fields("AddMailCRM").Value
    End If

    StrDestinataire =  Y

    cn.Close


问:
How to wait for a SQL Server database rollback to complete?
When using the ADO.NET SqlClient classes, there are a few ways in which a transaction can be rolled back. Either by explicitly calling SqlTransaction.Rollback, or having a command timeout, or a transaction timeout within a transaction scope etc.

But how can I detect when this rollback has completed when using SQL Server (2012 or later)? For a long running transaction the rollback may take a long time, and it is usually quite IO-intensive on the database, so it may not be wise to retry the transaction immediately. In our situation we would like to wait for the rollback to complete.

(In our specific case the rollback occurs because of a transaction timeout using the TransactionScope class, but I would prefer a method that would work for any kind of rollback).

I have looked at the sys.dm_exec_requests which looked promising at first. It had a command type of KILL/ROLLBACK at first, and reported the progress percentage. (If I captured the SPID from the original transaction I would be able to poll this table and wait for it to complete). However, about halfway through I noticed it changed to AWAITING COMMAND instead (while the rollback was still being performed).

I also looked at KILL <SPID> WITH STATUSONLY. This seems to generate an error if there is no rollback in progress, so it could work as well for a polling approach, but I noticed that if I ran a BEGIN TRAN ... ROLLBACK TRAN batch from SSMS, this reported an error saying that no rollback was in progress when it was rolling back. The dm_exec_requests table reported ROLLBACK TRANSACTION as the command type in this case.

So how can I wait for a rollback to complete in a reliable way?

答:
You can see transaction activity with sp_who based on spid. The column status will tell you the current state of transaction and change from rollback or disapear when finished.

If you want to have a feedback on .NET, use SqlChangeMonitor(example) to cache your result and wait for your SqlChangeMonitor to notify a change from rollback.

In case you fix your problem of timeout you can look to:

Using IsolationLevel.ReadCommitted. That way your .NET code will wait for completion of your Commit or Rollback.

(It will look like cmd.Connection.BeginTransaction(IsolationLevel.ReadCommitted) with cmd of type SqlCommand )


问:
Xcode 8 shows error that provisioning profile doesn't include signing certificate
Xcode 8 shows error that provisioning profile doesn't include signing certificate.

This issue is with Xcode-8 only with Xcode 7, same provisioning profile showing related identified certificate.

答:
There are many ways to fix this, like enabling automatic signing etc. But if you want to understand the reason for this error you need to look at the error message.

It says that the provisioning profile you have selected in the "General tab", does not contain the signing certificate you selected in the "Build settings" -> "Code Signing Identity".

Usually this happens if a distribution certificate has been selected for the debug identity under "Build settings" -> "Code Signing Identity".

If this happens under "Signing (Debug)" it might also be that the "Signing Identity" -> "iOS Development" is not included in the provisioning profile.


问:
Build Android App with Node.js
I'm trying to build my html5 with node.js to mobile application (Android APK). It is like a chat box for those who are connected on the same wireless network. But my problem is this, when I'm coding my app on my desktop, I'm using the node.js software to run the codes. How will I do it then in building my mobile App (Android APK)?

If that's not possible, what do you recommend?

答: Node.js can only act as a server ( back-end ) of your app . You could use your HTML file and convert it to an apk with a compiler , but it's not worth the trouble. If you run your node server on a localhost you can access it with your phones browser with " your ip:port" . But again, your computer must always be running node , or deploy it to a cloud service like heroku to use it anywhere.</p>

Title: Build Android App with Node.js