问:
Swift MultipeerConnectivity crash DateComponents unconditionallyBridgeFromObjectiveC
I have a repeatable crash that ends in a EXC_BREAKPOINT like in the image below:

Steps to reproduce the crash:

Connect two devices

Begin a transfer using func sendResource(at resourceURL: URL,
     withName resourceName: String,
       toPeer peerID: MCPeerID,
withCompletionHandler completionHandler: ((Error?) -> Void)? = nil) -> Progress?

Disconnect the device that initiated the transfer by calling func disconnect()

Edit: Another way to reproduce the crash, by calling Progress.cancel() Steps:

Connect two devices

Begin a transfer and store the Progress object let progress: Progress = session.sendResource(...)

call cancel on the progress object, causing a crash on the other device progress.cancel()

My code at the line didFinishReceivingResourceWithName:

```<code>func session(_ session: MCSession, didFinishReceivingResourceWithName resourceName: String, fromPeer peerID: MCPeerID, at localURL: URL, withError error: Error?) {
    // transfer to local URL
    MusicDownloadRequestor.sharedInstance.finishReceivingSongUploadAtLocalURL(tempUrl: localURL)
}
</code>```

Doesn't look like my code is called in the stack trace...

```<code>* thread #25: tid = 0x806ec, 0x0000000100944af4 libswiftFoundation.dylib`static Foundation.DateComponents._unconditionallyBridgeFromObjectiveC (Swift.Optional<__ObjC.NSDateComponents>) -> Foundation.DateComponents with unmangled suffix "_merged" + 96, queue = 'com.apple.MCSession.callbackQueue', stop reason = EXC_BREAKPOINT (code=1, subcode=0x100944af4)
frame #0: 0x0000000100944af4 libswiftFoundation.dylib`static Foundation.DateComponents._unconditionallyBridgeFromObjectiveC (Swift.Optional<__ObjC.NSDateComponents>) -> Foundation.DateComponents with unmangled suffix "_merged" + 96
frame #1: 0x0000000100114c60 MyAppSwift`@objc NetworkManager.session(MCSession, didFinishReceivingResourceWithName : String, fromPeer : MCPeerID, at : URL, withError : Error?) -> () + 168 at NetworkManager.swift:0
frame #2: 0x00000001a1dda028 MultipeerConnectivity`__79-[MCSession syncCloseIncomingStream:forPeer:state:error:reason:removeObserver:]_block_invoke + 208
frame #3: 0x0000000100c05258 libdispatch.dylib`_dispatch_call_block_and_release + 24
frame #4: 0x0000000100c05218 libdispatch.dylib`_dispatch_client_callout + 16
frame #5: 0x0000000100c12aec libdispatch.dylib`_dispatch_queue_serial_drain + 1136
frame #6: 0x0000000100c08ce0 libdispatch.dylib`_dispatch_queue_invoke + 672
frame #7: 0x0000000100c14e2c libdispatch.dylib`_dispatch_root_queue_drain + 584
frame #8: 0x0000000100c14b78 libdispatch.dylib`_dispatch_worker_thread3 + 140
frame #9: 0x000000018c2a32a0 libsystem_pthread.dylib`_pthread_wqthread + 1288
frame #10: 0x000000018c2a2d8c libsystem_pthread.dylib`start_wqthread + 4
</code>```

Update #1: added stack trace as text

Update #2: Found a possible lead on the crash, here's another crash with unconditionallyBridgeFromObjectiveC

I think that the problem is the URL is being passed to didFinishReceivingResourceWithName as nil but the parameter is non-optional. This makes sense, since if the file fails to transfer there will not be a final resting place for the URL. Is there any way I can fix this or intercept the error?

I think this is an Apple bug. Does anyone have a suggestion for doing a work-around?

答:
Just letting people know that this bug has been fixed with the release of xcode 9 beta 1. According to documentation and my tests, the at localurl parameter is now optional as expected : https://developer.apple.com/documentation/multipeerconnectivity/mcsessiondelegate/1406984-session

Just update to the last version of xcode9 to resolve this issue.

Body:
I have a repeatable crash that ends in a EXC_BREAKPOINT like in the image below:

Steps to reproduce the crash:

Connect two devices

Begin a transfer using func sendResource(at resourceURL: URL,
     withName resourceName: String,
       toPeer peerID: MCPeerID,
withCompletionHandler completionHandler: ((Error?) -> Void)? = nil) -> Progress?

Disconnect the device that initiated the transfer by calling func disconnect()

Edit: Another way to reproduce the crash, by calling Progress.cancel() Steps:

Connect two devices

Begin a transfer and store the Progress object let progress: Progress = session.sendResource(...)

call cancel on the progress object, causing a crash on the other device progress.cancel()

My code at the line didFinishReceivingResourceWithName:

func session(_ session: MCSession, didFinishReceivingResourceWithName resourceName: String, fromPeer peerID: MCPeerID, at localURL: URL, withError error: Error?) {
    // transfer to local URL
    MusicDownloadRequestor.sharedInstance.finishReceivingSongUploadAtLocalURL(tempUrl: localURL)
}

Doesn't look like my code is called in the stack trace...

* thread #25: tid = 0x806ec, 0x0000000100944af4 libswiftFoundation.dylib`static Foundation.DateComponents._unconditionallyBridgeFromObjectiveC (Swift.Optional<__ObjC.NSDateComponents>) -> Foundation.DateComponents with unmangled suffix "_merged" + 96, queue = 'com.apple.MCSession.callbackQueue', stop reason = EXC_BREAKPOINT (code=1, subcode=0x100944af4)
frame #0: 0x0000000100944af4 libswiftFoundation.dylib`static Foundation.DateComponents._unconditionallyBridgeFromObjectiveC (Swift.Optional<__ObjC.NSDateComponents>) -> Foundation.DateComponents with unmangled suffix "_merged" + 96
frame #1: 0x0000000100114c60 MyAppSwift`@objc NetworkManager.session(MCSession, didFinishReceivingResourceWithName : String, fromPeer : MCPeerID, at : URL, withError : Error?) -> () + 168 at NetworkManager.swift:0
frame #2: 0x00000001a1dda028 MultipeerConnectivity`__79-[MCSession syncCloseIncomingStream:forPeer:state:error:reason:removeObserver:]_block_invoke + 208
frame #3: 0x0000000100c05258 libdispatch.dylib`_dispatch_call_block_and_release + 24
frame #4: 0x0000000100c05218 libdispatch.dylib`_dispatch_client_callout + 16
frame #5: 0x0000000100c12aec libdispatch.dylib`_dispatch_queue_serial_drain + 1136
frame #6: 0x0000000100c08ce0 libdispatch.dylib`_dispatch_queue_invoke + 672
frame #7: 0x0000000100c14e2c libdispatch.dylib`_dispatch_root_queue_drain + 584
frame #8: 0x0000000100c14b78 libdispatch.dylib`_dispatch_worker_thread3 + 140
frame #9: 0x000000018c2a32a0 libsystem_pthread.dylib`_pthread_wqthread + 1288
frame #10: 0x000000018c2a2d8c libsystem_pthread.dylib`start_wqthread + 4

Update #1: added stack trace as text

Update #2: Found a possible lead on the crash, here's another crash with unconditionallyBridgeFromObjectiveC

I think that the problem is the URL is being passed to didFinishReceivingResourceWithName as nil but the parameter is non-optional. This makes sense, since if the file fails to transfer there will not be a final resting place for the URL. Is there any way I can fix this or intercept the error?

I think this is an Apple bug. Does anyone have a suggestion for doing a work-around?


来源: stackexchange

问:
(iOS) IAP working but missing in client's Beta using Fabric
I' working on an (ancient) app from a client. The app have been on the App Store for many years and it has working in-app purchases currently.

I'm updating this app and everything IAP related seems to work ok but when I send a beta to my client's test accounts using Crashlytics, the app works ok but the IAP are unavailable for them. Is there any configuration I should do in order to make the IAP working?

答:
Mike from Fabric here. There are many different things you need to do in order to allow for IAP testing. Apple's documentation is good on this, but a few key points from the doc.

To test in-app purchase, you need to create products to purchase and test accounts to make the purchases. iTunes Connect allows you to create and manage in-app purchases and test user accounts. You must complete the following steps in iTunes Connect:

Create test user accounts:  Apple provides a testing environment, called the sandbox, which allows you to test your in-app purchases without incurring any financial charges. The sandbox environment uses special test user accounts rather than your regular iTunes Connect accounts to test in-app purchase. See Sandbox Testers in the iTunes Connect Developer Guide for more information about creating test user accounts.

Note: You can use the same test user accounts to test both your iOS, macOS, and tvOS applications. Each in-app purchase test user account is tied to one and only one email address. As such, you cannot reuse an existing email address with another test user account.

To Test your application in the sandbox environment:

1) Sign out of the Store in the Settings application on your testing device.

2) Set the run destination of your application to an iOS or tvOS Device in Xcode.

3) Build and run your application from Xcode.

Important: Use your test user account when prompted by StoreKit to confirm a purchase from within your application.
StoreKit connects to the sandbox environment when you launch your application from Xcode, from your test device (iOS and tvOS), or from the Finder (macOS). It connects to a production environment for applications that were downloaded from the App Store. You must not use your test user account to sign into the production environment. This will result in your test user account becoming invalid. Invalid test accounts cannot be used to test in-app purchase again.

ContentLicense: CC BY-SA 3.0


问:
Lucene 6 How to avoid duplicate entries
Story:
I need to search for a list of transactionIds be a given username query e.g "Peter M*".

Question: How is it possible to keep the stored transactionIds unique?

I have populated my index with following documents:

```<code>Document doc = new Document();
doc.add(new StoredField(TRANSACTION_ID, data.getTransactionId()));
doc.add(new TextField(MARCHANT_NAME, data.getName(), Store.NO));
</code>```

I have tried allready two strategies (to avoid duplicate entries) to add a new entry.

IndexWriter.updateDocument with a Term holding the transactionId to store.

Search for the current transactionId, delete it and store it:

答: You are using a StoredField for the TRANSACTION_ID field. That means it can be retrieved from the index, but is not indexed and can't be searched, and as such, it can't be used as a key to updateDocument. Use a StringField, instead.

Title: Lucene 6 How to avoid duplicate entries

Body:
Story:
I need to search for a list of transactionIds be a given username query e.g "Peter M*".

Question: How is it possible to keep the stored transactionIds unique?

I have populated my index with following documents:

Document doc = new Document();
doc.add(new StoredField(TRANSACTION_ID, data.getTransactionId()));
doc.add(new TextField(MARCHANT_NAME, data.getName(), Store.NO));

I have tried allready two strategies (to avoid duplicate entries) to add a new entry.

IndexWriter.updateDocument with a Term holding the transactionId to store.

Search for the current transactionId, delete it and store it:


问:
how to use run time permissions for database in android
I have problem with runtime permission for database.I dont know how use and write permissions for my code. and I very search but at lost to understand.
the code is:

```<code>public class G  {
public static Context        context;
public static SQLiteDatabase database;
public static final String   DIR_SDCARD   = Environment.getExternalStorageDirectory().getAbsolutePath();
public static final String   DIR_DATABASE = DIR_SDCARD + "/database-test";
@Override
public void onCreate() {
    super.onCreate();
    context = this.getApplicationContext();
   // new File(DIR_DATABASE).mkdirs();
    File file=new File(DIR_DATABASE);
    file.mkdirs();
    database = SQLiteDatabase.openOrCreateDatabase(DIR_DATABASE + "/database.sqlite", null);
    database.execSQL("CREATE  TABLE  IF NOT EXISTS person (person_name TEXT NOT NULL ," +
                " person_family TEXT NOT NULL , " +
                " person_password TEXT NOT NULL   )");
}
</code>```

}
please help me

答:
You don't need Android run-time permissions for your own database in Android. All you are gonna do is create the database and do some CRUD operations on it.

The database resides inside your app's allocated space so that does not need any permissions. However if you are going to read/Write to sdCard then you might need those run time permissions.

You can find a detailed documentation right here,

https://developer.android.com/training/permissions/requesting.html

Body:
I have problem with runtime permission for database.I dont know how use and write permissions for my code. and I very search but at lost to understand.
the code is:

public class G  {
public static Context        context;
public static SQLiteDatabase database;
public static final String   DIR_SDCARD   = Environment.getExternalStorageDirectory().getAbsolutePath();
public static final String   DIR_DATABASE = DIR_SDCARD + "/database-test";
@Override
public void onCreate() {
    super.onCreate();
    context = this.getApplicationContext();
   // new File(DIR_DATABASE).mkdirs();
    File file=new File(DIR_DATABASE);
    file.mkdirs();
    database = SQLiteDatabase.openOrCreateDatabase(DIR_DATABASE + "/database.sqlite", null);
    database.execSQL("CREATE  TABLE  IF NOT EXISTS person (person_name TEXT NOT NULL ," +
                " person_family TEXT NOT NULL , " +
                " person_password TEXT NOT NULL   )");
}

}
please help me


问:
How to add line breaks to prevent overly long lines?
I just read the best practices of Python scripts. I found recommended length should not exceed 80 characters per line.

So in my script more than  100 characters are exist.

I have break the lines and below are examples.

Example 1

```<code>self.remote_conn_pre.connect("self.hostname, "
    "username=self.username, password=self.password, "
     "look_for_keys=False, allow_agent=False")
</code>```

Example 2

```<code> self.remote_conn.send(""create bigdata\n" "
    " .format(pending.upper(), (total) + 9)")
</code>```

Example 3

```<code> print ("This is the first line of my text {} "
 "which will be joined to a second {}.".format(a,b))
</code>```

Could any one please correct me if I am doing anything wrong and help me determine the best ways to break long lines into small lines.

答:
Python supports splitting up lines using the backslash \ character, like so:

```<code>d = "one two three " \
    "four five six"

print d
</code>```

Prints one two three four five six

Body:
I just read the best practices of Python scripts. I found recommended length should not exceed 80 characters per line.

So in my script more than  100 characters are exist.

I have break the lines and below are examples.

Example 1

self.remote_conn_pre.connect("self.hostname, "
    "username=self.username, password=self.password, "
     "look_for_keys=False, allow_agent=False")

Example 2

 self.remote_conn.send(""create bigdata\n" "
    " .format(pending.upper(), (total) + 9)")

Example 3

 print ("This is the first line of my text {} "
 "which will be joined to a second {}.".format(a,b))

Could any one please correct me if I am doing anything wrong and help me determine the best ways to break long lines into small lines.

Body:
Python supports splitting up lines using the backslash \ character, like so:

d = "one two three " \
    "four five six"

print d

Prints one two three four five six


问:
Access diagonal elements in a 2D array stored in a 1D array
Suppose my 2D array is:

```<code>int a[4][4] = {
               1,0,0,0,
               0,1,0,0,
               0,0,1,0,
               0,0,0,1
              };
</code>```

Suppose its stored in a 1D array as:

```<code>int b[16]={1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1};
</code>```

In general, assume a is of size m x n and b is of size mn.
Using a single for loop I want to be able to access all the diagonal elements, i.e output should be 1 1 1 1.

I understand A[i][j] = B[i*n+j]; but if I'm only using a single for loop, I don't have a j index.

Any help would be highly appreciated.

Edit:

Note let m=n be for all practical purposes. The interface I'm using expects two separate variables for row and column size. But I'm only working with square matrices.

答:
You only needto consider the number of columns.</p>

```<code>#define COLUMNS 4
#define ROWS 4

b[16]={1,0,0,0,
       0,1,0,0,
       0,0,1,0,
       0,0,0,1};

int i = 0;
for(; i < ROWS; i++ ){
  printf("%d\t",b[COLUMNS*i+i]);
}
</code>```

Body:
Suppose my 2D array is:

int a[4][4] = {
               1,0,0,0,
               0,1,0,0,
               0,0,1,0,
               0,0,0,1
              };

Suppose its stored in a 1D array as:

int b[16]={1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1};

In general, assume a is of size m x n and b is of size mn.
Using a single for loop I want to be able to access all the diagonal elements, i.e output should be 1 1 1 1.

I understand A[i][j] = B[i*n+j]; but if I'm only using a single for loop, I don't have a j index.

Any help would be highly appreciated.

Edit:

Note let m=n be for all practical purposes. The interface I'm using expects two separate variables for row and column size. But I'm only working with square matrices.

Body:
You only needto consider the number of columns.

#define COLUMNS 4
#define ROWS 4

b[16]={1,0,0,0,
       0,1,0,0,
       0,0,1,0,
       0,0,0,1};

int i = 0;
for(; i < ROWS; i++ ){
  printf("%d\t",b[COLUMNS*i+i]);
}


问:
Is it possible to work android 2.2 application on other android versions (1.5 to 2.1)?
I developed one application based on android 2.2 version.
Is it possible to work that application on other android versions (1.5 to 2.1)? </p>

答:
Be aware than in 1.5 multi-size screens are not manage.
I'm not sure about the effect of density.</p>

ContentLicense: CC BY-SA 2.5


问:
Zoom in IE breaks adjacent elements
I have several adjacent elements that I calculate their position according to another element on the page.

The elements should surround that element.

The problem is that on IE, when you zoom to a certain point, there appears a single line of pixels between those surrounding elements.

I created a jsfiddle to demonstrate the issue:

https://jsfiddle.net/0vcomjsk/

The divs in the fiddle are positioned according the the height and top of the previous div:

```<code>#first {
  width: 100%;
  height: 100px;
  top: 0;
  left: 0;
}

#second {
  width: 50%;
  left: 50%;
  top: 100px;
  height: 100px;
 }

 #third {
   width: 100%;
   top: 200px;
   left: 0;
   height: 100px;
 }
</code>```

As you can see in that fiddle, the red elements, surround a rectangle on the left.

picture:

If you open this page on IE and zoom enough, you would be able to see an empty line of pixels between those divs.

picture:

答:
I ended up changing the opacity of the divs to 100%, making them overlap each other and putting all of them in a new div with opacity 50%.
It solved the issue :)</p>

Title: Zoom in IE breaks adjacent elements

Body:
I have several adjacent elements that I calculate their position according to another element on the page.

The elements should surround that element.

The problem is that on IE, when you zoom to a certain point, there appears a single line of pixels between those surrounding elements.

I created a jsfiddle to demonstrate the issue:

https://jsfiddle.net/0vcomjsk/

The divs in the fiddle are positioned according the the height and top of the previous div:

#first {
  width: 100%;
  height: 100px;
  top: 0;
  left: 0;
}

#second {
  width: 50%;
  left: 50%;
  top: 100px;
  height: 100px;
 }

 #third {
   width: 100%;
   top: 200px;
   left: 0;
   height: 100px;
 }

As you can see in that fiddle, the red elements, surround a rectangle on the left.

picture:

If you open this page on IE and zoom enough, you would be able to see an empty line of pixels between those divs.

picture:


问:
Buttons won't go side by side
I'm trying to get the menu button and search button to sit side by side in the header, but nothing seems to be working. Below is an image of what I'm currently getting as well as the relevant markup and style for the buttons.

What I'm getting:

HTML:

```<code><div class="navbar navbar-default navbar-fixed-top">
                    <div class="navbar-header">
                        <button type="button" id="searchbuttonmobile" ><img src="~/Images/SearchBtn.png" /></button>
                        <button type="button" onclick="openNav()" class="navbar-toggle" data-toggle="collapse" data-target=".mobilenav" id="menubutton">
                            <img src="~/Images/MobileMenuBtn.png" />
                        </button>
</div>
</code>```

CSS:

```<code>/*----------------------------------*/
/*---MOBILE MENU LOGO AND BUTTONS---*/
/*----------------------------------*/
@media (max-width: 400px) {

    #logo {
        width: 100px;
    }

    #smokefree {
        padding-left: 5px;
        padding-top: 20px;
    }

        #smokefree a {
            font-size: 14pt;
        }

    #menubutton img {
        width: 43px;
        height: 44px;
    }

    #searchbuttonmobile {
        padding: 9px 0px;
    }

    #searchbuttonmobile img {
        width: 43px;
        height: 44px;
    }
}

/*--------------------------------------*/
/*--------MENU BUTTON APPEARANCE--------*/
/*--------------------------------------*/
@media (max-width: 1279px) {
    .navbar-header {
        float: none;
    }

    .navbar-left, .navbar-right {
        float: none !important;
    }

    .navbar-toggle {
        display: block;
        margin-top: 0px;
        margin-right: 0px;
        margin-bottom: 10px;
    }

    .navbar-default .navbar-toggle:hover, .navbar-default .navbar-toggle:focus {
        background-color: transparent;
    }

    .navbar-collapse {
        border-top: 1px solid transparent;
        box-shadow: inset 0 1px 0 rgba(255,255,255,0.1);
    }

    .navbar-fixed-top {
        top: 0;
        border-width: 0 0 1px;
    }

    .navbar-collapse.collapse, .desktopnav {
        display: none !important;
    }

    #mobilenav {
        display: block;
    }

    #searchbuttonmobile {
        padding: 9px 10px;
        display: inline;
    }

    .navbar-nav {
        float: none !important;
        margin-top: 7.5px;
    }

        .navbar-nav > li {
            float: none;
        }

            .navbar-nav > li > a {
                padding-top: 10px;
                padding-bottom: 10px;
            }

    .collapse.in {
        display: block !important;
    }
}
</code>```

答:
You can change button display to inline-block as ThisGuyHasTwoThumbs written on comment.
also you can float buttons to right.

```<code>.navbar-header button{
float:right;
display:block;
}
</code>```

or use:

```<code>.navbar-header button{
display:inline-block;
}
</code>```

Title: Buttons won't go side by side

Body:
I'm trying to get the menu button and search button to sit side by side in the header, but nothing seems to be working. Below is an image of what I'm currently getting as well as the relevant markup and style for the buttons.

What I'm getting:

HTML:

                        <button type="button" id="searchbuttonmobile" ></button>
                        <button type="button" onclick="openNav()" class="navbar-toggle" data-toggle="collapse" data-target=".mobilenav" id="menubutton">

                        </button>

CSS:

/*----------------------------------*/
/*---MOBILE MENU LOGO AND BUTTONS---*/
/*----------------------------------*/
@media (max-width: 400px) {

    #logo {
        width: 100px;
    }

    #smokefree {
        padding-left: 5px;
        padding-top: 20px;
    }

        #smokefree a {
            font-size: 14pt;
        }

    #menubutton img {
        width: 43px;
        height: 44px;
    }

    #searchbuttonmobile {
        padding: 9px 0px;
    }

    #searchbuttonmobile img {
        width: 43px;
        height: 44px;
    }
}

/*--------------------------------------*/
/*--------MENU BUTTON APPEARANCE--------*/
/*--------------------------------------*/
@media (max-width: 1279px) {
    .navbar-header {
        float: none;
    }

    .navbar-left, .navbar-right {
        float: none !important;
    }

    .navbar-toggle {
        display: block;
        margin-top: 0px;
        margin-right: 0px;
        margin-bottom: 10px;
    }

    .navbar-default .navbar-toggle:hover, .navbar-default .navbar-toggle:focus {
        background-color: transparent;
    }

    .navbar-collapse {
        border-top: 1px solid transparent;
        box-shadow: inset 0 1px 0 rgba(255,255,255,0.1);
    }

    .navbar-fixed-top {
        top: 0;
        border-width: 0 0 1px;
    }

    .navbar-collapse.collapse, .desktopnav {
        display: none !important;
    }

    #mobilenav {
        display: block;
    }

    #searchbuttonmobile {
        padding: 9px 10px;
        display: inline;
    }

    .navbar-nav {
        float: none !important;
        margin-top: 7.5px;
    }

        .navbar-nav > li {
            float: none;
        }

            .navbar-nav > li > a {
                padding-top: 10px;
                padding-bottom: 10px;
            }

    .collapse.in {
        display: block !important;
    }
}

Body:
You can change button display to inline-block as ThisGuyHasTwoThumbs written on comment.
also you can float buttons to right.

.navbar-header button{
float:right;
display:block;
}

or use:

.navbar-header button{
display:inline-block;
}


问:
Compulsary requirement to take and store users photo using Xam.Plugin.Media
I have a PCL type app and I'm using the Xam.Plugin.Media plugin. I need it to ensure a user submits a photo from the camera before they can continue.

To do this I show the camera page from a button click event and I want to ensure that in case the user cancels out of this that the app launches the camera again, this would repeat until a photograph is stored.

Currenty my app falls in the onActivityResumed method of the MainApplication file when the user cancels out of the camera

Attached photo of my code, My code.

```<code> private async void TakePicture()
        {
            await CrossMedia.Current.Initialize();

            if (!CrossMedia.Current.IsCameraAvailable || !CrossMedia.Current.IsTakePhotoSupported)
            {
                await App.Current.MainPage.DisplayAlert("No Camera", ":( No camera available.", "Aceptar");
            }

            file = await CrossMedia.Current.TakePhotoAsync(new Plugin.Media.Abstractions.StoreCameraMediaOptions
            {
                Directory = "Sample",
                Name = "test.jpg",
                PhotoSize = PhotoSize.Small,
            });

            //IsRunning = true;

            if (file != null)
            {
                ImageSource = ImageSource.FromStream(() =>
                {
                    var stream = file.GetStream();
                    return stream;
                });
            }

            IsRunning = false;
        }
</code>```

答:
Aside from the fact that it is usually a bit of a UX issue to force a user into anything nowadays, the question still has some merits.

this is the approach that I would consider, it involves recursion.

```<code>    private async void TakePicture()
    {
        await CrossMedia.Current.Initialize();

        if (!CrossMedia.Current.IsCameraAvailable || !CrossMedia.Current.IsTakePhotoSupported)
        {
            await App.Current.MainPage.DisplayAlert("No Camera", ":( No camera available.", "Aceptar");
        }

        file = await CrossMedia.Current.TakePhotoAsync(new Plugin.Media.Abstractions.StoreCameraMediaOptions
        {
            Directory = "Sample",
            Name = "test.jpg",
            PhotoSize = PhotoSize.Small,
        });

        //IsRunning = true;

        if (file != null)
        {
            ImageSource = ImageSource.FromStream(() =>
            {
                var stream = file.GetStream();
                return stream;
            });
        }
        else
        {
            // Recursion - I believe that this would continue until the file is not null, then it would carry on.
            TakePicture();
        }

        IsRunning = false;
    }
</code>```

I can't say I use recursion that often, but I think it might do the trick here.

Body:
I have a PCL type app and I'm using the Xam.Plugin.Media plugin. I need it to ensure a user submits a photo from the camera before they can continue.

To do this I show the camera page from a button click event and I want to ensure that in case the user cancels out of this that the app launches the camera again, this would repeat until a photograph is stored.

Currenty my app falls in the onActivityResumed method of the MainApplication file when the user cancels out of the camera

Attached photo of my code, My code.

 private async void TakePicture()
        {
            await CrossMedia.Current.Initialize();

            if (!CrossMedia.Current.IsCameraAvailable || !CrossMedia.Current.IsTakePhotoSupported)
            {
                await App.Current.MainPage.DisplayAlert("No Camera", ":( No camera available.", "Aceptar");
            }

            file = await CrossMedia.Current.TakePhotoAsync(new Plugin.Media.Abstractions.StoreCameraMediaOptions
            {
                Directory = "Sample",
                Name = "test.jpg",
                PhotoSize = PhotoSize.Small,
            });

            //IsRunning = true;

            if (file != null)
            {
                ImageSource = ImageSource.FromStream(() =>
                {
                    var stream = file.GetStream();
                    return stream;
                });
            }

            IsRunning = false;
        }

Body:
Aside from the fact that it is usually a bit of a UX issue to force a user into anything nowadays, the question still has some merits.

this is the approach that I would consider, it involves recursion.

    private async void TakePicture()
    {
        await CrossMedia.Current.Initialize();

        if (!CrossMedia.Current.IsCameraAvailable || !CrossMedia.Current.IsTakePhotoSupported)
        {
            await App.Current.MainPage.DisplayAlert("No Camera", ":( No camera available.", "Aceptar");
        }

        file = await CrossMedia.Current.TakePhotoAsync(new Plugin.Media.Abstractions.StoreCameraMediaOptions
        {
            Directory = "Sample",
            Name = "test.jpg",
            PhotoSize = PhotoSize.Small,
        });

        //IsRunning = true;

        if (file != null)
        {
            ImageSource = ImageSource.FromStream(() =>
            {
                var stream = file.GetStream();
                return stream;
            });
        }
        else
        {
            // Recursion - I believe that this would continue until the file is not null, then it would carry on.
            TakePicture();
        }

        IsRunning = false;
    }

I can't say I use recursion that often, but I think it might do the trick here.


问:
JWPlayer - Get all playlist ids
Is there any way to retrieve all playlist ids from an account?
Using JSON call.

I want this endpoint: /v2/playlists/

See the platform API:
https://developer.jwplayer.com/jw-platform/docs/delivery-api-reference/

答:
To pull a list of your playlist ids you will want to use the Management API:
https://developer.jwplayer.com/jw-platform/reference/v1/methods/channels/videos/show.html</p>

Title: JWPlayer - Get all playlist ids


问:
JavaScript color contraster
I'm looking for a technique where we could programmatically pick the best color contrast to apply on text over HTML elements of different (unpredictable) background colors.

Since the HTML elements will have different colors, we're looking for a technique that will be able to determine what is the color of the content behind the text, and then adapt the text's color to use the one with the best contrast.

I'm quite sure this can't be CSS only, I've looked for Jquery solutions but couldn't find any... anyone has a clue?

[UPDATE] :
Based on the first replies, I guess I need to rephrase. Imagine that I'm building a image sharing service and I want to allow people to tag on the pictures themselves. The pictures can be of any color. How can I pick up the right color of the tags, for each different picture?

答:
There is now a property called mix-blend-mode in CSS (currently just in draft) that can be used to achieve something similar to what you want.

```<code>.contrasting-text {
    mix-blend-mode: difference;
}
</code>```

CodePen someone has put together demonstrating this: https://codepen.io/thebabydino/pen/JNWqLL

Title: JavaScript color contraster

Body:
There is now a property called mix-blend-mode in CSS (currently just in draft) that can be used to achieve something similar to what you want.

.contrasting-text {
    mix-blend-mode: difference;
}

CodePen someone has put together demonstrating this: https://codepen.io/thebabydino/pen/JNWqLL


问:
Make WebView ignore scene CSS in JavaFX
When I load a site / html using javafx.scene.web.WebView that site seems to be affected by my scene custom styling. A minimal example to demonstrate the issue.

Main.java

```<code>public class Main extends Application {

    @Override
    public void start(Stage primaryStage) throws Exception {
        VBox root = new VBox();

        primaryStage.setScene(new Scene(root, 900, 900));

        String css = Main.class.getResource("/test.css").toExternalForm();
        primaryStage.getScene().getStylesheets().add(css);

        WebView webView = new WebView();

        root.getChildren().add(webView);

        webView.getEngine().load("http://google.pl");

        primaryStage.show();
    }

    public static void main(String[] args) {
        launch(args);
    }
}
</code>```

test.css

```<code>.text-area,
.text-field {
  -fx-background-color: red;
}
</code>```

This results in

Ultimately I wish for a method like webview.getEngine().dontInheritStyles()of course there is none and I couldn't find any method of doing it otherwise. Tried:

```<code>webView.getStylesheets().clear();
webView.setStyle(null);
webView.getStyleClass().clear();
</code>```

none of them worked. One way that I think could make this work (haven't tried it yet tho) would be to open the webview in a sub window which doesn't use the same scene, however I want the webview to be embeded in my existing application view so that option would be my last resort and I rather avoid it.

答:
You can use some kind of hack, such as a combination of JavaFX and Swing.

You have two classes:

JFXPanel - which allows you to embed a JavaFX control into Swing

SwingNode - which allows you to embed a Swing control into JavaFX

You can combine the use of the JFXPanel and SwingNode classes in the wrapper class:

```<code>public class Styleless<T extends Parent> extends StackPane {
    private T root;

    public Styleless(T root) {
        this.root = root;

        JFXPanel jfxPanel = new JFXPanel();
        jfxPanel.setScene(new Scene(root));

        SwingNode swingNode = new SwingNode();
        swingNode.setContent(jfxPanel);

        getChildren().add(swingNode);
    }

    public T getRoot() {
        return root;
    }
}
</code>```

And you can use it like this:

```<code>public class Main extends Application {

    @Override
    public void start(Stage primaryStage) throws Exception {
        VBox root = new VBox();
        primaryStage.setScene(new Scene(root, 900, 900));

        String css = Main.class.getResource("/test.css").toExternalForm();
        primaryStage.getScene().getStylesheets().add(css);

        WebView webView = new WebView();
        webView.getEngine().load("http://google.pl");

        Styleless<WebView> webViewStyleless = new Styleless<>(webView);

        root.getChildren().add(webViewStyleless);
        VBox.setVgrow(webViewStyleless, Priority.ALWAYS);

        primaryStage.show();
    }

    public static void main(String[] args) {
        launch(args);
    }
}
</code>```

Title: Make WebView ignore scene CSS in JavaFX

Body:
When I load a site / html using javafx.scene.web.WebView that site seems to be affected by my scene custom styling. A minimal example to demonstrate the issue.

Main.java

public class Main extends Application {

    @Override
    public void start(Stage primaryStage) throws Exception {
        VBox root = new VBox();

        primaryStage.setScene(new Scene(root, 900, 900));

        String css = Main.class.getResource("/test.css").toExternalForm();
        primaryStage.getScene().getStylesheets().add(css);

        WebView webView = new WebView();

        root.getChildren().add(webView);

        webView.getEngine().load("http://google.pl");

        primaryStage.show();
    }

    public static void main(String[] args) {
        launch(args);
    }
}

test.css

.text-area,
.text-field {
  -fx-background-color: red;
}

This results in

Ultimately I wish for a method like webview.getEngine().dontInheritStyles()of course there is none and I couldn't find any method of doing it otherwise. Tried:

webView.getStylesheets().clear();
webView.setStyle(null);
webView.getStyleClass().clear();

none of them worked. One way that I think could make this work (haven't tried it yet tho) would be to open the webview in a sub window which doesn't use the same scene, however I want the webview to be embeded in my existing application view so that option would be my last resort and I rather avoid it.

Body:
You can use some kind of hack, such as a combination of JavaFX and Swing.

You have two classes:

JFXPanel - which allows you to embed a JavaFX control into Swing

SwingNode - which allows you to embed a Swing control into JavaFX

You can combine the use of the JFXPanel and SwingNode classes in the wrapper class:

public class Styleless<T extends Parent> extends StackPane {
    private T root;

    public Styleless(T root) {
        this.root = root;

        JFXPanel jfxPanel = new JFXPanel();
        jfxPanel.setScene(new Scene(root));

        SwingNode swingNode = new SwingNode();
        swingNode.setContent(jfxPanel);

        getChildren().add(swingNode);
    }

    public T getRoot() {
        return root;
    }
}

And you can use it like this:

public class Main extends Application {

    @Override
    public void start(Stage primaryStage) throws Exception {
        VBox root = new VBox();
        primaryStage.setScene(new Scene(root, 900, 900));

        String css = Main.class.getResource("/test.css").toExternalForm();
        primaryStage.getScene().getStylesheets().add(css);

        WebView webView = new WebView();
        webView.getEngine().load("http://google.pl");

        Styleless<WebView> webViewStyleless = new Styleless<>(webView);

        root.getChildren().add(webViewStyleless);
        VBox.setVgrow(webViewStyleless, Priority.ALWAYS);

        primaryStage.show();
    }

    public static void main(String[] args) {
        launch(args);
    }
}


问:
How to bind Instanceproperty to viewmodel, view is not updated
Problem:

My Viewmodel creates a instance of a controller mycontroller and the property Busy shall be passed to the View and updated in the View based on the controller state, but my View doesn't get updated. The other property Busy2 is updated based on the current state. Bindablebase implements the I

Question:

Why the property Busy in the ViewModel is not updated? The mycontroller.Busy property is updating, but not the view.

Framework & Tools:

PRISM 6.3.0

Fody.Propertychanged

View:

```<code><TextBlock Text="{Binding Path=Busy}"></TextBlock>
<TextBlock Text="{Binding Path=Busy2}"></TextBlock>
</code>```

ViewModel:

```<code>public class Controller
    {
        public bool Busy { get; private set; }

        public async void GetValue()
        {
            Busy = true;
            await Task.Delay(5000);
            Busy = false;
        }
    }

    public class MyViewModel : BindableBase
    {
        private readonly Controller _mycontroller;
        public DelegateCommand<string> RunCommand { get; private set; }

        // This property is not updated in the view
        public bool Busy
        {
            get { return _mycontroller.Busy; }
        }

        // Works as aspected
        public bool Busy2 { get; set; }

        public MyViewModel()
        {
            _mycontroller = new Controller();
            RunCommand = new DelegateCommand<string>(Run, Canrun).ObservesProperty((() => _mycontroller.Busy));
        }

        private bool Canrun(string arg)
        {
            return _mycontroller.Busy != true;
        }

        private void Run(string obj)
        {

            Busy2 = true;
            _mycontroller.GetValue();

        }
    }
</code>```

Update:

I added the Bindablebase from Prism, because is implement the INotifyPropertyChanged, but the view is still not updated.
I refactored the code and I set a breakpoint to  set { SetProperty(ref _busy, value); } and the breakpoint is never reached.

I removed the Propertychanged.Fody nuget package too.

ViewModel:

```<code>   public class Controller : BindableBase
    {
        private bool _busy;
        public bool Busy
        {
            get { return _busy; }
            set { SetProperty(ref _busy, value); }
        }

        public Controller()
        {

        }

        public void DoWork1()
        {
            for (var i = 0; i < 10; i++)
            {
                Thread.Sleep(1000);
                _busy = !_busy;
                Debug.WriteLine(_busy.ToString());
            }
        }

        public void DoWork2()
        {
            _busy = !_busy;

        }
    }

    public class MainWindowViewModel : BindableBase
    {
        private Controller mycontroller;
        private string _title = "Prism Unity Application";

        public DelegateCommand RunCommand { get; private set; }

        public string Title
        {
            get { return _title; }
            set { SetProperty(ref _title, value); }
        }

        public bool Busy
        {
            get { return mycontroller.Busy; }
        }

        public MainWindowViewModel()
        {
            RunCommand = new DelegateCommand(Execute);
            mycontroller = new Controller();

        }

        private void Execute()
        {
            mycontroller.DoWork1();
        }
    }
</code>```

View:

```<code><Window x:Class="PropertytestPrism.Views.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:prism="http://prismlibrary.com/"
        prism:ViewModelLocator.AutoWireViewModel="True"
        Title="{Binding Title}" Height="350" Width="525">
    <StackPanel>
        <Button Command="{Binding RunCommand}" Content="Run"></Button>
        <TextBlock Text="{Binding Busy}"></TextBlock>

    </StackPanel>
</Window>
</code>```

Update 2

Failure: Missing INotifypropertychanged for the class Controller

The View is still not updated and the reason for this is my Delegatecommandmethod, which executes mycontroller.DoWork1();

Question:

Why the View is not updated? If I execute the method inside the DelegateCommandmethod?

答:
You should implement INotifyPropertyChanged by your Controller class. Property is changed inside Controller class and this changing should be notified:

```<code>public class Controller : INotifyPropertyChanged
{
    private bool _busy;

    public bool Busy
    {
        get
        {
            return  _busy;
        }
        private set
        {
            SetField(ref _busy, value, "Busy"); }
        }
    }

    public async void GetValue()
    {
        Busy = true;
        await Task.Delay(5000);
        Busy = false;
    }

    public event PropertyChangedEventHandler PropertyChanged;

    protected virtual void OnPropertyChanged(string propertyName)
    {
        PropertyChangedEventHandler handler = PropertyChanged;

        if (handler != null)
        {
           handler(this, new PropertyChangedEventArgs(propertyName));
        }
    }

    protected bool SetField<T>(ref T field, T value, string propertyName)
    {
        if (EqualityComparer<T>.Default.Equals(field, value))
        {
            return false;
        }

        field = value;
        OnPropertyChanged(propertyName);

        return true;
    }
}
</code>```

Body:
Problem:

My Viewmodel creates a instance of a controller mycontroller and the property Busy shall be passed to the View and updated in the View based on the controller state, but my View doesn't get updated. The other property Busy2 is updated based on the current state. Bindablebase implements the I

Question:

Why the property Busy in the ViewModel is not updated? The mycontroller.Busy property is updating, but not the view.

Framework & Tools:

PRISM 6.3.0

Fody.Propertychanged

View:

<TextBlock Text="{Binding Path=Busy}"></TextBlock>
<TextBlock Text="{Binding Path=Busy2}"></TextBlock>

ViewModel:

public class Controller
    {
        public bool Busy { get; private set; }

        public async void GetValue()
        {
            Busy = true;
            await Task.Delay(5000);
            Busy = false;
        }
    }

    public class MyViewModel : BindableBase
    {
        private readonly Controller _mycontroller;
        public DelegateCommand<string> RunCommand { get; private set; }

        // This property is not updated in the view
        public bool Busy
        {
            get { return _mycontroller.Busy; }
        }

        // Works as aspected
        public bool Busy2 { get; set; }

        public MyViewModel()
        {
            _mycontroller = new Controller();
            RunCommand = new DelegateCommand<string>(Run, Canrun).ObservesProperty((() => _mycontroller.Busy));
        }

        private bool Canrun(string arg)
        {
            return _mycontroller.Busy != true;
        }

        private void Run(string obj)
        {

            Busy2 = true;
            _mycontroller.GetValue();

        }
    }

Update:

I added the Bindablebase from Prism, because is implement the INotifyPropertyChanged, but the view is still not updated.
I refactored the code and I set a breakpoint to  set { SetProperty(ref _busy, value); } and the breakpoint is never reached.

I removed the Propertychanged.Fody nuget package too.

ViewModel:

   public class Controller : BindableBase
    {
        private bool _busy;
        public bool Busy
        {
            get { return _busy; }
            set { SetProperty(ref _busy, value); }
        }

        public Controller()
        {

        }

        public void DoWork1()
        {
            for (var i = 0; i < 10; i++)
            {
                Thread.Sleep(1000);
                _busy = !_busy;
                Debug.WriteLine(_busy.ToString());
            }
        }

        public void DoWork2()
        {
            _busy = !_busy;

        }
    }

    public class MainWindowViewModel : BindableBase
    {
        private Controller mycontroller;
        private string _title = "Prism Unity Application";

        public DelegateCommand RunCommand { get; private set; }

        public string Title
        {
            get { return _title; }
            set { SetProperty(ref _title, value); }
        }

        public bool Busy
        {
            get { return mycontroller.Busy; }
        }

        public MainWindowViewModel()
        {
            RunCommand = new DelegateCommand(Execute);
            mycontroller = new Controller();

        }

        private void Execute()
        {
            mycontroller.DoWork1();
        }
    }

View:

<Window x:Class="PropertytestPrism.Views.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:prism="http://prismlibrary.com/"
        prism:ViewModelLocator.AutoWireViewModel="True"
        Title="{Binding Title}" Height="350" Width="525">
    <StackPanel>
        <Button Command="{Binding RunCommand}" Content="Run"></Button>
        <TextBlock Text="{Binding Busy}"></TextBlock>

    </StackPanel>
</Window>

Update 2

Failure: Missing INotifypropertychanged for the class Controller

The View is still not updated and the reason for this is my Delegatecommandmethod, which executes mycontroller.DoWork1();

Question:

Why the View is not updated? If I execute the method inside the DelegateCommandmethod?

Body:
You should implement INotifyPropertyChanged by your Controller class. Property is changed inside Controller class and this changing should be notified:

public class Controller : INotifyPropertyChanged
{
    private bool _busy;

    public bool Busy
    {
        get
        {
            return  _busy;
        }
        private set
        {
            SetField(ref _busy, value, "Busy"); }
        }
    }

    public async void GetValue()
    {
        Busy = true;
        await Task.Delay(5000);
        Busy = false;
    }

    public event PropertyChangedEventHandler PropertyChanged;

    protected virtual void OnPropertyChanged(string propertyName)
    {
        PropertyChangedEventHandler handler = PropertyChanged;

        if (handler != null)
        {
           handler(this, new PropertyChangedEventArgs(propertyName));
        }
    }

    protected bool SetField<T>(ref T field, T value, string propertyName)
    {
        if (EqualityComparer<T>.Default.Equals(field, value))
        {
            return false;
        }

        field = value;
        OnPropertyChanged(propertyName);

        return true;
    }
}


问:
Setting up the MKReverseGeocoderDelegate?
I am a little confused about setting up the MKReverseGeocoderDelegate, I noted from Apples example that they are assigning the MKReverseGeocoder to a property iVar, in the end I decided to alloc the MKReverseGeocoder when a position is found and release the MKReverseGeocoders as they either report back success or failure, does this seem right?</p>

```<code>// ------------------------------------------------------------------- **
// DELEGATE: CLLocationManager
// ------------------------------------------------------------------- **

- (void)locationManager:(CLLocationManager *)manager
    didUpdateToLocation:(CLLocation *)newLocation
           fromLocation:(CLLocation *)oldLocation {

    MKReverseGeocoder *myGeocoder = [[MKReverseGeocoder alloc] initWithCoordinate:[newLocation coordinate]];
    [myGeocoder setDelegate:self];
    [myGeocoder start];
}

// ------------------------------------------------------------------- **
// DELEGATE: MKReverseGeocoderDelegate
// ------------------------------------------------------------------- **

- (void)reverseGeocoder:(MKReverseGeocoder *)geocoder didFindPlacemark:(MKPlacemark *)placemark {
    NSLog(@"%@", [placemark locality]);
    [geocoder release];
}

- (void)reverseGeocoder:(MKReverseGeocoder *)geocoder didFailWithError:(NSError *)error {
    [geocoder release];
}
@end
</code>```

答:
You're fine in terms of memory management. If you run this through the leaks tool in Instruments, it'll probably complain about a possible leak in your locationManager:didUpdate method, but it's wrong about that, it just can't see where you're releasing the object.

I would do a couple things to decrease the impact on the geocoder, though. I'd look and see that the location you just didUpdate to has an accuracy that's worth talking about. When Core Location first comes to life, you're likely to get some garbage hits before the hardware's really up and receiving. And then the accuracy will narrow in on the real location (the Google Maps app shows pretty nicely what is happening there, the blue circle zeroing in on your real location). There's probably no point in geocoding until you've got an accuracy within 100 meters or so.

EDIT: Try this

```<code>- (void)locationManager:(CLLocationManager *)manager
    didUpdateToLocation:(CLLocation *)newLocation
           fromLocation:(CLLocation *)oldLocation {

  if((newLocation.coordinate.latitude != oldLocation.coordinate.latitude) &&
     (newLocation.coordinate.longitude != oldLocation.coordinate.longitude) &&
     ([newLocation horizontalAccuracy] < 100 && [newLocation horizontalAccuracy] > 0))
    {

        MKReverseGeocoder *myGeocoder = [[MKReverseGeocoder alloc] initWithCoordinate:[newLocation coordinate]];
        [myGeocoder setDelegate:self];
        [myGeocoder start];
    }
}
</code>```

That should ignore updates that are the same as the last update (which might be fairly frequent) and those that have invalid accuracy (you'll get negative numbers there occasionally, when the location hardware is first fired up) or are over 100 meters of horizontal accuracy.

Also, if you just want to do this once, go ahead and have your CLLocationManager stop updating once you get a valid and sufficiently accurate position.

Body:
I am a little confused about setting up the MKReverseGeocoderDelegate, I noted from Apples example that they are assigning the MKReverseGeocoder to a property iVar, in the end I decided to alloc the MKReverseGeocoder when a position is found and release the MKReverseGeocoders as they either report back success or failure, does this seem right?

// ------------------------------------------------------------------- **
// DELEGATE: CLLocationManager
// ------------------------------------------------------------------- **

- (void)locationManager:(CLLocationManager *)manager
    didUpdateToLocation:(CLLocation *)newLocation
           fromLocation:(CLLocation *)oldLocation {

    MKReverseGeocoder *myGeocoder = [[MKReverseGeocoder alloc] initWithCoordinate:[newLocation coordinate]];
    [myGeocoder setDelegate:self];
    [myGeocoder start];
}

// ------------------------------------------------------------------- **
// DELEGATE: MKReverseGeocoderDelegate
// ------------------------------------------------------------------- **

- (void)reverseGeocoder:(MKReverseGeocoder *)geocoder didFindPlacemark:(MKPlacemark *)placemark {
    NSLog(@"%@", [placemark locality]);
    [geocoder release];
}

- (void)reverseGeocoder:(MKReverseGeocoder *)geocoder didFailWithError:(NSError *)error {
    [geocoder release];
}
@end

Body:
You're fine in terms of memory management. If you run this through the leaks tool in Instruments, it'll probably complain about a possible leak in your locationManager:didUpdate method, but it's wrong about that, it just can't see where you're releasing the object.

I would do a couple things to decrease the impact on the geocoder, though. I'd look and see that the location you just didUpdate to has an accuracy that's worth talking about. When Core Location first comes to life, you're likely to get some garbage hits before the hardware's really up and receiving. And then the accuracy will narrow in on the real location (the Google Maps app shows pretty nicely what is happening there, the blue circle zeroing in on your real location). There's probably no point in geocoding until you've got an accuracy within 100 meters or so.

EDIT: Try this

- (void)locationManager:(CLLocationManager *)manager
    didUpdateToLocation:(CLLocation *)newLocation
           fromLocation:(CLLocation *)oldLocation {

  if((newLocation.coordinate.latitude != oldLocation.coordinate.latitude) &&
     (newLocation.coordinate.longitude != oldLocation.coordinate.longitude) &&
     ([newLocation horizontalAccuracy] < 100 && [newLocation horizontalAccuracy] > 0))
    {

        MKReverseGeocoder *myGeocoder = [[MKReverseGeocoder alloc] initWithCoordinate:[newLocation coordinate]];
        [myGeocoder setDelegate:self];
        [myGeocoder start];
    }
}

That should ignore updates that are the same as the last update (which might be fairly frequent) and those that have invalid accuracy (you'll get negative numbers there occasionally, when the location hardware is first fired up) or are over 100 meters of horizontal accuracy.

Also, if you just want to do this once, go ahead and have your CLLocationManager stop updating once you get a valid and sufficiently accurate position.


问:
How to connect to weather API using requests?
I am trying to learn Requests and practicing by connecting to the weather API.  But for some reason I can't get it to work?  It is clear the weather API is wanting the param in a certain way that I cannot seem to figure out how it translates to Requests.

Here is my code:

```<code>r = requests.get('http://api.openweathermap.org/data/2.5/weather', q={'Anderson'})
</code>```

Here is the link to the API page:
https://openweathermap.org/current

I see the weather pages wants the param in terms of q = city, but the error I get is:

```<code>TypeError: request() got an unexpected keyword argument 'q'
</code>```

Also here the the Requests page that I am referring to: http://docs.python-requests.org/en/master/

Thanks for the help!

答:
You need an appid for openweather, which for individual use is free (https://openweathermap.org/appid#get)

```<code>>>> import requests
>>> r = requests.get('http://samples.openweathermap.org/data/2.5/weather?q=London,uk&appid=b1b15e88fa797225412429c1c50c122a1')
>>> loc_weather = r.content.strip()
>>> loc_weather
'{"coord":{"lon":-0.13,"lat":51.51},"weather":[{"id":300,"main":"Drizzle","description":"light intensity drizzle","icon":"09d"}],"base":"stations","main":{"temp":280.32,"pressure":1012,"humidity":81,"temp_min":279.15,"temp_max":281.15},"visibility":10000,"wind":{"speed":4.1,"deg":80},"clouds":{"all":90},"dt":1485789600,"sys":{"type":1,"id":5091,"message":0.0103,"country":"GB","sunrise":1485762037,"sunset":1485794875},"id":2643743,"name":"London","cod":200}'
</code>```

Body:
I am trying to learn Requests and practicing by connecting to the weather API.  But for some reason I can't get it to work?  It is clear the weather API is wanting the param in a certain way that I cannot seem to figure out how it translates to Requests.

Here is my code:

r = requests.get('http://api.openweathermap.org/data/2.5/weather', q={'Anderson'})

Here is the link to the API page:
https://openweathermap.org/current

I see the weather pages wants the param in terms of q = city, but the error I get is:

TypeError: request() got an unexpected keyword argument 'q'

Also here the the Requests page that I am referring to: http://docs.python-requests.org/en/master/

Thanks for the help!

Body:
You need an appid for openweather, which for individual use is free (https://openweathermap.org/appid#get)

>>> import requests
>>> r = requests.get('http://samples.openweathermap.org/data/2.5/weather?q=London,uk&appid=b1b15e88fa797225412429c1c50c122a1')
>>> loc_weather = r.content.strip()
>>> loc_weather
'{"coord":{"lon":-0.13,"lat":51.51},"weather":[{"id":300,"main":"Drizzle","description":"light intensity drizzle","icon":"09d"}],"base":"stations","main":{"temp":280.32,"pressure":1012,"humidity":81,"temp_min":279.15,"temp_max":281.15},"visibility":10000,"wind":{"speed":4.1,"deg":80},"clouds":{"all":90},"dt":1485789600,"sys":{"type":1,"id":5091,"message":0.0103,"country":"GB","sunrise":1485762037,"sunset":1485794875},"id":2643743,"name":"London","cod":200}'


问:
Check which one of two buttons has been pressed and pass a value to sharedpreferences
I have an activity with two buttons. Both buttons bring you to the next activity and at the same time a value is being given to sharedpreferences. I want to access this value in my very last activity.

How do I check which of the two buttons has been pressed?

What is the problem in my code? I always get the same value in the end. So it seems like I always press the same button, which I don't.

Here the first activity where the two buttons are in:

public void imagebutton (){

        ImageButton btn = (ImageButton) findViewById(R.id.imageButton3);
        btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(Akt1.this);
                SharedPreferences.Editor editor = preferences.edit();
                editor.putString("name2", "Geschlecht");

                editor.clear();
                editor.apply();
                startActivity(new Intent(Akt1.this, Akt2.class));
            }
        });
    }

               //buttonclick mit datapass gemixt

    private void imagebutton1 () {
        ImageButton btn = (ImageButton) findViewById(R.id.imageButton4);
        btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                SharedPreferences preferences = getSharedPreferences("myprefs", MODE_PRIVATE);
                SharedPreferences.Editor editor = preferences.edit();
                editor.putString("name","Geschlecht");
                editor.commit();

                Intent intent = new Intent (Akt1.this,Akt2.class);
                startActivity(intent);```
</div>
</div>
</p>

<p>And here the code from the last activity where I want to access the value that has been passed to sharedpreferences from the buttonclick:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>public class Akt6 extends AppCompatActivity {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //Hiermit Layout mit Activity verbinden
        setContentView(R.layout.activity_akt6);

        SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
        String name = preferences.getString("Name",null);
        name ="Männlich";

        SharedPreferences preferences2 = PreferenceManager.getDefaultSharedPreferences(this);
        String name2 = preferences.getString("Name", "default");
        name2 ="Weiblich";
        //zeige Wert on screen

        TextView textView19 = (TextView) findViewById(R.id.textView19);
        textView19.setText(name);</code>```

答:
You are getting the same value because of this:

```<code>String name = preferences.getString("Name", null);
...
String name2 = preferences.getString("Name", "default");
</code>```

You're using the same key "Name". You stored the values with the keys "name" and "name2".
So if you want to get those values you need to write something like this:

```<code>String name = preferences.getString("name", null);
...
String name2 = preferences.getString("name2", "default");
</code>```

Also you are storing always the same value "Geschlecht":

```<code>editor.putString("name2", "Geschlecht");
editor.putString("name","Geschlecht");
</code>```

Body:
I have an activity with two buttons. Both buttons bring you to the next activity and at the same time a value is being given to sharedpreferences. I want to access this value in my very last activity.

How do I check which of the two buttons has been pressed?

What is the problem in my code? I always get the same value in the end. So it seems like I always press the same button, which I don't.

Here the first activity where the two buttons are in:

public void imagebutton (){

        ImageButton btn = (ImageButton) findViewById(R.id.imageButton3);
        btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(Akt1.this);
                SharedPreferences.Editor editor = preferences.edit();
                editor.putString("name2", "Geschlecht");

                editor.clear();
                editor.apply();
                startActivity(new Intent(Akt1.this, Akt2.class));
            }
        });
    }

               //buttonclick mit datapass gemixt

    private void imagebutton1 () {
        ImageButton btn = (ImageButton) findViewById(R.id.imageButton4);
        btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                SharedPreferences preferences = getSharedPreferences("myprefs", MODE_PRIVATE);
                SharedPreferences.Editor editor = preferences.edit();
                editor.putString("name","Geschlecht");
                editor.commit();

                Intent intent = new Intent (Akt1.this,Akt2.class);
                startActivity(intent);

And here the code from the last activity where I want to access the value that has been passed to sharedpreferences from the buttonclick:

public class Akt6 extends AppCompatActivity {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //Hiermit Layout mit Activity verbinden
        setContentView(R.layout.activity_akt6);

        SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
        String name = preferences.getString("Name",null);
        name ="Männlich";

        SharedPreferences preferences2 = PreferenceManager.getDefaultSharedPreferences(this);
        String name2 = preferences.getString("Name", "default");
        name2 ="Weiblich";
        //zeige Wert on screen

        TextView textView19 = (TextView) findViewById(R.id.textView19);
        textView19.setText(name);

Body:
You are getting the same value because of this:

String name = preferences.getString("Name", null);
...
String name2 = preferences.getString("Name", "default");

You're using the same key "Name". You stored the values with the keys "name" and "name2".
So if you want to get those values you need to write something like this:

String name = preferences.getString("name", null);
...
String name2 = preferences.getString("name2", "default");

Also you are storing always the same value "Geschlecht":

editor.putString("name2", "Geschlecht");
editor.putString("name","Geschlecht");


问:
Grouping data in specific way
I am building report which shows the parts of one work order in different departments.
Consider the table below

```<code>work_order  part  dept_code  datein
aaaa        11    XXX        20/01/2017
aaaa        12    BBB        22/01/2017
bbbb        12    XXX        20/01/2017
bbbb        15    XXX        22/01/2017
cccc        13    XXX        20/01/2017
cccc        17    XYX        20/01/2017
</code>```

Now i want to group this data in such way that only the work order with different dept_code should show up.
RESULT

```<code>work_order  part  dept_code  datein
aaaa        11    XXX        20/01/2017
aaaa        12    BBB        22/01/2017
cccc        13    XXX        20/01/2017
cccc        17    XYX        20/01/2017
</code>```

答:
Use a subquery that identifies those work_order items which's department-count is greater than 1:

```<code>select * from work
where work_order in
  (select work_order
   from work w2
   group by w2.work_order
   having count(w2.dept_code) > 1
  )
</code>```

Title: Grouping data in specific way

Body:
I am building report which shows the parts of one work order in different departments.
Consider the table below

work_order  part  dept_code  datein
aaaa        11    XXX        20/01/2017
aaaa        12    BBB        22/01/2017
bbbb        12    XXX        20/01/2017
bbbb        15    XXX        22/01/2017
cccc        13    XXX        20/01/2017
cccc        17    XYX        20/01/2017

Now i want to group this data in such way that only the work order with different dept_code should show up.
RESULT

work_order  part  dept_code  datein
aaaa        11    XXX        20/01/2017
aaaa        12    BBB        22/01/2017
cccc        13    XXX        20/01/2017
cccc        17    XYX        20/01/2017

Body:
Use a subquery that identifies those work_order items which's department-count is greater than 1:

select * from work
where work_order in
  (select work_order
   from work w2
   group by w2.work_order
   having count(w2.dept_code) > 1
  )


问:
Issues With the radgrid
I am getting few issues with RadGrid. One is I have GridClientSelectColumn in RadGrid. I am able to select all checkboxes using header checkbox but I am not able to select individual ones. Another is when I click the row I am changing the background color of a row but it's not coming fully. Only half of the row is changing the color (see image 1). Another one is I have RadMenu in CommandItem template. Which is not displaying properly (see image 2). Here is my code.....

```<code><telerik:RadGrid ID="gvPjtMnt" runat="server" AutoGenerateColumns="false" Height="600px"
BorderWidth="2px" BorderStyle="Solid" BackColor="White" AllowPaging="True" PagerStyle-AlwaysVisible="true"
PageSize="20" AllowSorting="True" OnNeedDataSource="gvPjtMnt_OnNeedDataSource"
AllowFilteringByColumn="true" OnItemCommand="gvPjtMnt_ItemCommand" OnItemCreated="gvPjtMnt_ItemCreated"
OnItemDataBound="gvPjtMnt_ItemDataBound" OnPreRender="gvPjtMnt_PreRender" AllowMultiRowSelection="true"
ClientSettings-Selecting-AllowRowSelect="true">
    <HeaderStyle Height="20px" BackColor="#004000" Font-Size="8pt" Font-Bold="True" ForeColor="White"
        HorizontalAlign="Center" BorderColor="White" BorderWidth="1px" />
    <AlternatingItemStyle BackColor="#F5F5E9" HorizontalAlign="Center" BorderColor="White" />
    <ItemStyle HorizontalAlign="Center" />
    <MasterTableView GridLines="None" DataKeyNames="ProjectId" CommandItemDisplay="Top">
        <CommandItemTemplate>
            <table style="width: 100%">
                <tr align="right">
                    <td style="width: 75%">
                        <telerik:RadMenu ID="RadMenu1" runat="server" EnableRoundedCorners="true" EnableShadows="true"
                            EnableAjaxSkinRendering="true">
                            <Items>
                                <telerik:RadMenuItem Text="Text" CssClass>
                                    <Items>
                                        <telerik:RadMenuItem ImageUrl="Images/comment-icon.png" Value="1" NavigateUrl="javascript:validateChkUpdate()"
                                            Text="Add Notes">
                                        </telerik:RadMenuItem>
                                        <telerik:RadMenuItem ImageUrl="Images/OrdUpdate.gif" Value="2" NavigateUrl="javascript:validateChkUpdate()"
                                            Text="Bulk Updates">
                                        </telerik:RadMenuItem>
                                    </Items>
                                </telerik:RadMenuItem>
                            </Items>
                        </telerik:RadMenu>
                    </td>
                    <td align="right">
                        <asp:LinkButton ID="lnkshwFilter" Text="ShowFilter" Font-Underline="true" ForeColor="MidnightBlue"
                            runat="server" OnClientClick="return showFilterItem()" />
                        <asp:LinkButton ID="lnkhdFilter" Text="HideFilter" Font-Underline="true" ForeColor="MidnightBlue"
                            runat="server" OnClientClick="return hideFilterItem()" />
                    </td>
                    <td align="right">
                        <asp:LinkButton ID="lnkclrFilter" Text="ClearFilter" Font-Underline="true" ForeColor="MidnightBlue"
                            runat="server" OnClick="lnkclrFilter_Click"></asp:LinkButton>
                    </td>
                    <td align="right">
                        Total Records found: <asp:Label ID="lblTotRecCount" runat="server" Font-Bold="True"
                            Font-Size="10pt" ForeColor="Black" Text="0"></asp:Label>
                    </td>
                    <td align="right" valign="middle">
                        <asp:ImageButton ID="lnkExportAll" ImageUrl="~/images/Excel.png" ToolTip="Export All"
                            runat="server" OnClick="ExportAll_Click" />
                    </td>
                    <td align="right" valign="middle">
                        <asp:ImageButton ID="ExportToExcelButton" runat="server" ImageUrl="~/images/ExportToExcel.gif"
                            ToolTip="Export to Excel" OnClick="ExportExcel_Click" />
                    </td>
                </tr>
            </table>
        </CommandItemTemplate>
        <Columns>
            <telerik:GridClientSelectColumn UniqueName="CheckboxSelectColumn" HeaderStyle-Width="3%">
            </telerik:GridClientSelectColumn>
            <telerik:GridBoundColumn DataField="ProjectId" UniqueName="ProjectId" Visible="false">
            </telerik:GridBoundColumn>
            <telerik:GridBoundColumn HeaderText="LOB" DataField="LOB" UniqueName="LOB">
            </telerik:GridBoundColumn>
            <telerik:GridBoundColumn HeaderText="Division Name" DataField="Division" UniqueName="Division">
            </telerik:GridBoundColumn>
            <telerik:GridBoundColumn HeaderText="Region Name" DataField="MarketName" UniqueName="MarketName">
            </telerik:GridBoundColumn>
            <telerik:GridBoundColumn HeaderText="Project Name" DataField="ProjectName" UniqueName="ProjectName">
            </telerik:GridBoundColumn>
            <telerik:GridBoundColumn HeaderText="Project Manager Name" DataField="ProjectMgrName"
                UniqueName="ProjectMgrName">
            </telerik:GridBoundColumn>
            <telerik:GridBoundColumn HeaderText="Number Of Sites Received" DataField="NumSitesReceived"
                UniqueName="NumSitesReceived">
            </telerik:GridBoundColumn>
            <telerik:GridBoundColumn HeaderText="Accept Service Order Date" DataField="AcceptServiceOrderTaskCompleteDate"
                UniqueName="AcceptServiceOrderTaskCompleteDate" DataFormatString="{0:MM/dd/yyyy}">
            </telerik:GridBoundColumn>
            <telerik:GridBoundColumn HeaderText="PTD" DataField="PTD" UniqueName="PTD" DataFormatString="{0:MM/dd/yyyy}">
            </telerik:GridBoundColumn>
            <telerik:GridBoundColumn HeaderText="Health Reason" DataField="HealthReason" UniqueName="HealthReason">
            </telerik:GridBoundColumn>
            <telerik:GridBoundColumn HeaderText="Project Health" DataField="ProjectHealth" UniqueName="ProjectHealth">
            </telerik:GridBoundColumn>
            <telerik:GridBoundColumn HeaderText="Customer Signed Date" DataField="CustomerSignedDate"
                UniqueName="CustomerSignedDate" DataFormatString="{0:MM/dd/yyyy}">
            </telerik:GridBoundColumn>
            <telerik:GridBoundColumn HeaderText="OA Complete Date" DataField="OACompleteDate"
                UniqueName="OACompleteDate" DataFormatString="{0:MM/dd/yyyy}">
            </telerik:GridBoundColumn>
            <telerik:GridBoundColumn HeaderText="Customer Requested Due Date" DataField="CustomerRequestedDueDate"
                UniqueName="CustomerRequestedDueDate" DataFormatString="{0:MM/dd/yyyy}">
            </telerik:GridBoundColumn>
            <telerik:GridBoundColumn HeaderText="Last Note Added" DataField="LastNoteAdded" HeaderStyle-Width="10%"
                UniqueName="LastNoteAdded">
            </telerik:GridBoundColumn>
            <telerik:GridTemplateColumn UniqueName="EditRows" HeaderStyle-Width="2%" AllowFiltering="false">
                <ItemTemplate>
                    <asp:ImageButton runat="server" ID="EditPMTsk" CommandName="EditRow" ImageUrl="Images/edit-icon.png"
                        ImageAlign="Middle" ToolTip="Edit Task" />
                </ItemTemplate>
            </telerik:GridTemplateColumn>
        </Columns>
    </MasterTableView>
    <ClientSettings>
        <ClientEvents OnGridCreated="GridCreated" />
        <Scrolling AllowScroll="true" UseStaticHeaders="true" />
        <Resizing AllowColumnResize="true" EnableRealTimeResize="false" ResizeGridOnColumnResize="false"
            AllowRowResize="false" />
        <Selecting AllowRowSelect="true" />
    </ClientSettings>
</telerik:RadGrid>
</code>```

.cs:

```<code>protected void gvPjtMnt_ItemDataBound(object sender, GridItemEventArgs e)
{
    if (e.Item is GridDataItem)
    {
        GridDataItem dataItem = e.Item as GridDataItem;
        TableCell myCell = dataItem["ProjectHealth"];
        myCell.Font.Size = 10;
        myCell.Font.Bold = true;

        if (myCell.Text.Trim() == "GREEN")
        {
            myCell.BackColor = System.Drawing.Color.Green;
            myCell.ForeColor = System.Drawing.Color.White;
        }
        if (myCell.Text.Trim() == "RED")
        {
            myCell.BackColor = System.Drawing.Color.Red;
            myCell.ForeColor = System.Drawing.Color.White;
        }
        if (myCell.Text.Trim() == "YELLOW")
        {
            myCell.BackColor = System.Drawing.Color.Yellow;
            myCell.ForeColor = System.Drawing.Color.Black;
        }
        if (myCell.Text.Trim() == "COMPLETE")
        {
            myCell.BackColor = System.Drawing.Color.Blue;
            myCell.ForeColor = System.Drawing.Color.White;
        }
    }

}
</code>```

答:
Will try to be as brief as possible:

How to style telerik grid rows conditionally - doc

The checkbox-select column should work both for select all and select single - check if javascript errors on the site prevent that

I see that you have empty CssClass attribute for the root menu item - can this spoil its rendering? Also check if the image urls you set for the inner items are valid.

Title: Issues With the radgrid

Body:
I am getting few issues with RadGrid. One is I have GridClientSelectColumn in RadGrid. I am able to select all checkboxes using header checkbox but I am not able to select individual ones. Another is when I click the row I am changing the background color of a row but it's not coming fully. Only half of the row is changing the color (see image 1). Another one is I have RadMenu in CommandItem template. Which is not displaying properly (see image 2). Here is my code.....

<telerik:RadGrid ID="gvPjtMnt" runat="server" AutoGenerateColumns="false" Height="600px"
BorderWidth="2px" BorderStyle="Solid" BackColor="White" AllowPaging="True" PagerStyle-AlwaysVisible="true"
PageSize="20" AllowSorting="True" OnNeedDataSource="gvPjtMnt_OnNeedDataSource"
AllowFilteringByColumn="true" OnItemCommand="gvPjtMnt_ItemCommand" OnItemCreated="gvPjtMnt_ItemCreated"
OnItemDataBound="gvPjtMnt_ItemDataBound" OnPreRender="gvPjtMnt_PreRender" AllowMultiRowSelection="true"
ClientSettings-Selecting-AllowRowSelect="true">
    <HeaderStyle Height="20px" BackColor="#004000" Font-Size="8pt" Font-Bold="True" ForeColor="White"
        HorizontalAlign="Center" BorderColor="White" BorderWidth="1px" />
    <AlternatingItemStyle BackColor="#F5F5E9" HorizontalAlign="Center" BorderColor="White" />
    <ItemStyle HorizontalAlign="Center" />
    <MasterTableView GridLines="None" DataKeyNames="ProjectId" CommandItemDisplay="Top">
        <CommandItemTemplate>

                        <telerik:RadMenu ID="RadMenu1" runat="server" EnableRoundedCorners="true" EnableShadows="true"
                            EnableAjaxSkinRendering="true">
                            <Items>
                                <telerik:RadMenuItem Text="Text" CssClass>
                                    <Items>
                                        <telerik:RadMenuItem ImageUrl="Images/comment-icon.png" Value="1" NavigateUrl="javascript:validateChkUpdate()"
                                            Text="Add Notes">
                                        </telerik:RadMenuItem>
                                        <telerik:RadMenuItem ImageUrl="Images/OrdUpdate.gif" Value="2" NavigateUrl="javascript:validateChkUpdate()"
                                            Text="Bulk Updates">
                                        </telerik:RadMenuItem>
                                    </Items>
                                </telerik:RadMenuItem>
                            </Items>
                        </telerik:RadMenu>

                        <asp:LinkButton ID="lnkshwFilter" Text="ShowFilter" Font-Underline="true" ForeColor="MidnightBlue"
                            runat="server" OnClientClick="return showFilterItem()" />
                        <asp:LinkButton ID="lnkhdFilter" Text="HideFilter" Font-Underline="true" ForeColor="MidnightBlue"
                            runat="server" OnClientClick="return hideFilterItem()" />

                        <asp:LinkButton ID="lnkclrFilter" Text="ClearFilter" Font-Underline="true" ForeColor="MidnightBlue"
                            runat="server" OnClick="lnkclrFilter_Click"></asp:LinkButton>

                        Total Records found: <asp:Label ID="lblTotRecCount" runat="server" Font-Bold="True"
                            Font-Size="10pt" ForeColor="Black" Text="0"></asp:Label>

                        <asp:ImageButton ID="lnkExportAll" ImageUrl="~/images/Excel.png" ToolTip="Export All"
                            runat="server" OnClick="ExportAll_Click" />

                        <asp:ImageButton ID="ExportToExcelButton" runat="server" ImageUrl="~/images/ExportToExcel.gif"
                            ToolTip="Export to Excel" OnClick="ExportExcel_Click" />

        </CommandItemTemplate>
        <Columns>
            <telerik:GridClientSelectColumn UniqueName="CheckboxSelectColumn" HeaderStyle-Width="3%">
            </telerik:GridClientSelectColumn>
            <telerik:GridBoundColumn DataField="ProjectId" UniqueName="ProjectId" Visible="false">
            </telerik:GridBoundColumn>
            <telerik:GridBoundColumn HeaderText="LOB" DataField="LOB" UniqueName="LOB">
            </telerik:GridBoundColumn>
            <telerik:GridBoundColumn HeaderText="Division Name" DataField="Division" UniqueName="Division">
            </telerik:GridBoundColumn>
            <telerik:GridBoundColumn HeaderText="Region Name" DataField="MarketName" UniqueName="MarketName">
            </telerik:GridBoundColumn>
            <telerik:GridBoundColumn HeaderText="Project Name" DataField="ProjectName" UniqueName="ProjectName">
            </telerik:GridBoundColumn>
            <telerik:GridBoundColumn HeaderText="Project Manager Name" DataField="ProjectMgrName"
                UniqueName="ProjectMgrName">
            </telerik:GridBoundColumn>
            <telerik:GridBoundColumn HeaderText="Number Of Sites Received" DataField="NumSitesReceived"
                UniqueName="NumSitesReceived">
            </telerik:GridBoundColumn>
            <telerik:GridBoundColumn HeaderText="Accept Service Order Date" DataField="AcceptServiceOrderTaskCompleteDate"
                UniqueName="AcceptServiceOrderTaskCompleteDate" DataFormatString="{0:MM/dd/yyyy}">
            </telerik:GridBoundColumn>
            <telerik:GridBoundColumn HeaderText="PTD" DataField="PTD" UniqueName="PTD" DataFormatString="{0:MM/dd/yyyy}">
            </telerik:GridBoundColumn>
            <telerik:GridBoundColumn HeaderText="Health Reason" DataField="HealthReason" UniqueName="HealthReason">
            </telerik:GridBoundColumn>
            <telerik:GridBoundColumn HeaderText="Project Health" DataField="ProjectHealth" UniqueName="ProjectHealth">
            </telerik:GridBoundColumn>
            <telerik:GridBoundColumn HeaderText="Customer Signed Date" DataField="CustomerSignedDate"
                UniqueName="CustomerSignedDate" DataFormatString="{0:MM/dd/yyyy}">
            </telerik:GridBoundColumn>
            <telerik:GridBoundColumn HeaderText="OA Complete Date" DataField="OACompleteDate"
                UniqueName="OACompleteDate" DataFormatString="{0:MM/dd/yyyy}">
            </telerik:GridBoundColumn>
            <telerik:GridBoundColumn HeaderText="Customer Requested Due Date" DataField="CustomerRequestedDueDate"
                UniqueName="CustomerRequestedDueDate" DataFormatString="{0:MM/dd/yyyy}">
            </telerik:GridBoundColumn>
            <telerik:GridBoundColumn HeaderText="Last Note Added" DataField="LastNoteAdded" HeaderStyle-Width="10%"
                UniqueName="LastNoteAdded">
            </telerik:GridBoundColumn>
            <telerik:GridTemplateColumn UniqueName="EditRows" HeaderStyle-Width="2%" AllowFiltering="false">
                <ItemTemplate>
                    <asp:ImageButton runat="server" ID="EditPMTsk" CommandName="EditRow" ImageUrl="Images/edit-icon.png"
                        ImageAlign="Middle" ToolTip="Edit Task" />
                </ItemTemplate>
            </telerik:GridTemplateColumn>
        </Columns>
    </MasterTableView>
    <ClientSettings>
        <ClientEvents OnGridCreated="GridCreated" />
        <Scrolling AllowScroll="true" UseStaticHeaders="true" />
        <Resizing AllowColumnResize="true" EnableRealTimeResize="false" ResizeGridOnColumnResize="false"
            AllowRowResize="false" />
        <Selecting AllowRowSelect="true" />
    </ClientSettings>
</telerik:RadGrid>

.cs:

protected void gvPjtMnt_ItemDataBound(object sender, GridItemEventArgs e)
{
    if (e.Item is GridDataItem)
    {
        GridDataItem dataItem = e.Item as GridDataItem;
        TableCell myCell = dataItem["ProjectHealth"];
        myCell.Font.Size = 10;
        myCell.Font.Bold = true;

        if (myCell.Text.Trim() == "GREEN")
        {
            myCell.BackColor = System.Drawing.Color.Green;
            myCell.ForeColor = System.Drawing.Color.White;
        }
        if (myCell.Text.Trim() == "RED")
        {
            myCell.BackColor = System.Drawing.Color.Red;
            myCell.ForeColor = System.Drawing.Color.White;
        }
        if (myCell.Text.Trim() == "YELLOW")
        {
            myCell.BackColor = System.Drawing.Color.Yellow;
            myCell.ForeColor = System.Drawing.Color.Black;
        }
        if (myCell.Text.Trim() == "COMPLETE")
        {
            myCell.BackColor = System.Drawing.Color.Blue;
            myCell.ForeColor = System.Drawing.Color.White;
        }
    }

}


问:
Oracle Grid Infrastructure 12c Release 2 installation ASM Disk Group Candidates are empty
I am installing Oracle Grid Infrastructure for a Standalone Server (Oracle Restart) per this article and cannot see any disks/candidate disks: http://prntscr.com/fgl12s

I have tried different mask: http://prntscr.com/fgl1bu

```<code>[root@Rhino ~]# oracleasm configure -i
Configuring the Oracle ASM library driver.

This will configure the on-boot properties of the Oracle ASM library
driver.  The following questions will determine whether the driver is
loaded on boot and what permissions it will have.  The current values
will be shown in brackets ('[]').  Hitting <ENTER> without typing an
answer will keep that current value.  Ctrl-C will abort.

Default user to own the driver interface [oracle]:
Default group to own the driver interface [dba]:
Scan for Oracle ASM disks on boot (y/n) [y]:
Writing Oracle ASM library driver configuration: done
</code>```

[root@Rhino ~]# oracleasm init doesn't produce any output

```<code>[root@Rhino ~]# oracleasm scandisks
Reloading disk partitions: done
Cleaning any stale ASM disks...
Scanning system for ASM disks...

[root@Rhino ~]# oracleasm status
Checking if ASM is loaded: yes
Checking if /dev/oracleasm is mounted: yes

[root@Rhino ~]# oracleasm listdisks
DATA1
DATA2
DATA3
DATA4

[root@Rhino ~]#  /usr/sbin/oracleasm querydisk DATA1
Disk "DATA1" is a valid ASM disk
</code>```

答: It appeared discovery paths should be: /dev/oracleasm/disks/*

Body:
I am installing Oracle Grid Infrastructure for a Standalone Server (Oracle Restart) per this article and cannot see any disks/candidate disks: http://prntscr.com/fgl12s

I have tried different mask: http://prntscr.com/fgl1bu

[root@Rhino ~]# oracleasm configure -i
Configuring the Oracle ASM library driver.

This will configure the on-boot properties of the Oracle ASM library
driver.  The following questions will determine whether the driver is
loaded on boot and what permissions it will have.  The current values
will be shown in brackets ('[]').  Hitting <ENTER> without typing an
answer will keep that current value.  Ctrl-C will abort.

Default user to own the driver interface [oracle]:
Default group to own the driver interface [dba]:
Scan for Oracle ASM disks on boot (y/n) [y]:
Writing Oracle ASM library driver configuration: done

[root@Rhino ~]# oracleasm init doesn't produce any output

[root@Rhino ~]# oracleasm scandisks
Reloading disk partitions: done
Cleaning any stale ASM disks...
Scanning system for ASM disks...

[root@Rhino ~]# oracleasm status
Checking if ASM is loaded: yes
Checking if /dev/oracleasm is mounted: yes

[root@Rhino ~]# oracleasm listdisks
DATA1
DATA2
DATA3
DATA4

[root@Rhino ~]#  /usr/sbin/oracleasm querydisk DATA1
Disk "DATA1" is a valid ASM disk


问:
openpyxl: ValueError: dtype: int64 to Excel
I am combining two .csv file and writing a new .xlsx file.

The code goes like this:

```<code>ODEMPTY = pandas.read_csv('OD_Empty_unduplicated.csv')
ODNEW = pandas.read_csv('OD_Out.csv')

ODNEW = ODNEW.append(ODEMPTY)

wb = openpyxl.load_workbook('cm2011.xlsx')
sheet = wb.get_sheet_by_name('Sheet1')

for i in range(len(ODNEW)):
   sheet['A'+ str(i+1)].value = ODNEW['comm'][i] # start writing on A1 not A0
   sheet['B'+ str(i+1)].value = ODNEW['ONode'][i]
   sheet['C'+ str(i+1)].value = ODNEW['DNode'][i]
   sheet['D'+ str(i+1)].value = ODNEW['quantity'][i]
   sheet['E'+ str(i+1)].value = ODNEW['startRR'][i]
</code>```

Error: ValueError: dtype: int64 to Excel

答:
You're currently trying to write multiple pd.Series to cells. To get just one value you'd have to use .iloc, e.g.:

```<code>for i in range(len(ODNEW)):
   sheet['A'+ str(i+1)].value = ODNEW['comm'].iloc[i] # start writing on A1 not A0
   sheet['B'+ str(i+1)].value = ODNEW['ONode'].iloc[i]
   sheet['C'+ str(i+1)].value = ODNEW['DNode'].iloc[i]
   sheet['D'+ str(i+1)].value = ODNEW['quantity'].iloc[i]
   sheet['E'+ str(i+1)].value = ODNEW['startRR'].iloc[i]
</code>```

But you can iterate over the table directly:

```<code>for i,j in ODNEW.iterrows():
   sheet['A'+ str(i+1)].value = j['ONode']
   sheet['C'+ str(i+1)].value = j['DNode']
   sheet['D'+ str(i+1)].value = j['quantity']
   sheet['E'+ str(i+1)].value = j['startRR']
</code>```

Otherwise look at the utility function provided here: http://openpyxl.readthedocs.io/en/default/pandas.html

Body:
I am combining two .csv file and writing a new .xlsx file.

The code goes like this:

ODEMPTY = pandas.read_csv('OD_Empty_unduplicated.csv')
ODNEW = pandas.read_csv('OD_Out.csv')

ODNEW = ODNEW.append(ODEMPTY)

wb = openpyxl.load_workbook('cm2011.xlsx')
sheet = wb.get_sheet_by_name('Sheet1')

for i in range(len(ODNEW)):
   sheet['A'+ str(i+1)].value = ODNEW['comm'][i] # start writing on A1 not A0
   sheet['B'+ str(i+1)].value = ODNEW['ONode'][i]
   sheet['C'+ str(i+1)].value = ODNEW['DNode'][i]
   sheet['D'+ str(i+1)].value = ODNEW['quantity'][i]
   sheet['E'+ str(i+1)].value = ODNEW['startRR'][i]

Error: ValueError: dtype: int64 to Excel

Body:
You're currently trying to write multiple pd.Series to cells. To get just one value you'd have to use .iloc, e.g.:

for i in range(len(ODNEW)):
   sheet['A'+ str(i+1)].value = ODNEW['comm'].iloc[i] # start writing on A1 not A0
   sheet['B'+ str(i+1)].value = ODNEW['ONode'].iloc[i]
   sheet['C'+ str(i+1)].value = ODNEW['DNode'].iloc[i]
   sheet['D'+ str(i+1)].value = ODNEW['quantity'].iloc[i]
   sheet['E'+ str(i+1)].value = ODNEW['startRR'].iloc[i]

But you can iterate over the table directly:

for i,j in ODNEW.iterrows():
   sheet['A'+ str(i+1)].value = j['ONode']
   sheet['C'+ str(i+1)].value = j['DNode']
   sheet['D'+ str(i+1)].value = j['quantity']
   sheet['E'+ str(i+1)].value = j['startRR']

Otherwise look at the utility function provided here: http://openpyxl.readthedocs.io/en/default/pandas.html


答:
Something like this</p>

```<code>SELECT work_order, part, dept_code, datein
FROM [Table]
WHERE work_order in
(
    SELECT work_order
    FROM [Table]
    GROUP BY work_order
    HAVING COUNT(DISTINCT dept_code) > 1
)
</code>```

Title: Grouping data in specific way

Body:
Something like this

SELECT work_order, part, dept_code, datein
FROM [Table]
WHERE work_order in
(
    SELECT work_order
    FROM [Table]
    GROUP BY work_order
    HAVING COUNT(DISTINCT dept_code) > 1
)


问:
Casting a float for int and int to float
Having a little difficulty with pointers. I have to store a float in an array of unsigned ints and be able to pull it out.

I know there is a special way to cast this so I don't reorder the bits, I think this is the correct way to store it when I want to put it into the array:

```<code>float f = 5.0;
int newF = (int *) f;
arrayOfInts[0] = *newF
</code>```

Which seems to successfully store the value in the array.
However, at some point I have to pull the value back out of the array of ints, this is where my confusion comes in (assuming I inputed into the array correctly)

```<code>float * f = (float *) arrayOfInts[0]
int result = *f;
</code>```

however, that gives me the warning: 'cast to pointer from integer of different size'

I can't really think of how to solve that without some sort of long cast.. which doesn't seem right..

I don't want to lose the value or damage the bits.. obviously It will lose decimal point precision.. but I know theirs some way to safety convert back and forth

答:
To convert a float to an int

```<code>float fval = 123.4f;
int ival = *(int*)&fval;
</code>```

To convert back

```<code>int ival = /* from float */
float fval = *(float*) &ival;
</code>```

it won't work if float and int are different sizes, but presumably you know that already. The unsigned char union method outlined in other answer for chux is more robust, but over-complicated for what you probably want to do.

Body:
Having a little difficulty with pointers. I have to store a float in an array of unsigned ints and be able to pull it out.

I know there is a special way to cast this so I don't reorder the bits, I think this is the correct way to store it when I want to put it into the array:

float f = 5.0;
int newF = (int *) f;
arrayOfInts[0] = *newF

Which seems to successfully store the value in the array.
However, at some point I have to pull the value back out of the array of ints, this is where my confusion comes in (assuming I inputed into the array correctly)

float * f = (float *) arrayOfInts[0]
int result = *f;

however, that gives me the warning: 'cast to pointer from integer of different size'

I can't really think of how to solve that without some sort of long cast.. which doesn't seem right..

I don't want to lose the value or damage the bits.. obviously It will lose decimal point precision.. but I know theirs some way to safety convert back and forth

Body:
To convert a float to an int

float fval = 123.4f;
int ival = *(int*)&fval;

To convert back

int ival = /* from float */
float fval = *(float*) &ival;

it won't work if float and int are different sizes, but presumably you know that already. The unsigned char union method outlined in other answer for chux is more robust, but over-complicated for what you probably want to do.


问:
How do I protect phone number from bots
I want a phone number which display on public page will be protected. Example converts phone number characters to HTML entities and bots can't grab the number in plain text. Let me know the trick.</p>

答:
This is a...passing thought, though I'm not sure how practical it would be:

```<code><span class="protectedNumber" title="01234567890"></span>
</code>```

css:

```<code>span.protectedNumber:before {
    content: "Phone number: " attr(title);
}
</code>```

JS Fiddle demo.

Edited, in response to 'cross browser?' question in comments, to add a jQuery option to assist with those browsers that don't have the ability to deal with css-generated content:

```<code>$(document).ready(
    function(){
       $('.protectedNumber').each(
           function(){
               $(this).text('Phone number: ' + $(this).attr('title'));
           });
    });
</code>```

Title: How do I protect phone number from bots

Body:
This is a...passing thought, though I'm not sure how practical it would be:

<span class="protectedNumber" title="01234567890"></span>

css:

span.protectedNumber:before {
    content: "Phone number: " attr(title);
}

JS Fiddle demo.

Edited, in response to 'cross browser?' question in comments, to add a jQuery option to assist with those browsers that don't have the ability to deal with css-generated content:

$(document).ready(
    function(){
       $('.protectedNumber').each(
           function(){
               $(this).text('Phone number: ' + $(this).attr('title'));
           });
    });