问:
Adding UIImageView to UIScrollView in background Thread, wont show up until all are added
I have a scrollView where I add some UIButtons and UIActivityIndicators in the main thread.
Then I perform a [NSThread detachSelectorInBackground:@selector(getImages) toTarget:self withObject:nil];

getImages downloads some images and add them into UIImageViews and then adds the UIImageViews to the scrollView, but they wont show up until the method getImages is done.
Is there any way to get the scrollView to redraw or refresh or something like that?

AND
If I scroll the scrollView (with my fingers..) during the getImages method, the UIImageViews that has been added shows up.

```<code>- (void) getImages {
    NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
    int x=5;
    int y=0;
    NSData *imgData;
    UIImage *img;
    UIImageView *imgView;
    for (NSDictionary *tmp in thumbs) {

  imgData = [[NSData alloc] initWithContentsOfURL:[NSURL URLWithString:[Functions urlForFile:[tmp objectForKey:@"img"]]]];
  if ([imgData length] > 0) {
    img = [[UIImage alloc] initWithData:imgData];
    imgView = [[UIImageView alloc] initWithFrame:CGRectMake(x, y + (133-img.size.height)/2, 100, img.size.height)];

    imgView.image = img;
    [imgView setAlpha:0.0];
    [[self.scrollView viewWithTag:1500000*[[tmp objectForKey:@"id"] intValue]] setAlpha:1.0];
    [self.scrollView addSubview:imgView];

    [UIView beginAnimations:nil context:NULL];
    [UIView setAnimationBeginsFromCurrentState:YES];
    [UIView setAnimationDuration:2.0];
    [[self.scrollView viewWithTag:1500000*[[tmp objectForKey:@"id"] intValue]] setAlpha:0.0];
    [imgView setAlpha:1.0];
    [UIView commitAnimations];
    [[self.scrollView viewWithTag:1500000*[[tmp objectForKey:@"id"] intValue]] removeFromSuperview];

    [imgView release];
    [img release];
    [imgData release];

    x+=105;
    if (x > 300) {
      x=5;
      y+=138;
    }
  }
}
[pool release];
[appDelegate.loadingView setHidden:YES];
}
</code>```

答:
changing the UI in background is not thread-safe! Downloading in background but not displaying. To show an image one by one you can try to run it with performSelectorOnMainThread:@selector() withObject:nil waitUntilDone:YES
for example with self.scrollView addSubview:.

But again, UI should always use MainThread (e.g. animations)

Body:
I have a scrollView where I add some UIButtons and UIActivityIndicators in the main thread.
Then I perform a [NSThread detachSelectorInBackground:@selector(getImages) toTarget:self withObject:nil];

getImages downloads some images and add them into UIImageViews and then adds the UIImageViews to the scrollView, but they wont show up until the method getImages is done.
Is there any way to get the scrollView to redraw or refresh or something like that?

AND
If I scroll the scrollView (with my fingers..) during the getImages method, the UIImageViews that has been added shows up.

- (void) getImages {
    NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
    int x=5;
    int y=0;
    NSData *imgData;
    UIImage *img;
    UIImageView *imgView;
    for (NSDictionary *tmp in thumbs) {

  imgData = [[NSData alloc] initWithContentsOfURL:[NSURL URLWithString:[Functions urlForFile:[tmp objectForKey:@"img"]]]];
  if ([imgData length] > 0) {
    img = [[UIImage alloc] initWithData:imgData];
    imgView = [[UIImageView alloc] initWithFrame:CGRectMake(x, y + (133-img.size.height)/2, 100, img.size.height)];

    imgView.image = img;
    [imgView setAlpha:0.0];
    [[self.scrollView viewWithTag:1500000*[[tmp objectForKey:@"id"] intValue]] setAlpha:1.0];
    [self.scrollView addSubview:imgView];

    [UIView beginAnimations:nil context:NULL];
    [UIView setAnimationBeginsFromCurrentState:YES];
    [UIView setAnimationDuration:2.0];
    [[self.scrollView viewWithTag:1500000*[[tmp objectForKey:@"id"] intValue]] setAlpha:0.0];
    [imgView setAlpha:1.0];
    [UIView commitAnimations];
    [[self.scrollView viewWithTag:1500000*[[tmp objectForKey:@"id"] intValue]] removeFromSuperview];

    [imgView release];
    [img release];
    [imgData release];

    x+=105;
    if (x > 300) {
      x=5;
      y+=138;
    }
  }
}
[pool release];
[appDelegate.loadingView setHidden:YES];
}


来源: stackexchange

问:
splitting a drill file using regex
i have a file here is it's dump

```<code>T01
X064900Y049200
X065900
X066900
X067900
X068900
X069900
T02
X062900Y048200
Y049200
Y050200
Y053700
X063900
X064900
X065900
X046350
</code>```

I wan to split it's contents   by T*   "T* must be included" by using
Java regex
   here what i did i read file contents into string parts
then String [] tools = parts.split("T\\d+");

but it didn't work, what is the best regex to use .

答:
Here is your solution.I am assuming that you are expecting separate strings which starts with the letter 'T'.

```<code>package com.sujit;

import java.util.regex.Pattern;

public class Testt {
    public static void main(String[] args)
    {
        String txt="T01X064900Y049200X065900X066900X067900X068900X069900T02X062900Y048200Y049200Y050200Y053700X063900X064900X065900X046350";
            Pattern ptn = Pattern.compile("T");
            String[] parts = ptn.split(txt);
            for(String p:parts){
                if(!p.isEmpty()){
                    System.out.println("T"+p);
                }
            }
    }
}
</code>```

Output:

T01X064900Y049200X065900X066900X067900X068900X069900
T02X062900Y048200Y049200Y050200Y053700X063900X064900X065900X046350

ContentLicense: CC BY-SA 3.0

Title: splitting a drill file using regex

Body:
i have a file here is it's dump

T01
X064900Y049200
X065900
X066900
X067900
X068900
X069900
T02
X062900Y048200
Y049200
Y050200
Y053700
X063900
X064900
X065900
X046350

I wan to split it's contents   by T*   "T* must be included" by using
Java regex
   here what i did i read file contents into string parts
then String [] tools = parts.split("T\\d+");

but it didn't work, what is the best regex to use .

Body:
Here is your solution.I am assuming that you are expecting separate strings which starts with the letter 'T'.

package com.sujit;

import java.util.regex.Pattern;

public class Testt {
    public static void main(String[] args)
    {
        String txt="T01X064900Y049200X065900X066900X067900X068900X069900T02X062900Y048200Y049200Y050200Y053700X063900X064900X065900X046350";
            Pattern ptn = Pattern.compile("T");
            String[] parts = ptn.split(txt);
            for(String p:parts){
                if(!p.isEmpty()){
                    System.out.println("T"+p);
                }
            }
    }
}

Output:

T01X064900Y049200X065900X066900X067900X068900X069900
T02X062900Y048200Y049200Y050200Y053700X063900X064900X065900X046350


问:
Pass array to Laravel view and use that array as VueJS prop
I have an array variable $screenshots that I am trying to pass to my Laravel view. Usually, I would use the @foreach and loop through the array, but I want to pass the full array to a Vue component by defining it as a prop. I want to do this so that I can loop over the array in the component. I am getting the htmlentities() expects parameter 1 to be string, array given error.

What is the proper way to do this with VueJS and Laravel?

Here is my blade template:

```<code>@section('content')

    <ticket-edit id="edit-ticket" single-ticket="{{ $ticket }}" screenshots="{{ $files }}">

    </ticket-edit>

@endsection
</code>```

Here is my custom component (different file):

```<code><script>
    export default {

        template: '#edit-ticket-template',

        props: ['SingleTicket', 'screenshots'],

        data: function() {
            return {
                ticket: [],
                screenshots: []
            };
        },

        methods: {
            getTicket() {
                return this.ticket = JSON.parse(this.SingleTicket);
            },

            getScreenshots() {
                return this.screenshots = JSON.parse(this.files);
            },

            createNotes: function () {
                var ticketNotes = $('.summernote');
                ticketNotes.summernote({
                    height: 260,
                    toolbar: [
                        ['style', ['bold', 'italic', 'underline', 'clear', 'strikethrough']],
                        ['fontsize', ['fontsize']],
                        ['para', ['ul', 'ol']],
                    ]
                });
            }
        },

        created: function() {
            this.getTicket();
            this.getScreenshots();
        },

        ready: function() {
            this.createNotes();
        }

    }
</script>
</code>```

EDIT: When I am adding attachments, I am using json_encode to encode the path to the attachments. Then when I retrieve them, I run json_decode in my model like so $files = json_decode($ticket->screenshots); So my controller looks like this:

```<code>public function edit($sub_domain, $id)
{
    $ticket = Ticket::find($id);
    $files = json_decode($ticket->screenshots);

    return view('templates.tickets-single', compact('ticket', 'files'));
}
</code>```

答: You should use {!! json_encode($ticket) !!}}

Body:
I have an array variable $screenshots that I am trying to pass to my Laravel view. Usually, I would use the @foreach and loop through the array, but I want to pass the full array to a Vue component by defining it as a prop. I want to do this so that I can loop over the array in the component. I am getting the htmlentities() expects parameter 1 to be string, array given error.

What is the proper way to do this with VueJS and Laravel?

Here is my blade template:

@section('content')

    <ticket-edit id="edit-ticket" single-ticket="{{ $ticket }}" screenshots="{{ $files }}">

    </ticket-edit>

@endsection

Here is my custom component (different file):

EDIT: When I am adding attachments, I am using json_encode to encode the path to the attachments. Then when I retrieve them, I run json_decode in my model like so $files = json_decode($ticket->screenshots); So my controller looks like this:

public function edit($sub_domain, $id)
{
    $ticket = Ticket::find($id);
    $files = json_decode($ticket->screenshots);

    return view('templates.tickets-single', compact('ticket', 'files'));
}


问:
How to use bitcoin blockchain for image usage?
I have read a little about blockchains and found there is lot of blockchain npm libraries available.

How can I take benefit of the bitcoin blockchain to authenticate documents :  to obtain a proof a document has not been falsificated.

Any clues, suggestions, ideas and remarks are welcome.

答:
If you are looking for a way to certify the existence of an image, I'd suggest taking at OpenTimestamps. OpenTimestamps collects documents to timestamp and batches them in such a way that they use only minimal space in the blockchain, but still gain the advantages of using the Bitcoin blockchain.

If on the other hand you are looking to track ownership of assets, then I suggest looking into the native assets of Elements Project or Colored coins.

I would strongly suggest attempting to build a new scheme on top of an existing blockchain if one of these suggestions fits your use-case.

(disclaimer: my employer is a contributor in the Elements Project)

ContentLicense: CC BY-SA 4.0


问:
java.lang.NoClassDefFoundError: io.reactivex.Observable
When I use Observable in my retrofit API on the phone with API 21 I got this error:

```<code>java.lang.NoClassDefFoundError: io.reactivex.Observable
</code>```

but on the phone with API 19 or emulator with API 23 it works.

This is my API Interface:

```<code>import io.reactivex.Observable;
import retrofit2.Response;
import retrofit2.http.Body;
import retrofit2.http.POST;
public interface ApiService {
    /**
     * Created by Mohsen on 5/10/2017.
     *
     */
    @POST("/cp/api/")
    Observable<Response<Integer>> Get_BuyBox_Count(@Body Object request);
}
</code>```

and this is my Retrofit setting:

```<code>    @Provides
    @Application_Scope
    @Store_Retrofit_Qualifier
    public Retrofit Store_retrofit(OkHttpClient client) {
        return new Retrofit.Builder()
                .baseUrl(Urls.Sotre_Base_Url)
                .client(client)
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .addConverterFactory(JSONConverterFactory.create())
                .addConverterFactory(GsonConverterFactory.create())
                .build();
    }
</code>```

my Dependencies:

```<code>    compile 'com.squareup.retrofit2:retrofit:2.2.0'
    compile 'com.squareup.retrofit2:converter-gson:2.1.0'
    compile 'io.reactivex.rxjava2:rxjava:2.0.1'
    compile 'io.reactivex.rxjava2:rxandroid:2.0.1'
    compile 'com.jakewharton.retrofit:retrofit2-rxjava2-adapter:1.0.0'
</code>```

答:
Finally, after while I found the solution.

the problem is conflicting  Rxjava with Constrainlayout

```<code>compile 'com.android.support.constraint:constraint-layout:1.0.2'
</code>```

with

```<code>compile 'io.reactivex:rxjava:1.2.6'
</code>```

Body:
When I use Observable in my retrofit API on the phone with API 21 I got this error:

java.lang.NoClassDefFoundError: io.reactivex.Observable

but on the phone with API 19 or emulator with API 23 it works.

This is my API Interface:

import io.reactivex.Observable;
import retrofit2.Response;
import retrofit2.http.Body;
import retrofit2.http.POST;
public interface ApiService {
    /**
     * Created by Mohsen on 5/10/2017.
     *
     */
    @POST("/cp/api/")
    Observable<Response<Integer>> Get_BuyBox_Count(@Body Object request);
}

and this is my Retrofit setting:

    @Provides
    @Application_Scope
    @Store_Retrofit_Qualifier
    public Retrofit Store_retrofit(OkHttpClient client) {
        return new Retrofit.Builder()
                .baseUrl(Urls.Sotre_Base_Url)
                .client(client)
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .addConverterFactory(JSONConverterFactory.create())
                .addConverterFactory(GsonConverterFactory.create())
                .build();
    }

my Dependencies:

    compile 'com.squareup.retrofit2:retrofit:2.2.0'
    compile 'com.squareup.retrofit2:converter-gson:2.1.0'
    compile 'io.reactivex.rxjava2:rxjava:2.0.1'
    compile 'io.reactivex.rxjava2:rxandroid:2.0.1'
    compile 'com.jakewharton.retrofit:retrofit2-rxjava2-adapter:1.0.0'

Body:
Finally, after while I found the solution.

the problem is conflicting  Rxjava with Constrainlayout

compile 'com.android.support.constraint:constraint-layout:1.0.2'

with

compile 'io.reactivex:rxjava:1.2.6'


问:
How to set authorization header in SoapUIProTestCaseRunner?
While integrating ReadyAPI tests with Java code, how to set authorization? I get error:

```<code>#status# : HTTP/1.1 403 Forbidden in java console
</code>```

```<code>SoapUIProTestCaseRunner runner = new SoapUIProTestCaseRunner();
runner.setProjectFile("C://APILOcal//activations.xml");
runner.setTestSuite("ServiceSOAP TestSuite");
runner.setTestCase("createContractBundle TestCase");
runner.setTestStepCount(3);
//runner.setGlobalProperties(new String[]{"Authorization: Basic admin=admin"});
//runner.setCustomHeaders(new String[]{"Authorization: Basic admin=admin"});
//runner.setUsername("admin");
//runner.setPassword("admin");
//runner.setWssPasswordType("PasswordText");
runner.run();
</code>```

Please guide.

答: Request(s) inside your SOAPUI project must have Authorization. User Name/Password values there can be set explicitly or to the Custom Properties from any level Project, Test Suite etc...</p>

Body:
While integrating ReadyAPI tests with Java code, how to set authorization? I get error:

#status# : HTTP/1.1 403 Forbidden in java console

SoapUIProTestCaseRunner runner = new SoapUIProTestCaseRunner();
runner.setProjectFile("C://APILOcal//activations.xml");
runner.setTestSuite("ServiceSOAP TestSuite");
runner.setTestCase("createContractBundle TestCase");
runner.setTestStepCount(3);
//runner.setGlobalProperties(new String[]{"Authorization: Basic admin=admin"});
//runner.setCustomHeaders(new String[]{"Authorization: Basic admin=admin"});
//runner.setUsername("admin");
//runner.setPassword("admin");
//runner.setWssPasswordType("PasswordText");
runner.run();

Please guide.


问:
making a rock, paper, scissors code in python. SyntaxError: multiple statements found while compiling a single statement
this is my code:

```<code>import random
import time

validInput = False

computer = (random.choice(["rock", "paper", "scissors"]))
batman = input("welcome to rock, paper, scissors would you like to play: yes or no?"
if batman == "yes":
         choice = input("okay, these are the rules: I will say, rock, paper, scissors, shoot and then I will ask you what you picked and then tell you who won - are you ready to play: yes or no?")
         if choice == "yes":
            while validInput = False:
              time.sleep(1)

              print("rock")
              time.sleep(1)

              print("paper")
              time.sleep(1)

              print("scissors")
              time.sleep(1)

              print("shoot")
              time.sleep(1)

              what = input("what did you pick")
              if what == "rock" and computer == "rock":
                  print("I picked rock too, I guess we drawed")
                  fudge = input("do you want to play again: yes or no?)
                  if fudge == "yes":
                     print("restarting program")
                     continue
                  if fudge == "no":
                     print("okay, terminating program")
                     exit()
                  else:
                     print("invalid input, terminating program")
                     exit()
              if what == "rock" and computer == "paper":
                  print("I picked paper, so I guess I won better luck next time")
                  fudge = input("do you want to play again: yes or no?)
                  if fudge == "yes":
                     print("restarting program")
                     continue
                  if fudge == "no":
                     print("okay, terminating program")
                     exit()
                  else:
                     print("invalid input, terminating program")
                     exit()
              if what == "rock" and computer == "scissors":
                  print("I picked scissors, I guess you win")
                  fudge = input("do you want to play again: yes or no?)
                  if fudge == "yes":
                     print("restarting program")
                     continue
                  if fudge == "no":
                     print("okay, terminating program")
                     exit()
                  else:
                     print("invalid input, terminating program")
                     exit()
              if what == "paper" and computer == "paper":
                  print("I picked paper, so I guess we drawed")
                  fudge = input("do you want to play again: yes or no?)
                  if fudge == "yes":
                     print("restarting program")
                     continue
                  if fudge == "no":
                     print("okay, terminating program")
                     exit()
                  else:
                     print("invalid input, terminating program")
                     exit()
              if what == "paper" and computer == "scissors":
                  print("I picked scissors, so I guess I won better luck next time")
                  fudge = input("do you want to play again: yes or no?)
                  if fudge == "yes":
                     print("restarting program")
                     continue
                  if fudge == "no":
                     print("okay, terminating program")
                     exit()
                  else:
                     print("invalid input, terminating program")
                     exit()
              if what == "paper" and computer == "rock":
                  print("I picked rock, so I guess you won")
                  fudge = input("do you want to play again: yes or no?)
                  if fudge == "yes":
                     print("restarting program")
                     continue
                  if fudge == "no":
                     print("okay, terminating program")
                     exit()
                  else:
                     print("invalid input, terminating program")
                     exit()
              if what == "scissors" and computer == "scissors":
                  print("I picked scissors, so I guess we drawed")
                  fudge = input("do you want to play again: yes or no?)
                  if fudge == "yes":
                     print("restarting program")
                     continue
                  if fudge == "no":
                     print("okay, terminating program")
                     exit()
                  else:
                     print("invalid input, terminating program")
                     exit()
              if what == "scissors" and computer == "rock":
                  print("I picked rock, so I guess I won better luck next time")
                  fudge = input("do you want to play again: yes or no?)
                  if fudge == "yes":
                     print("restarting program")
                     continue
                  if fudge == "no":
                     print("okay, terminating program")
                     exit()
                  else:
                     print("invalid input, terminating program")
                     exit()
              if what == "scissors" and computer == "paper":
                  print("I picked paper, so I guess you won")
                  fudge = input("do you want to play again: yes or no?)
                  if fudge == "yes":
                     print("restarting program")
                     continue
                  if fudge == "no":
                     print("okay, terminating program")
                     exit()
                  else:
                     print("invalid input, terminating program")
                     exit()
              else:
                  chicken = input("invalid input, do you want to try again: yes or no?")
                  if chicken == "yes":
                      print("restarting now")
                      invalidInput = False
                      continue
                  if chicken == "no":
                      print("okay, terminating program")
                      invalidInput = True
                      exit()
                  else:
                      print("invalid input, terminating program")
                      invalidInput = True
                      exit()

         if choice == "no":
               print("okay terminating program")
               invalidInput = True
               exit()
         else:
             print("invalid input, terminating program")
             exit()

if batman == "no"
   print("okay, terminating program")
   exit()

else:
   print ("invalid input, terminating program")
   exit()
</code>```

i don't know why it isn't working all it tells me is

SyntaxError: multiple statements found while compiling a single statement.

could someone please help thank you.

Oh also i'm running python on 3.6.0

答:
In the while loop you are making an assignment, not a comparison, change = to ==.

Every time you use fudge() there are missing quotes at the end.

At the end, you have if batman == "no" where it should have been if batman == "no": (note the two points).

Body:
this is my code:

import random
import time

validInput = False

computer = (random.choice(["rock", "paper", "scissors"]))
batman = input("welcome to rock, paper, scissors would you like to play: yes or no?"
if batman == "yes":
         choice = input("okay, these are the rules: I will say, rock, paper, scissors, shoot and then I will ask you what you picked and then tell you who won - are you ready to play: yes or no?")
         if choice == "yes":
            while validInput = False:
              time.sleep(1)

              print("rock")
              time.sleep(1)

              print("paper")
              time.sleep(1)

              print("scissors")
              time.sleep(1)

              print("shoot")
              time.sleep(1)

              what = input("what did you pick")
              if what == "rock" and computer == "rock":
                  print("I picked rock too, I guess we drawed")
                  fudge = input("do you want to play again: yes or no?)
                  if fudge == "yes":
                     print("restarting program")
                     continue
                  if fudge == "no":
                     print("okay, terminating program")
                     exit()
                  else:
                     print("invalid input, terminating program")
                     exit()
              if what == "rock" and computer == "paper":
                  print("I picked paper, so I guess I won better luck next time")
                  fudge = input("do you want to play again: yes or no?)
                  if fudge == "yes":
                     print("restarting program")
                     continue
                  if fudge == "no":
                     print("okay, terminating program")
                     exit()
                  else:
                     print("invalid input, terminating program")
                     exit()
              if what == "rock" and computer == "scissors":
                  print("I picked scissors, I guess you win")
                  fudge = input("do you want to play again: yes or no?)
                  if fudge == "yes":
                     print("restarting program")
                     continue
                  if fudge == "no":
                     print("okay, terminating program")
                     exit()
                  else:
                     print("invalid input, terminating program")
                     exit()
              if what == "paper" and computer == "paper":
                  print("I picked paper, so I guess we drawed")
                  fudge = input("do you want to play again: yes or no?)
                  if fudge == "yes":
                     print("restarting program")
                     continue
                  if fudge == "no":
                     print("okay, terminating program")
                     exit()
                  else:
                     print("invalid input, terminating program")
                     exit()
              if what == "paper" and computer == "scissors":
                  print("I picked scissors, so I guess I won better luck next time")
                  fudge = input("do you want to play again: yes or no?)
                  if fudge == "yes":
                     print("restarting program")
                     continue
                  if fudge == "no":
                     print("okay, terminating program")
                     exit()
                  else:
                     print("invalid input, terminating program")
                     exit()
              if what == "paper" and computer == "rock":
                  print("I picked rock, so I guess you won")
                  fudge = input("do you want to play again: yes or no?)
                  if fudge == "yes":
                     print("restarting program")
                     continue
                  if fudge == "no":
                     print("okay, terminating program")
                     exit()
                  else:
                     print("invalid input, terminating program")
                     exit()
              if what == "scissors" and computer == "scissors":
                  print("I picked scissors, so I guess we drawed")
                  fudge = input("do you want to play again: yes or no?)
                  if fudge == "yes":
                     print("restarting program")
                     continue
                  if fudge == "no":
                     print("okay, terminating program")
                     exit()
                  else:
                     print("invalid input, terminating program")
                     exit()
              if what == "scissors" and computer == "rock":
                  print("I picked rock, so I guess I won better luck next time")
                  fudge = input("do you want to play again: yes or no?)
                  if fudge == "yes":
                     print("restarting program")
                     continue
                  if fudge == "no":
                     print("okay, terminating program")
                     exit()
                  else:
                     print("invalid input, terminating program")
                     exit()
              if what == "scissors" and computer == "paper":
                  print("I picked paper, so I guess you won")
                  fudge = input("do you want to play again: yes or no?)
                  if fudge == "yes":
                     print("restarting program")
                     continue
                  if fudge == "no":
                     print("okay, terminating program")
                     exit()
                  else:
                     print("invalid input, terminating program")
                     exit()
              else:
                  chicken = input("invalid input, do you want to try again: yes or no?")
                  if chicken == "yes":
                      print("restarting now")
                      invalidInput = False
                      continue
                  if chicken == "no":
                      print("okay, terminating program")
                      invalidInput = True
                      exit()
                  else:
                      print("invalid input, terminating program")
                      invalidInput = True
                      exit()

         if choice == "no":
               print("okay terminating program")
               invalidInput = True
               exit()
         else:
             print("invalid input, terminating program")
             exit()

if batman == "no"
   print("okay, terminating program")
   exit()

else:
   print ("invalid input, terminating program")
   exit()

i don't know why it isn't working all it tells me is

SyntaxError: multiple statements found while compiling a single statement.

could someone please help thank you.

Oh also i'm running python on 3.6.0


问:
what does initLoader do if loader already exists?
On developers.android.com it says,
"Ensures a loader is initialized and active. If the loader doesn't already exist, one is created and (if the activity/fragment is currently started) starts the loader. Otherwise the last created loader is re-used."

So what does it mean by last created loader is re-used? Which method does it immediately call after initLoader()  if the loader already exists?

I am asking this because I am still not sure how caching works with Loaders.

```<code> protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    getSupportLoaderManager().initLoader(loaderId, null, MainActivity.this);
}

public Loader<String[]> onCreateLoader(int id, final Bundle loaderArgs) {

    return new AsyncTaskLoader<String[]>(this) {

        String[] mCachedData = null;

        @Override
        protected void onStartLoading() {
            if (mCachedData != null) {
                deliverResult(mCachedData);
            } else {
                forceLoad();
            }
        }

 . . . . .

}
</code>```

In the above code, if the loader already exists then what is the flow? What method does it call it next after initLoader. Because if it calls onCreateLoader then my cached Data is initialized to null again.

答:
If you check the LoaderManager source initLoader creates loader only if a loader with the same id doesn't exist.

Which method does it immediately call after initLoader() if the loader
  already exists?

It tells the loader to call onLoadFinish only if the loader is already done with its job (Check this).

If the loader has not completed its job, the loader itself will call the onLoadFinish after it has finished with it.

Body:
On developers.android.com it says,
"Ensures a loader is initialized and active. If the loader doesn't already exist, one is created and (if the activity/fragment is currently started) starts the loader. Otherwise the last created loader is re-used."

So what does it mean by last created loader is re-used? Which method does it immediately call after initLoader()  if the loader already exists?

I am asking this because I am still not sure how caching works with Loaders.

 protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    getSupportLoaderManager().initLoader(loaderId, null, MainActivity.this);
}

public Loader<String[]> onCreateLoader(int id, final Bundle loaderArgs) {

    return new AsyncTaskLoader<String[]>(this) {

        String[] mCachedData = null;

        @Override
        protected void onStartLoading() {
            if (mCachedData != null) {
                deliverResult(mCachedData);
            } else {
                forceLoad();
            }
        }

 . . . . .

}

In the above code, if the loader already exists then what is the flow? What method does it call it next after initLoader. Because if it calls onCreateLoader then my cached Data is initialized to null again.


问:
silverlight draw on bitmap
```<code>Image img = new Bitmap(Image.FromFile(file.FullName));

using (Graphics g = Graphics.FromImage(img)){
    g.DrawRectangle(Pens.Black, 0, 0, img.Width - 2, img.Height - 2);
}
</code>```

like this

how to do in sliverlight?

答:
You can use a WriteableBitmap for this. Create a Canvas and draw your elements on the Canvas, load other images etc. Then once you are done rendering on the Canvase you can create the WriteableBitmap from the Canvas and then do what every you need.

In the example below I assigned the bitmap as the Source of an Image element to show that the final result.

```<code>Canvas canvas = new Canvas();
UIElement ellipse = new Ellipse()
  { Width = 100, Height = 100, Fill = new SolidColorBrush(Colors.Red) };
Canvas.SetLeft(ellipse, 100);
Canvas.SetTop(ellipse, 100);
canvas.Children.Add(ellipse);

WriteableBitmap bmp = new WriteableBitmap(canvas, null);
myImage.Source = bmp;
</code>```

ContentLicense: CC BY-SA 2.5

Title: silverlight draw on bitmap

Body:
Image img = new Bitmap(Image.FromFile(file.FullName));

using (Graphics g = Graphics.FromImage(img)){
    g.DrawRectangle(Pens.Black, 0, 0, img.Width - 2, img.Height - 2);
}

like this

how to do in sliverlight?

Body:
You can use a WriteableBitmap for this. Create a Canvas and draw your elements on the Canvas, load other images etc. Then once you are done rendering on the Canvase you can create the WriteableBitmap from the Canvas and then do what every you need.

In the example below I assigned the bitmap as the Source of an Image element to show that the final result.

Canvas canvas = new Canvas();
UIElement ellipse = new Ellipse()
  { Width = 100, Height = 100, Fill = new SolidColorBrush(Colors.Red) };
Canvas.SetLeft(ellipse, 100);
Canvas.SetTop(ellipse, 100);
canvas.Children.Add(ellipse);

WriteableBitmap bmp = new WriteableBitmap(canvas, null);
myImage.Source = bmp;


问:
java.util.zip.ZipException: duplicate entry error
here's my build.gradle dependencies part :
 `

dependencies {

```<code>compile fileTree(include: ['*.jar'], dir: 'libs')

compile 'com.android.support:appcompat-v7:23.0.0'
compile files('libs/google-play-services.jar')

compile files('libs/android-async-http-1.4.9.jar')
compile 'cz.msebera.android:httpclient:4.3.6'
compile 'com.google.android.gms:play-services-location:7.+'
</code>```

and my error is :
Error:Execution failed for task ':app:packageAllDebugClassesForMultiDex'.

java.util.zip.ZipException: duplicate entry: com/google/android/gms/auth/UserRecoverableAuthException.class

what's the cause of the error ??

答:
You are adding google-play-services twice in your gradle file.

```<code>compile files('libs/google-play-services.jar')
compile 'com.google.android.gms:play-services-location:7.+'
</code>```

Remove the following line from your build.gradle file.

```<code>compile files('libs/google-play-services.jar')
</code>```

Body:
here's my build.gradle dependencies part :
 `

dependencies {

compile fileTree(include: ['*.jar'], dir: 'libs')

compile 'com.android.support:appcompat-v7:23.0.0'
compile files('libs/google-play-services.jar')

compile files('libs/android-async-http-1.4.9.jar')
compile 'cz.msebera.android:httpclient:4.3.6'
compile 'com.google.android.gms:play-services-location:7.+'

and my error is :
Error:Execution failed for task ':app:packageAllDebugClassesForMultiDex'.

java.util.zip.ZipException: duplicate entry: com/google/android/gms/auth/UserRecoverableAuthException.class

what's the cause of the error ??

Body:
You are adding google-play-services twice in your gradle file.

compile files('libs/google-play-services.jar')
compile 'com.google.android.gms:play-services-location:7.+'

Remove the following line from your build.gradle file.

compile files('libs/google-play-services.jar')


问:
How do I merge two sorted object lists based on common attribute in Java
I have two object lists both with a common attribute called timestamp and both are sorted by timestamp.

I want to broadcast these objects one by one based on the timestamp, example if first object of 1st list has timestamp < first object of 2nd list, broadcast first object of the 1st list and then compare second object of the 1st list with the first object of the 2nd list.

I am a newbie in java. This is what I have come up with:

```<code> //Merge the 2 object lists based on timestamp
        ListIterator<x> xIterator = list1.listIterator();
        ListIterator<y> yIterator = list2.listIterator();
        while (xIterator.hasNext() && yIterator.hasNext()) {
            if (xIterator.next().timestamp <= yIterator.next().timestamp) {
                Bundle extra = new Bundle();
                extra.putParcelable(LocalBroadcastConstants.ACTION, xIterator.previous());
                MyBroadcastManager.getInstance(getTargetContext()).sendBroadcast(
                        new Intent(LocalBroadcastConstants.ACTION_SEND).putExtras(extra)
                );
                yIterator.previous();
            } else {
                Bundle extra = new Bundle();
                extra.putParcelable(LocalBroadcastConstants.ACTION,
                        yIterator.previous());
                MyBroadcastManager.getInstance(getTargetContext()).sendBroadcast(
                        new Intent(LocalBroadcastConstants.ACTION_SEND).putExtras(extra)
                );
                xIterator.previous();
            }
</code>```

I know my logic is incorrect because for the first item in the Iterators, xIterator.previous and yIterator.previous will point to nothing. I can't seem to find the correct solution for this problem statement. Please help.

答:
If you want to merge two lists with Sorting with one of the fields, the below example may help u. Using Java8 Streams</p>

```<code>Obj p1 = new Obj();
    p1.setDept("EC");
    p1.setName("Sagar");
    p1.setJoinedDate(new Date(2007, 8, 2));

    Obj p2 = new Obj();
    p2.setDept("EE");
    p2.setName("Rang");
    p2.setJoinedDate(new Date(2007, 8, 3));

    Obj p3 = new Obj();
    p3.setDept("ME");
    p3.setName("Avadh");
    p3.setJoinedDate(new Date(2008, 8, 2));

    Obj p4 = new Obj();
    p4.setDept("IP");
    p4.setName("Pams");
    p4.setJoinedDate(new Date(2007, 8, 1));

    List<Obj> dept1 = new ArrayList<>();
    dept1.add(p1);
    dept1.add(p2);

    List<Obj> dept2 = new ArrayList<>();
    dept2.add(p3);
    dept2.add(p4);
    dept1.addAll(dept2);
    List<Obj> sortedList = dept1.stream().sorted(new Comparator<Obj>() {

        @Override
        public int compare(Obj o1, Obj o2) {
            if(Instant.ofEpochMilli(o1.getJoinedDate().getTime()).atZone(ZoneId.systemDefault())
            .toLocalDateTime().isBefore(Instant.ofEpochMilli(o2.getJoinedDate().getTime()).atZone(ZoneId.systemDefault())
            .toLocalDateTime())){
                return -1;
            }else if(Instant.ofEpochMilli(o1.getJoinedDate().getTime()).atZone(ZoneId.systemDefault())
                    .toLocalDateTime().isAfter(Instant.ofEpochMilli(o2.getJoinedDate().getTime()).atZone(ZoneId.systemDefault())
                            .toLocalDateTime())){
                return 1;
            }
            return 0;
        }
    }).collect(Collectors.toList());

    System.out.println(sortedList);
</code>```

Body:
I have two object lists both with a common attribute called timestamp and both are sorted by timestamp.

I want to broadcast these objects one by one based on the timestamp, example if first object of 1st list has timestamp < first object of 2nd list, broadcast first object of the 1st list and then compare second object of the 1st list with the first object of the 2nd list.

I am a newbie in java. This is what I have come up with:

 //Merge the 2 object lists based on timestamp
        ListIterator<x> xIterator = list1.listIterator();
        ListIterator<y> yIterator = list2.listIterator();
        while (xIterator.hasNext() && yIterator.hasNext()) {
            if (xIterator.next().timestamp <= yIterator.next().timestamp) {
                Bundle extra = new Bundle();
                extra.putParcelable(LocalBroadcastConstants.ACTION, xIterator.previous());
                MyBroadcastManager.getInstance(getTargetContext()).sendBroadcast(
                        new Intent(LocalBroadcastConstants.ACTION_SEND).putExtras(extra)
                );
                yIterator.previous();
            } else {
                Bundle extra = new Bundle();
                extra.putParcelable(LocalBroadcastConstants.ACTION,
                        yIterator.previous());
                MyBroadcastManager.getInstance(getTargetContext()).sendBroadcast(
                        new Intent(LocalBroadcastConstants.ACTION_SEND).putExtras(extra)
                );
                xIterator.previous();
            }

I know my logic is incorrect because for the first item in the Iterators, xIterator.previous and yIterator.previous will point to nothing. I can't seem to find the correct solution for this problem statement. Please help.

Body:
If you want to merge two lists with Sorting with one of the fields, the below example may help u. Using Java8 Streams

Obj p1 = new Obj();
    p1.setDept("EC");
    p1.setName("Sagar");
    p1.setJoinedDate(new Date(2007, 8, 2));

    Obj p2 = new Obj();
    p2.setDept("EE");
    p2.setName("Rang");
    p2.setJoinedDate(new Date(2007, 8, 3));

    Obj p3 = new Obj();
    p3.setDept("ME");
    p3.setName("Avadh");
    p3.setJoinedDate(new Date(2008, 8, 2));

    Obj p4 = new Obj();
    p4.setDept("IP");
    p4.setName("Pams");
    p4.setJoinedDate(new Date(2007, 8, 1));

    List<Obj> dept1 = new ArrayList<>();
    dept1.add(p1);
    dept1.add(p2);

    List<Obj> dept2 = new ArrayList<>();
    dept2.add(p3);
    dept2.add(p4);
    dept1.addAll(dept2);
    List<Obj> sortedList = dept1.stream().sorted(new Comparator<Obj>() {

        @Override
        public int compare(Obj o1, Obj o2) {
            if(Instant.ofEpochMilli(o1.getJoinedDate().getTime()).atZone(ZoneId.systemDefault())
            .toLocalDateTime().isBefore(Instant.ofEpochMilli(o2.getJoinedDate().getTime()).atZone(ZoneId.systemDefault())
            .toLocalDateTime())){
                return -1;
            }else if(Instant.ofEpochMilli(o1.getJoinedDate().getTime()).atZone(ZoneId.systemDefault())
                    .toLocalDateTime().isAfter(Instant.ofEpochMilli(o2.getJoinedDate().getTime()).atZone(ZoneId.systemDefault())
                            .toLocalDateTime())){
                return 1;
            }
            return 0;
        }
    }).collect(Collectors.toList());

    System.out.println(sortedList);


问:
Can I specify a path to Python.h for sip-4.18.1 when running 'make' command?
I am trying to configure sip-4.18.1 on RHEL 7. I have downloaded/installed/configured Python3.5.2.

When I run 'make' inside sip directory I get this error:

gcc -c -pipe -fPIC -O2 -Wall -W -DNDEBUG -I. -I/usr/include/python2.7 -o siplib.o siplib.c
  siplib.c:20:20: fatal error: Python.h: No such file or directory
   #include

Which I would understand to mean that there is Python 2.7 at least downloaded to this machine, but it doesn't look to be configured.

Is there any way I can specify a path for sip to look for Python.h when running 'make'?

答:
Maybe you need to install python-dev and/or python3-dev</p>

```<code>sudo apt-get install python-dev
sudo apt-get install python3-dev
</code>```

Body:
Maybe you need to install python-dev and/or python3-dev

sudo apt-get install python-dev
sudo apt-get install python3-dev


答: you need use multidex in project link</p>

Title: java.util.zip.ZipException: duplicate entry error

Body: you need use multidex in project link


问:
Code generation for Python 3 annotation with default value
In working over uncompyle6 decompilation bugs I've come across problem
of trying to reconcile CPython assembly output with what the Python
docs describe for MAKE_FUNCTION.

Python Source:

```<code>def foo(x: 'an argument that defaults to 5' = 5):
    return
</code>```

Disassemby (xdis's version):

```<code> # Argument count:    1
 # Kw-only arguments: 0
 # Number of locals:  1
 # Stack size:        1
 # Flags:             0x00000043 (NOFREE | NEWLOCALS | OPTIMIZED)
 # First Line:        1
 # Constants:
 #    0: 5
 #    1: 'an argument that defaults to 5'
 #    2: ('x',)
 #    3: <code object foo at 0x7f49115938a0, file "exec", line 1>
 #    4: 'foo'
 #    5: None
 # Names:
 #    0: foo
 1 0 LOAD_CONST                0 (5)
   3 LOAD_CONST                1 ('an argument that defaults to 5')
   6 LOAD_CONST                2 (('x',))
   9 LOAD_CONST                3 (<code object foo at 0x7f49115938a0, file "exec", line 1>)
  12 LOAD_CONST                4 ('foo')
  15 EXTENDED_ARG              2 (131072)
  18 MAKE_FUNCTION        131073 (1 positional, 0 name and default, 2 annotations)
  21 STORE_NAME                0 (foo)
  24 LOAD_CONST                5 (None)
  27 RETURN_VALUE
</code>```

Note that in offset 18 the value is basically the arg value at offset 19 (1) plus the extended arg value.

The interpretation in parenthesis is xdis's and may not be correct. Edit: Not only is it correct, but the additional pair in offset 6 to indicate a tuple is essential.

In https://docs.python.org/3.4/library/dis.html#opcode-MAKE_FUNCTION it says:

Pushes a new function object on the stack. From bottom to top, the consumed stack must consist of

argc & 0xFF default argument objects in positional order

(argc >> 8) & 0xFF pairs of name and default argument, with the name just below the object on the stack, for keyword-only parameters

(argc >> 16) & 0x7FFF parameter annotation objects

a tuple listing the parameter names for the annotations (only if there are any annotation objects)

It looks to me like there is one annotation object, not two. And one default argument rather than a positional argument. Also
at offset 24 we see an mention of 5, but this is after we have
MAKE_FUNCTION. The association of a default value with parameter x is elusive in the code. Some sort of optimization here?

How am I to make sense of the assembly as an accurate representation of the Python source?

Note: I see this code generated in at least Python 3.1 - 3.5

答:
Below is uncompyle6's deparse of the above. I'm not totally sure it is correct that the first argument of mkfunc_annotate is rightly called a pos_arg rather than say a default value arg.

One of the subtle points in the assembly above is that the LOAD_CONST is of a tuple (with one argument) and that is important in clueing a deparser (or person) in that the function is annotated.

```<code>stmts
    sstmt
        stmt
            funcdef_annotate (2)
                 0. mkfunc_annotate (7)
                     0. pos_arg
                        expr
                            L.   1       0  LOAD_CONST            5  5
                     1. annotate_arg
                        expr
                                         3  LOAD_CONST               'an argument that defaults to 5'
                     2. annotate_tuple
                                     6  LOAD_CONST               ('x',)
                     3.              9  LOAD_CONST               '<code_object foo>'
                     4.             12  LOAD_CONST               'foo'
                     5.             15  EXTENDED_ARG     131074  '131072'
                     6.             18  MAKE_FUNCTION_A_2_1        '1 positional, 0 keyword pair, 2 annotated'
                 1. designator
                                21  STORE_NAME               'foo'
</code>```

Body:
In working over uncompyle6 decompilation bugs I've come across problem
of trying to reconcile CPython assembly output with what the Python
docs describe for MAKE_FUNCTION.

Python Source:

def foo(x: 'an argument that defaults to 5' = 5):
    return

Disassemby (xdis's version):

 # Argument count:    1
 # Kw-only arguments: 0
 # Number of locals:  1
 # Stack size:        1
 # Flags:             0x00000043 (NOFREE | NEWLOCALS | OPTIMIZED)
 # First Line:        1
 # Constants:
 #    0: 5
 #    1: 'an argument that defaults to 5'
 #    2: ('x',)
 #    3:
 #    4: 'foo'
 #    5: None
 # Names:
 #    0: foo
 1 0 LOAD_CONST                0 (5)
   3 LOAD_CONST                1 ('an argument that defaults to 5')
   6 LOAD_CONST                2 (('x',))
   9 LOAD_CONST                3 ()
  12 LOAD_CONST                4 ('foo')
  15 EXTENDED_ARG              2 (131072)
  18 MAKE_FUNCTION        131073 (1 positional, 0 name and default, 2 annotations)
  21 STORE_NAME                0 (foo)
  24 LOAD_CONST                5 (None)
  27 RETURN_VALUE

Note that in offset 18 the value is basically the arg value at offset 19 (1) plus the extended arg value.

The interpretation in parenthesis is xdis's and may not be correct. Edit: Not only is it correct, but the additional pair in offset 6 to indicate a tuple is essential.

In https://docs.python.org/3.4/library/dis.html#opcode-MAKE_FUNCTION it says:

Pushes a new function object on the stack. From bottom to top, the consumed stack must consist of

argc & 0xFF default argument objects in positional order

(argc >> 8) & 0xFF pairs of name and default argument, with the name just below the object on the stack, for keyword-only parameters

(argc >> 16) & 0x7FFF parameter annotation objects

a tuple listing the parameter names for the annotations (only if there are any annotation objects)

It looks to me like there is one annotation object, not two. And one default argument rather than a positional argument. Also
at offset 24 we see an mention of 5, but this is after we have
MAKE_FUNCTION. The association of a default value with parameter x is elusive in the code. Some sort of optimization here?

How am I to make sense of the assembly as an accurate representation of the Python source?

Note: I see this code generated in at least Python 3.1 - 3.5

Body:
Below is uncompyle6's deparse of the above. I'm not totally sure it is correct that the first argument of mkfunc_annotate is rightly called a pos_arg rather than say a default value arg.

One of the subtle points in the assembly above is that the LOAD_CONST is of a tuple (with one argument) and that is important in clueing a deparser (or person) in that the function is annotated.

stmts
    sstmt
        stmt
            funcdef_annotate (2)
                 0. mkfunc_annotate (7)
                     0. pos_arg
                        expr
                            L.   1       0  LOAD_CONST            5  5
                     1. annotate_arg
                        expr
                                         3  LOAD_CONST               'an argument that defaults to 5'
                     2. annotate_tuple
                                     6  LOAD_CONST               ('x',)
                     3.              9  LOAD_CONST               '<code_object foo>'
                     4.             12  LOAD_CONST               'foo'
                     5.             15  EXTENDED_ARG     131074  '131072'
                     6.             18  MAKE_FUNCTION_A_2_1        '1 positional, 0 keyword pair, 2 annotated'
                 1. designator
                                21  STORE_NAME               'foo'


问:
Why dose cx_freeze throw the exception like 'MSIError'
I met the question about making .py into .exe. When I try using cx_freeze to pack, I will always get 'MSIError', which is something like this:

```<code>Traceback (most recent call last):
File "setup.py", line 15, in <module>
  setup(name="NumberCounter",version="1.0",description="无",options={"build_exe":build_options},executables=executables)
File "C:\Users\apple1\AppData\Local\Programs\Python\Python35\lib\site-packages\cx_Freeze\dist.py", line 349, in setup
  distutils.core.setup(**attrs)
File "C:\Users\apple1\AppData\Local\Programs\Python\Python35\lib\distutils\core.py", line 148, in setup
  dist.run_commands()
File "C:\Users\apple1\AppData\Local\Programs\Python\Python35\lib\distutils\dist.py", line 955, in run_commands
  self.run_command(cmd)
File "C:\Users\apple1\AppData\Local\Programs\Python\Python35\lib\distutils\dist.py", line 974, in run_command
  cmd_obj.run()
File "C:\Users\apple1\AppData\Local\Programs\Python\Python35\lib\site-packages\cx_Freeze\windist.py", line 392, in run
  self.add_files()
File "C:\Users\apple1\AppData\Local\Programs\Python\Python35\lib\site-packages\cx_Freeze\windist.py", line 133, in add_files
  cab.commit(db)
File "C:\Users\apple1\AppData\Local\Programs\Python\Python35\lib\msilib\__init__.py", line 220, in commit
  add_stream(db, self.name, filename)
File "C:\Users\apple1\AppData\Local\Programs\Python\Python35\lib\msilib\__init__.py", line 129, in add_stream
  r.SetStream(1, path)
_msi.MSIError: 1: 1101 2: C:\Users\apple1\AppData\Local\Temp\tmp5kgryuh8 3: 2
</code>```

How can I solve it and why did it happen?

答:
I'll unpack the error line for you.

```<code>_msi.MSIError: 1: 1101 2: C:\Users\apple1\AppData\Local\Temp\tmp5kgryuh8 3: 2
</code>```

Per Windows Installer Error Messages, 1101 means Could not open file stream: [2]. System error: [3].

Per command net helpmsg 2, system error 2 is The system cannot find the file specified.

The path appears to be a temporary file that should have been created, but according to the error, it probably was not. You could try to use a tool like Process Monitor to figure out what if anything is going on with the temporary files.

I don't know anything useful about cx_freeze, but I do know that Windows Installer's support for Unicode is a little surprising; it can easily come off as half-baked. Because of that, I would worry about your description="无", and consider setting that to a simple ASCII-only string, just to see if it helps.

Body:
I met the question about making .py into .exe. When I try using cx_freeze to pack, I will always get 'MSIError', which is something like this:

Traceback (most recent call last):
File "setup.py", line 15, in <module>
  setup(name="NumberCounter",version="1.0",description="无",options={"build_exe":build_options},executables=executables)
File "C:\Users\apple1\AppData\Local\Programs\Python\Python35\lib\site-packages\cx_Freeze\dist.py", line 349, in setup
  distutils.core.setup(**attrs)
File "C:\Users\apple1\AppData\Local\Programs\Python\Python35\lib\distutils\core.py", line 148, in setup
  dist.run_commands()
File "C:\Users\apple1\AppData\Local\Programs\Python\Python35\lib\distutils\dist.py", line 955, in run_commands
  self.run_command(cmd)
File "C:\Users\apple1\AppData\Local\Programs\Python\Python35\lib\distutils\dist.py", line 974, in run_command
  cmd_obj.run()
File "C:\Users\apple1\AppData\Local\Programs\Python\Python35\lib\site-packages\cx_Freeze\windist.py", line 392, in run
  self.add_files()
File "C:\Users\apple1\AppData\Local\Programs\Python\Python35\lib\site-packages\cx_Freeze\windist.py", line 133, in add_files
  cab.commit(db)
File "C:\Users\apple1\AppData\Local\Programs\Python\Python35\lib\msilib\__init__.py", line 220, in commit
  add_stream(db, self.name, filename)
File "C:\Users\apple1\AppData\Local\Programs\Python\Python35\lib\msilib\__init__.py", line 129, in add_stream
  r.SetStream(1, path)
_msi.MSIError: 1: 1101 2: C:\Users\apple1\AppData\Local\Temp\tmp5kgryuh8 3: 2

How can I solve it and why did it happen?

Body:
I'll unpack the error line for you.

_msi.MSIError: 1: 1101 2: C:\Users\apple1\AppData\Local\Temp\tmp5kgryuh8 3: 2

Per Windows Installer Error Messages, 1101 means Could not open file stream: [2]. System error: [3].

Per command net helpmsg 2, system error 2 is The system cannot find the file specified.

The path appears to be a temporary file that should have been created, but according to the error, it probably was not. You could try to use a tool like Process Monitor to figure out what if anything is going on with the temporary files.

I don't know anything useful about cx_freeze, but I do know that Windows Installer's support for Unicode is a little surprising; it can easily come off as half-baked. Because of that, I would worry about your description="无", and consider setting that to a simple ASCII-only string, just to see if it helps.


问:
Flask add parameter to view methods in before_request
Lets say I have an API at /api/something. The API requires a definition for api_key, it looks in the request arguments and the cookies. If it finds the api_key, I want it to pass the api_key to the route methods, in this case something.

```<code>@app.before_request
def pass_api_key():
    api_key = request.args.get('api_key', None)
    if api_key is None:
        api_key = request.cookies.get('api_key', None)
    if api_key is None:
        return 'api_key is required'
    # add parameter of api_key to something method

@app.route('/api/something')
def something(api_key):
    return api_key
</code>```

Is this possible?

Thanks in advance.

答:
This can be done using the url_value_processor decorator:

```<code>@app.url_value_preprocessor
def get_project_object(endpoint, values):
    api_key = values.get('api_key')
    if api_key is None:
        api_key = request.cookies.get('api_key', None)
    if api_key is None:
        raise Exception('api_key is required')
    values['api_key'] = api_key
</code>```

This can also be done in a Blueprint basis, so that it only applies to the views in the specified Blueprint.

Body:
Lets say I have an API at /api/something. The API requires a definition for api_key, it looks in the request arguments and the cookies. If it finds the api_key, I want it to pass the api_key to the route methods, in this case something.

@app.before_request
def pass_api_key():
    api_key = request.args.get('api_key', None)
    if api_key is None:
        api_key = request.cookies.get('api_key', None)
    if api_key is None:
        return 'api_key is required'
    # add parameter of api_key to something method

@app.route('/api/something')
def something(api_key):
    return api_key

Is this possible?

Thanks in advance.

Body:
This can be done using the url_value_processor decorator:

@app.url_value_preprocessor
def get_project_object(endpoint, values):
    api_key = values.get('api_key')
    if api_key is None:
        api_key = request.cookies.get('api_key', None)
    if api_key is None:
        raise Exception('api_key is required')
    values['api_key'] = api_key

This can also be done in a Blueprint basis, so that it only applies to the views in the specified Blueprint.


问:
Saving multiple params in a single array with ajax and rails
When a card is dragged inside a list, I'm using thejQueryUI sortable plugin's update callback to send the new position of each card to my controller. This AJAX request posts the position attribute of every card in whichever list the dragged card was released in.

```<code>$(".js-Sortable").sortable({
    connectWith: ".js-Sortable",
    items: ".js-CardContainer",
    update: function( event, ui ) {
        if (this === ui.item.parent()[0]) {

            var data = $(this).sortable('serialize');

            $.ajax({
                url: "/c/sort",
                type: "POST",
                dataType: "script",
                data: data,
                success: function(resp){
                    console.log('Yay');
                }
            });
        }
    }
});
</code>```

This sends params which look something like this

```<code>Parameters: {"card"=>["39", "2", "1", "6", "40", "5", "18", "3", "16", "7", "17", "8", "15", "9", "10", "11", "12", "13", "14", "4"]}
</code>```

I'm then updating each affected card's position attribute in my controller action like this:

```<code>def sort
    params[:card].each_with_index do |id, index|
        card = Card.find(id)
        card.update_attribute(:position, index) if card
    end

    head :ok
end
</code>```

The view looks like this:

```<code><ul class="js-CardsContainer js-Sortable">
  <% list.cards.order(:position).where(archived: false).each do |card| %>
    <li class="js-CardContainer" id="card-<%= card.id %>">
      <%= link_to card, class: 'js-Card', :data => { :id => card.id }, remote: true do %>
        <span><%= card.title %></span>
      <% end %>
    </li>
  <% end %>
</ul>
</code>```

This is all working so far. The problem is, cards can be moved across different lists. So, I need to somehow get the id of whichever list the dragged card was released in and post that with the AJAX request too.

I can get the list_id as a variable, but how can I add this list_id to the array in the AJAX request?

答:
as per your question, you are getting cards_id and you want to pass list_id along with it

in your DOM you need to add list_id first

```<code><%= link_to card, class: 'js-Card', :data => { :id => card.id }, remote: true,"data-list-id":list.id do %>
        <span><%= card.title %></span> <% end %>
</code>```

now you need to fetch this list id in the event handler and combine it with your cards_id params

```<code>$(".js-Sortable").sortable({
    connectWith: ".js-Sortable",
    items: ".js-CardContainer",
    update: function( event, ui ) {
        if (this === ui.item.parent()[0]) {
            var data = {}
            var data['cards_id'] = $(this).sortable('serialize');
            var data['list_id'] = $(this).attr("data-list-id")
            $.ajax({
                url: "/c/sort",
                type: "POST",
                dataType: "script",
                data: data,
                success: function(resp){
                    console.log('Yay');
                }
            });
        }
    }
});
</code>```

in your controller sort action, you need to follow this code

```<code>params[:card].each_with_index do |id, index, list_id|
card = Card.find(id)
card.update(:position => index,
:list_id => params[:ListId])
end
</code>```

Hope it help

Body:
When a card is dragged inside a list, I'm using thejQueryUI sortable plugin's update callback to send the new position of each card to my controller. This AJAX request posts the position attribute of every card in whichever list the dragged card was released in.

$(".js-Sortable").sortable({
    connectWith: ".js-Sortable",
    items: ".js-CardContainer",
    update: function( event, ui ) {
        if (this === ui.item.parent()[0]) {

            var data = $(this).sortable('serialize');

            $.ajax({
                url: "/c/sort",
                type: "POST",
                dataType: "script",
                data: data,
                success: function(resp){
                    console.log('Yay');
                }
            });
        }
    }
});

This sends params which look something like this

Parameters: {"card"=>["39", "2", "1", "6", "40", "5", "18", "3", "16", "7", "17", "8", "15", "9", "10", "11", "12", "13", "14", "4"]}

I'm then updating each affected card's position attribute in my controller action like this:

def sort
    params[:card].each_with_index do |id, index|
        card = Card.find(id)
        card.update_attribute(:position, index) if card
    end

    head :ok
end

The view looks like this:

  <% list.cards.order(:position).where(archived: false).each do |card| %>
    <li class="js-CardContainer" id="card-<%= card.id %>">
      <%= link_to card, class: 'js-Card', :data => { :id => card.id }, remote: true do %>
        <%= card.title %>
      <% end %>

  <% end %>

This is all working so far. The problem is, cards can be moved across different lists. So, I need to somehow get the id of whichever list the dragged card was released in and post that with the AJAX request too.

I can get the list_id as a variable, but how can I add this list_id to the array in the AJAX request?

Body:
as per your question, you are getting cards_id and you want to pass list_id along with it

in your DOM you need to add list_id first

<%= link_to card, class: 'js-Card', :data => { :id => card.id }, remote: true,"data-list-id":list.id do %>
        <span><%= card.title %></span> <% end %>

now you need to fetch this list id in the event handler and combine it with your cards_id params

$(".js-Sortable").sortable({
    connectWith: ".js-Sortable",
    items: ".js-CardContainer",
    update: function( event, ui ) {
        if (this === ui.item.parent()[0]) {
            var data = {}
            var data['cards_id'] = $(this).sortable('serialize');
            var data['list_id'] = $(this).attr("data-list-id")
            $.ajax({
                url: "/c/sort",
                type: "POST",
                dataType: "script",
                data: data,
                success: function(resp){
                    console.log('Yay');
                }
            });
        }
    }
});

in your controller sort action, you need to follow this code

params[:card].each_with_index do |id, index, list_id|
card = Card.find(id)
card.update(:position => index,
:list_id => params[:ListId])
end

Hope it help


问:
Sum of cost IF checkbox is true
I'm making a spreadsheet in Numbers to calculate how much deposit each tenant of a house should get based on who is responsible for particular damages; below is the sheet so far.

In the "Total Bill" column I would like to have a sum of the charges, divided by the number of people involved, for all damages. Formulae I have tried previously are,

```<code>SUMIF(C2:C20,TRUE,B2:B20÷K2:K20)
SUMIF(person, true, cost/split)
</code>```

This does not work however. What should I use instead?

答:
Seems like Numbers can't do math with checkboxes. Just the formula of my comment as an answer:

```<code>=SUM(IF(C2:C20,B2:B20/K2:K20,0))
</code>```

This is an array formula and must be confirmed with ctrl+shift+enter.

Title: Sum of cost IF checkbox is true

Body:
I'm making a spreadsheet in Numbers to calculate how much deposit each tenant of a house should get based on who is responsible for particular damages; below is the sheet so far.

In the "Total Bill" column I would like to have a sum of the charges, divided by the number of people involved, for all damages. Formulae I have tried previously are,

SUMIF(C2:C20,TRUE,B2:B20÷K2:K20)
SUMIF(person, true, cost/split)

This does not work however. What should I use instead?

Body:
Seems like Numbers can't do math with checkboxes. Just the formula of my comment as an answer:

=SUM(IF(C2:C20,B2:B20/K2:K20,0))

This is an array formula and must be confirmed with ctrl+shift+enter.


问:
Is it safe to cast jlong to long?
I'm developing a native plugin for Android with JNI in C++. I want to print out a jlong value, which is defined as a 64-bit value. Is it safe to cast it directly to a long, or are there any platform-specific issues I should be aware of?

```<code>jlong foo = 2;

// This results in the following warning:
// Format specifier '%ld' requires 'long' argument instead of 'jlong'.
printf("%ld", foo);

// This works without a warning.
printf("%ld", (long)foo);
</code>```

答:
No. Yes.

Java, as you have correctly noticed, defines long as a 64 bit number. C++ does not do that long is only guaranteed to be at least as large as int, so it might as well be a 32-bit number.

However, it so happens that given the combination "Android" + "64 bit", indeed long is a 64-bit integer. That's much different from e.g. Windows where it's still just a 32-bit integer.

So, assuming you are writing for 64-bit only, you could stop reading here and now.

But, why the trouble?

C++ borrows the <cstdint> header from C, which defines among others the type int64_t. So you need to use something of which you know is a 64-bit type and you're worried it might not fit?

Well, use a type that is guaranteed to cope with that:

```<code>#include <cstdio>
using my_jlong = int64_t;
</code>```

Title: Is it safe to cast jlong to long?

Body:
I'm developing a native plugin for Android with JNI in C++. I want to print out a jlong value, which is defined as a 64-bit value. Is it safe to cast it directly to a long, or are there any platform-specific issues I should be aware of?

jlong foo = 2;

// This results in the following warning:
// Format specifier '%ld' requires 'long' argument instead of 'jlong'.
printf("%ld", foo);

// This works without a warning.
printf("%ld", (long)foo);

Body:
No. Yes.

Java, as you have correctly noticed, defines long as a 64 bit number. C++ does not do that long is only guaranteed to be at least as large as int, so it might as well be a 32-bit number.

However, it so happens that given the combination "Android" + "64 bit", indeed long is a 64-bit integer. That's much different from e.g. Windows where it's still just a 32-bit integer.

So, assuming you are writing for 64-bit only, you could stop reading here and now.

But, why the trouble?

C++ borrows the <cstdint> header from C, which defines among others the type int64_t. So you need to use something of which you know is a 64-bit type and you're worried it might not fit?

Well, use a type that is guaranteed to cope with that:

#include <cstdio>
using my_jlong = int64_t;


问:
Entity Framework database first: Cannot find the object because it does not exist or you do not have permissions
I'm building a console app in C# which uses Entity Framework to access some tables of plots in an SQL Server database. It looks at a table called ControlTable, sees which plots are missing soil analysis, asynchronously goes to the Plots table and gets those plots' coordinates, then makes an API call, returns soil data and saves it in the PlotSoilChemistry table.

I've added all these tables with Entity Framework Database First, and can see them in an .edmx model.

The code fine, updates everything, and then throws an SqlException:

```<code>System.Data.SqlClient.SqlException: 'Cannot find the object "[dbo.PlotSoilChemistry" because it does not exist or you do not have permissions.'
</code>```

The table exists-I can see it in SSMS and in the .edmx file. I've tried deleting and re-adding the model, and the error does not go away. Suggestions?

答: Found the problem-I'm using "SET IDENTITY_INSERT [dbo].[PlotSoilChemistry] ON" and had an extra square bracket work its way in there. D'oh!</p>

Body:
I'm building a console app in C# which uses Entity Framework to access some tables of plots in an SQL Server database. It looks at a table called ControlTable, sees which plots are missing soil analysis, asynchronously goes to the Plots table and gets those plots' coordinates, then makes an API call, returns soil data and saves it in the PlotSoilChemistry table.

I've added all these tables with Entity Framework Database First, and can see them in an .edmx model.

The code fine, updates everything, and then throws an SqlException:

System.Data.SqlClient.SqlException: 'Cannot find the object "[dbo.PlotSoilChemistry" because it does not exist or you do not have permissions.'

The table exists-I can see it in SSMS and in the .edmx file. I've tried deleting and re-adding the model, and the error does not go away. Suggestions?


问:
Compile views at build time VS2010?

Possible Duplicate:

  ASP.Net MVC - Compiler Errors in Views

I'm using ASP.NET MVC 2 with Visual Studio 2010, and I hate runtime errors.  Compile errors that only happen when I browse that page are almost as bad.

Is there a way I can have my views compile when I hit build?

答: I havent found a way, what i do when working with views is to right click the webserver icon in the task bar (when running) that hosts my web application and then choose to browse the page. I then simply edit my view in visual studio, save it and then update the browser (no compile is required when working in views). Unfortunately this doesnt give breakpoint capabilities since its outside the debugger.</p>

Title: Compile views at build time VS2010?


问:
Updating MongoDB Date in String to Date Format
I am re-asking this question as there seemed to be some misunderstanding.  I need to convert a string in my mongo to a date format using Python.  I have the following code:

```<code>newest_date = datetime.strptime(r["date"], "%Y-%m-%d").isoformat()
</code>```

Which successfully created the following date object (new_date):

```<code>2017-01-03T00:00:00
</code>```

When I try:

```<code>db.address.update_one({"address": "1234", {"$set": {"date" : new_date}})
</code>```

I get the item updated in the document but it's still a string, not a date.  I can successfully do it in the shell using:

```<code>db.address.find({ "date" : { $type : 2 } } ).forEach(function(element){  element.date = ISODate(element.date); db.address.save(element);})
</code>```

How can I update the actual type to be a date because when I do it from the console I get the output:

```<code>"date": {"$date": "2017-06-28T00:00:00.000Z"
</code>```

},

答:
Hopefully this will help someone not make the stupid mistake I made.  Make sure you don't append .isoformat() to a datetime object like a clown...</p>

```<code>newest_date = datetime.strptime(r["date"], "%Y-%m-%d")
</code>```

Body:
I am re-asking this question as there seemed to be some misunderstanding.  I need to convert a string in my mongo to a date format using Python.  I have the following code:

newest_date = datetime.strptime(r["date"], "%Y-%m-%d").isoformat()

Which successfully created the following date object (new_date):

2017-01-03T00:00:00

When I try:

db.address.update_one({"address": "1234", {"$set": {"date" : new_date}})

I get the item updated in the document but it's still a string, not a date.  I can successfully do it in the shell using:

db.address.find({ "date" : { $type : 2 } } ).forEach(function(element){  element.date = ISODate(element.date); db.address.save(element);})

How can I update the actual type to be a date because when I do it from the console I get the output:

"date": {"$date": "2017-06-28T00:00:00.000Z"

},

Body:
Hopefully this will help someone not make the stupid mistake I made.  Make sure you don't append .isoformat() to a datetime object like a clown...

newest_date = datetime.strptime(r["date"], "%Y-%m-%d")


问:
Not getting values from XML with C#
I have a XML like this.

```<code><language code="eng">
  <label lang="tr">İngilizce</label>
  <label lang="en">English</label>
</language>
</code>```

This is example. I have a 402 nodes.

I'm trying to parse this XML file with C# like on the code and I just can get language code values.

Here is the code.

```<code>var languageCode = doc.Root
                          .Elements("language")
                          .Select(x => new XmlModel
                          {
                              Code = (string) x.Attribute("code"),
                          })
                          .ToList();
</code>```

But I need to get label lang="tr" and label lang="en" inner texts (Ingilizce,English) in same code. I didn't do it.

How can I change my code ? Thanks for your helps. :)

EDIT :

```<code> var languageCodeAndValue = doc.Root
                  .Elements("language")
                  .SelectMany(x => x.Elements("label").Select(item => new Tuple<string, string>(item.Attribute("lang").Value, item.Value)))
                  .ToList();
</code>```

This code give me a list like this :

```<code>tr,Turkce
en,Turkish
tr,Ingilizce
en,English
</code>```

But I need

```<code>tur,tr,Turkce
tur,en,Turkish
eng,tr,Ingilizce
eng,en,English
</code>```

答:
If I right understood you, just try this:

```<code>var languageCodeAndValue = doc.Root
                      .Elements("language")
                      .SelectMany(x => x.Elements("label").Select(item => new Tuple<string, string, string>(x.Attribute("code").Value, item.Attribute("lang").Value, item.Value)))
                      .ToList();
</code>```

Your languageCodeAndValue would be contain a language code, it attribute and text: ("eng", "tr", "İngilizce"), ("eng", "en", "English")

And retrive values:

```<code>foreach (var value in languageCodeAndValue)
{
    Console.WriteLine(value.Item1);
    Console.WriteLine(value.Item2);
    Console.WriteLine(value.Item3);
}
</code>```

Title: Not getting values from XML with C#

Body:
I have a XML like this.

<language code="eng">
  İngilizce
  English
</language>

This is example. I have a 402 nodes.

I'm trying to parse this XML file with C# like on the code and I just can get language code values.

Here is the code.

var languageCode = doc.Root
                          .Elements("language")
                          .Select(x => new XmlModel
                          {
                              Code = (string) x.Attribute("code"),
                          })
                          .ToList();

But I need to get label lang="tr" and label lang="en" inner texts (Ingilizce,English) in same code. I didn't do it.

How can I change my code ? Thanks for your helps. :)

EDIT :

 var languageCodeAndValue = doc.Root
                  .Elements("language")
                  .SelectMany(x => x.Elements("label").Select(item => new Tuple<string, string>(item.Attribute("lang").Value, item.Value)))
                  .ToList();

This code give me a list like this :

tr,Turkce
en,Turkish
tr,Ingilizce
en,English

But I need

tur,tr,Turkce
tur,en,Turkish
eng,tr,Ingilizce
eng,en,English

Body:
If I right understood you, just try this:

var languageCodeAndValue = doc.Root
                      .Elements("language")
                      .SelectMany(x => x.Elements("label").Select(item => new Tuple<string, string, string>(x.Attribute("code").Value, item.Attribute("lang").Value, item.Value)))
                      .ToList();

Your languageCodeAndValue would be contain a language code, it attribute and text: ("eng", "tr", "İngilizce"), ("eng", "en", "English")

And retrive values:

foreach (var value in languageCodeAndValue)
{
    Console.WriteLine(value.Item1);
    Console.WriteLine(value.Item2);
    Console.WriteLine(value.Item3);
}


问:
Send UIImage to LocalwebServer using GCDWebServer
My app using GCDWebServer I get a photo from my iPhone album by using AssetsLibrary and I store them in NSDocumentDirectory. I just want to get access Url to this photo to show them in a web page.

There is my code :

```<code>[_webServer addHandlerForMethod:@"POST"
                              path:@"/"
                      requestClass:[GCDWebServerURLEncodedFormRequest class]
                      processBlock:^GCDWebServerResponse *(GCDWebServerRequest* request) {

                          ALAsset *asset = [self.arrayPictures objectAtIndex:0];
                          ALAssetRepresentation *rep = [asset defaultRepresentation];
                          CGImageRef iref = [rep fullResolutionImage];
                          UIImage *thumbnail = [UIImage imageWithCGImage:iref];
                          NSString* path ;
                          if (thumbnail != nil)
                          {
                              NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
                              NSString *documentsDirectory = [paths objectAtIndex:0];
                               path =  [[NSString alloc] initWithString:[documentsDirectory stringByAppendingPathComponent:@"test.png"]];
                              NSData* data = UIImagePNGRepresentation(thumbnail);
                              [data writeToFile:path atomically:YES];
                          }

                          NSURL *url = [NSURL fileURLWithPath:path];
                          NSString* html = [NSString stringWithFormat:@"<html><body><img src=\"%@\" width=\"400\" height=\"500\"/></body></html>", url];
                          return [GCDWebServerDataResponse responseWithHTML:html];

                      }];
</code>```

答:
You can create one GET request which will return all custom URLs of the photo assets.

After that create one handler of that custom URLs which will return requested URL image Data.

In a custom URL handler use below code

```<code>//Get PHAsset image name with extionsion.
let filename = NSURL(string: (asset as! PHAsset).originalFilename!)

// Retrive image data from PHAsset object
PHImageManager.default().requestImageData(for: asset as! PHAsset, options: nil, resultHandler: { (imageData, str, nil, info) in

    //Check imageData is nil or not.
    if (imageData) {

        //Return image Data with contentType
        let imageDatas = UIImagePNGRepresentation(imageData)

        completionBlock!(GCDWebServerDataResponse(data: imageDatas, contentType: "image/\((filename?.pathExtension)!)"))
    } else {

        // Image retrive error message return.
        let jsonResponse = ["type":"failed","Message":"Image not avilable."] as [String : Any]
        completionBlock!(GCDWebServerDataResponse(jsonObject: jsonResponse))
    }
})

// MARK:- Get File name from PHAsset.
extension PHAsset {

    var originalFilename: String? {

        var fname:String?

        if #available(iOS 9.0, *) {
            let resources = PHAssetResource.assetResources(for: self)
            if let resource = resources.first {
                fname = resource.originalFilename
            }
        }

        if fname == nil {
            // this is an undocumented workaround that works as of iOS 9.1
            fname = self.value(forKey: "filename") as? String
        }

        return fname
    }
}
</code>```

Body:
My app using GCDWebServer I get a photo from my iPhone album by using AssetsLibrary and I store them in NSDocumentDirectory. I just want to get access Url to this photo to show them in a web page.

There is my code :

[_webServer addHandlerForMethod:@"POST"
                              path:@"/"
                      requestClass:[GCDWebServerURLEncodedFormRequest class]
                      processBlock:^GCDWebServerResponse *(GCDWebServerRequest* request) {

                          ALAsset *asset = [self.arrayPictures objectAtIndex:0];
                          ALAssetRepresentation *rep = [asset defaultRepresentation];
                          CGImageRef iref = [rep fullResolutionImage];
                          UIImage *thumbnail = [UIImage imageWithCGImage:iref];
                          NSString* path ;
                          if (thumbnail != nil)
                          {
                              NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
                              NSString *documentsDirectory = [paths objectAtIndex:0];
                               path =  [[NSString alloc] initWithString:[documentsDirectory stringByAppendingPathComponent:@"test.png"]];
                              NSData* data = UIImagePNGRepresentation(thumbnail);
                              [data writeToFile:path atomically:YES];
                          }

                          NSURL *url = [NSURL fileURLWithPath:path];
                          NSString* html = [NSString stringWithFormat:@"", url];
                          return [GCDWebServerDataResponse responseWithHTML:html];

                      }];

Body:
You can create one GET request which will return all custom URLs of the photo assets.

After that create one handler of that custom URLs which will return requested URL image Data.

In a custom URL handler use below code

//Get PHAsset image name with extionsion.
let filename = NSURL(string: (asset as! PHAsset).originalFilename!)

// Retrive image data from PHAsset object
PHImageManager.default().requestImageData(for: asset as! PHAsset, options: nil, resultHandler: { (imageData, str, nil, info) in

    //Check imageData is nil or not.
    if (imageData) {

        //Return image Data with contentType
        let imageDatas = UIImagePNGRepresentation(imageData)

        completionBlock!(GCDWebServerDataResponse(data: imageDatas, contentType: "image/\((filename?.pathExtension)!)"))
    } else {

        // Image retrive error message return.
        let jsonResponse = ["type":"failed","Message":"Image not avilable."] as [String : Any]
        completionBlock!(GCDWebServerDataResponse(jsonObject: jsonResponse))
    }
})

// MARK:- Get File name from PHAsset.
extension PHAsset {

    var originalFilename: String? {

        var fname:String?

        if #available(iOS 9.0, *) {
            let resources = PHAssetResource.assetResources(for: self)
            if let resource = resources.first {
                fname = resource.originalFilename
            }
        }

        if fname == nil {
            // this is an undocumented workaround that works as of iOS 9.1
            fname = self.value(forKey: "filename") as? String
        }

        return fname
    }
}


问:
MacOS App Runs in Debug and Release in Xcode, but not Standalone
I've been working on my apps for months and never had problem get it to run in debug. When I went to create my first release, I get this error:

```<code>Library not loaded: @rpath/MacOSGlues.framework/Versions/A/MacOSGlues
Referenced from: /Users/USER/Library/Developer/Xcode/DerivedData/JazzCat-ffbfdfrcekhzjacupibevqyrfyoh/Build/Products/Debug/jazzcat.app/Contents/MacOS/jazzcat
Reason: image not found
</code>```

I'm doing the build in a workspace that also contains another module. The error references one of the files in that module.

To build the release version, I edited the scheme and changed "Build Configuration" to release. I located the app in Finder and ran it to get the error. If I press Cmd R in xcode, the release version runs fine. It's only when I try to run it directly (i.e., outside of Xcode).

Is there a parallel set up that I have to do for release that includes some or all that is set up for debug? I would have thought this would have been a common problem and there would already be an answer. I couldn't find one. This is a snap shot of the workspace in Xcode. I assuming the files are red because they aren't under version control whereas the bulk of the project is.

There are no entries in the "Target Dependencies" in the "Build Phases". When I attempt to add one, my only choices are the source code files in my own project.

The SwiftAE project is source code.

Under jazzcat/Build Settings/Search Paths/Framework Search Paths nothing is set for debug, which works, or release.

答:
Library not loaded mostly occurs when Library Dependency is not configured properly. First, the libraries should be built either by manual building or the better way by dependency configuration. That way the library will be built automatically.

Adding Frameworks should be configured in Embedded Binaries section

@curt: I hope you don't mind that I relinked your screenshot.

Body:
I've been working on my apps for months and never had problem get it to run in debug. When I went to create my first release, I get this error:

Library not loaded: @rpath/MacOSGlues.framework/Versions/A/MacOSGlues
Referenced from: /Users/USER/Library/Developer/Xcode/DerivedData/JazzCat-ffbfdfrcekhzjacupibevqyrfyoh/Build/Products/Debug/jazzcat.app/Contents/MacOS/jazzcat
Reason: image not found

I'm doing the build in a workspace that also contains another module. The error references one of the files in that module.

To build the release version, I edited the scheme and changed "Build Configuration" to release. I located the app in Finder and ran it to get the error. If I press Cmd R in xcode, the release version runs fine. It's only when I try to run it directly (i.e., outside of Xcode).

Is there a parallel set up that I have to do for release that includes some or all that is set up for debug? I would have thought this would have been a common problem and there would already be an answer. I couldn't find one. This is a snap shot of the workspace in Xcode. I assuming the files are red because they aren't under version control whereas the bulk of the project is.

There are no entries in the "Target Dependencies" in the "Build Phases". When I attempt to add one, my only choices are the source code files in my own project.

The SwiftAE project is source code.

Under jazzcat/Build Settings/Search Paths/Framework Search Paths nothing is set for debug, which works, or release.


问:
Create a common library in Play framework
I created 3 subprojects in play: A,B, and common

A and B needs to use common subproject.
the code looks like this for the build.sbt:

```<code>name := """play"""
organization := "com.play"

version := "1.0-SNAPSHOT"

lazy val common = (project in file("modules/common")).enablePlugins(PlayScala)

lazy val A = (project in file("modules/A")).enablePlugins(PlayScala)
 .dependsOn(common).aggregate(common)
lazy val B= (project in file("modules/B")).enablePlugins(PlayScala)
                .dependsOn(common).aggregate(common)

lazy val root = (project in file(".")).enablePlugins(PlayScala)
            .dependsOn(A).aggregate(A)
            .dependsOn(B).aggregate(B)

scalaVersion := "2.11.11"

libraryDependencies += filters
libraryDependencies += evolutions
libraryDependencies += "org.scalatestplus.play" %% "scalatestplus-play" % "2.0.0" % Test
</code>```

The package system, I follow the documentation in the Play framework which is like "package.moduleName"
So, the class in model package in my common subproject has a package name called: "model.common"

Now in subproject A, i want to call the library in the common subproject

I call like this:

```<code>import model.common.className
</code>```

I cannot find it

答:
You can put all the classes inside a top level package.
For example for the common project you can put all the classes inside the com.play.common package.

After that you can use the class example(declare in the common project) from the project A using import com.play.common.A.

Body:
I created 3 subprojects in play: A,B, and common

A and B needs to use common subproject.
the code looks like this for the build.sbt:

name := """play"""
organization := "com.play"

version := "1.0-SNAPSHOT"

lazy val common = (project in file("modules/common")).enablePlugins(PlayScala)

lazy val A = (project in file("modules/A")).enablePlugins(PlayScala)
 .dependsOn(common).aggregate(common)
lazy val B= (project in file("modules/B")).enablePlugins(PlayScala)
                .dependsOn(common).aggregate(common)

lazy val root = (project in file(".")).enablePlugins(PlayScala)
            .dependsOn(A).aggregate(A)
            .dependsOn(B).aggregate(B)

scalaVersion := "2.11.11"

libraryDependencies += filters
libraryDependencies += evolutions
libraryDependencies += "org.scalatestplus.play" %% "scalatestplus-play" % "2.0.0" % Test

The package system, I follow the documentation in the Play framework which is like "package.moduleName"
So, the class in model package in my common subproject has a package name called: "model.common"

Now in subproject A, i want to call the library in the common subproject

I call like this:

import model.common.className

I cannot find it


问:
Trying out [[nodiscard]] with no success
I am trying to test a little C++17. I am trying to do:

```<code>[[nodiscard]] int get_value1()
{
    return 42;
}

inline void start()
{
    // Should generate warning
    get_value1();
}
</code>```

However, it does not. I am using Visual studio 2017. Warning level set to Level4(\W4). I have set C++ Language Standard to ISO C++ Latest Draft Standard (/std:c++latest).

But it does not generate the warning that I want. Why is that? Also, a little side question: That tab to select the language standard only appears in Debug configuration and not Release. Why is that? Release complains on the nodiscard, Would that mean that Release is in C++14?

edit: naturally I meant warning in the second section. Corrected. :)

答: Actually [[nodiscard]] is supported only since VS 2017.3 and it should give you a warning, not an error. And as I understand specification assumes that compiler may warn you. And may not.

Body:
I am trying to test a little C++17. I am trying to do:

[[nodiscard]] int get_value1()
{
    return 42;
}

inline void start()
{
    // Should generate warning
    get_value1();
}

However, it does not. I am using Visual studio 2017. Warning level set to Level4(\W4). I have set C++ Language Standard to ISO C++ Latest Draft Standard (/std:c++latest).

But it does not generate the warning that I want. Why is that? Also, a little side question: That tab to select the language standard only appears in Debug configuration and not Release. Why is that? Release complains on the nodiscard, Would that mean that Release is in C++14?

edit: naturally I meant warning in the second section. Corrected. :)


问:
change the image doesnt work
here is my javasript:

```<code>$(function() {
    $(".image2").click(function() {
        var image = $(this).attr("rel");
        $('#random_img').hide();
        $('#random_img').fadeIn('slow');
        $('#random_img').attr('src') == image;
        var image2 = $('#random_img').attr('src');
        $("#thumb2 a img").removeClass("open");
        $("#thumb2 a[rel='" + image2 + "'] img").addClass("open");
        return false;
    });
});
</code>```

here is my html:

```<code><div id="image2">
    <img id="random_img" src="/documents/templates/projedepo/banner/indigovision.jpg" height="420" width="964" />
</div>
<div id="thumb2">
    <a href="#" rel="/documents/templates/projedepo/banner/canon.jpg" class="image2">
        <img title="Canon" class="slider_thumb" src="/documents/templates/bilgiteknolojileri/images/t_flash/t1.png" border="0"/></a>
    <a href="#" rel="/documents/templates/projedepo/banner/indigovision.jpg" class="image2">
        <img title="IndigoVision" class="slider_thumb" src="/documents/templates/bilgiteknolojileri/images/t_flash/t2.png" border="0"/>
    </a>
</div>
</code>```

when i click on a thumbnail, the animation fadeIn and hide works, but the image is not changed...why?

答:
Check http://api.jquery.com/attr/

Also, you are using equality operator == where you may usually use assignment operator =. This won't work with .attr method though..

Title: change the image doesnt work

Body:
here is my javasript:

$(function() {
    $(".image2").click(function() {
        var image = $(this).attr("rel");
        $('#random_img').hide();
        $('#random_img').fadeIn('slow');
        $('#random_img').attr('src') == image;
        var image2 = $('#random_img').attr('src');
        $("#thumb2 a img").removeClass("open");
        $("#thumb2 a[rel='" + image2 + "'] img").addClass("open");
        return false;
    });
});

here is my html:

when i click on a thumbnail, the animation fadeIn and hide works, but the image is not changed...why?


问:
How to remove padding and margin from my html content?

I have tried :

```<code>body{
     margin:0px;
     padiing:0px
}
</code>```

and also

```<code>*{
   margin:0px;
   padiing:0px
 }
</code>```

Please give some other solution

答:
There could be a few things causing this to not work.

You are missing a semi-colon at the end of each padding property.

You are spelling padding wrong. It should be padding: 0px;

Make sure you are referencing your css file in your head tag as such <link rel="stylesheet" href="path to css file here">

Body:
I have tried :

body{
     margin:0px;
     padiing:0px
}

and also

*{
   margin:0px;
   padiing:0px
 }

Please give some other solution