问:
Laravel multiple PDF to ZIP
I am making an external API call which returns several objects with download URL inside. Those are all PDF-s of which I would like to provide a single ZIP download link.

The way it works now is that I am downloading every single PDF to a specific user folder, and then making a ZIP out of it and presenting it back to user.

I see this as a somewhat slow and inefficient of doing things as the user will have to trigger another download for the ZIP, and this way I am making user wait basically for 2 downloads of the same file batch.

Is there a smarter way to deal with this?

```<code>$path = '/user_downloads/' . Auth::user()->id . '/';

if (!Storage::disk('uploads')->has($path)) {
    Storage::disk('uploads')->makeDirectory($path);
}

$zipper = new \Chumper\Zipper\Zipper;
$zip_filename = 'zipped/' . uniqid() . '_merged.zip';
foreach (json_decode($res)->hits as $hit) {
    $filename = public_path() . $path . uniqid() . '_file.pdf';
    copy($hit->document_download_link, $filename);
    $zipper->make($zip_filename)->add($filename);
}
</code>```

答:
This question has a couple of ways you could present the files to the user on by one but this is less user friendly and might get blocked by browsers.

You could probably also use JSZip (haven't looked too closely at it) but that would use the browser's RAM to compress the PDF's which is not ideal, especially on mobile devices.

I think your current solution is the best one.

Title: Laravel multiple PDF to ZIP

Body:
I am making an external API call which returns several objects with download URL inside. Those are all PDF-s of which I would like to provide a single ZIP download link.

The way it works now is that I am downloading every single PDF to a specific user folder, and then making a ZIP out of it and presenting it back to user.

I see this as a somewhat slow and inefficient of doing things as the user will have to trigger another download for the ZIP, and this way I am making user wait basically for 2 downloads of the same file batch.

Is there a smarter way to deal with this?

$path = '/user_downloads/' . Auth::user()->id . '/';

if (!Storage::disk('uploads')->has($path)) {
    Storage::disk('uploads')->makeDirectory($path);
}

$zipper = new \Chumper\Zipper\Zipper;
$zip_filename = 'zipped/' . uniqid() . '_merged.zip';
foreach (json_decode($res)->hits as $hit) {
    $filename = public_path() . $path . uniqid() . '_file.pdf';
    copy($hit->document_download_link, $filename);
    $zipper->make($zip_filename)->add($filename);
}


来源: stackexchange

问:
How do I filter a stream of integers into a list?
I am trying to process a stream of Integers and collect the integers that match a predicate (via the compare() function) into a list. Here's a rough outline of the code I've written.

```<code>private List<Integer> process() {
    Z z = f(-1);
    return IntStream.range(0, 10)
        .filter(i -> compare(z, f(i)))
        .collect(Collectors.toCollection(ArrayList::new)); // Error on this line
}

private boolean compare(Z z1, Z z2) { ... }
private Z f(int i) { ... }
</code>```

Unfortunately my solution does not compile and I cannot make sense of the compiler error for the line highlighted:

The method collect(Supplier<R>, ObjIntConsumer<R>, BiConsumer<R,R>) in the type IntStream is not applicable for the arguments (Collector<Object,capture#1-of ?,Collection<Object>>)

Any suggestions?

答:
Or you can specify the Supplier, Accumulator and Combiner yourself:

```<code> IntStream.range(0, 10)
            .filter(i -> compare(z, f(i)))
            .collect(ArrayList::new, ArrayList::add, ArrayList::addAll);
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I am trying to process a stream of Integers and collect the integers that match a predicate (via the compare() function) into a list. Here's a rough outline of the code I've written.

private List<Integer> process() {
    Z z = f(-1);
    return IntStream.range(0, 10)
        .filter(i -> compare(z, f(i)))
        .collect(Collectors.toCollection(ArrayList::new)); // Error on this line
}

private boolean compare(Z z1, Z z2) { ... }
private Z f(int i) { ... }

Unfortunately my solution does not compile and I cannot make sense of the compiler error for the line highlighted:

The method collect(Supplier<R>, ObjIntConsumer<R>, BiConsumer<R,R>) in the type IntStream is not applicable for the arguments (Collector<Object,capture#1-of ?,Collection<Object>>)

Any suggestions?

Body:
Or you can specify the Supplier, Accumulator and Combiner yourself:

 IntStream.range(0, 10)
            .filter(i -> compare(z, f(i)))
            .collect(ArrayList::new, ArrayList::add, ArrayList::addAll);


问:
Center form content vertically
I've got the following landing page form (I've cut all the unnecessary stuff I don't think matters leaving only minimum of style). Here is the code (I'm using Bootstrap 3.3.5):

```<code><div class="col-md-6 app-door">
  <form class="image-hover text-center">
    <h3>Application name</h3>
    <div class="landing-page-form-group">
      <label class="landing-page-label">Label: </label>
      <input class="form-control landing-page-input">
    </div>
    <button class="btn">Submit</button>
  </form>
  <div class="center-block app-link some-img"/>
</div>
</code>```

..and css

```<code>.image-hover {
  width: 300px;
  height: 300px;
  background-color: rgba(0, 0, 0, 0.7) !important;
  position: absolute;
  z-index: 100;
  color: #cccccc;
  margin: 0 auto;
  left: 0;
  right: 0;
  border-radius: 25px;
}

.landing-page-form-group {
  padding-top: 16px;
  padding-bottom: 16px;
}

.landing-page-label {
  width: 100px;
  vertical-align: middle;
}

.landing-page-input {
  width: 150px;
  display: inline-block;
}

.app-link {
  width: 300px;
  height: 300px;
  background-size: 100% 100%;
  border-radius: 25px;
}

.some-img {
  background-image: url("http://dl.hiapphere.com/data/icon/201511/HiAppHere_com_com.ludicside.mrsquare.png");
}
</code>```

I want to center all the form inputs and etc vertically. I've tried such things as playing with position (relative on parent, absolute on child), vertical-align, top, maybe something else I don't remember right now as I spent lots of hours trying.

I'm not a great specialist in frontend development (I mean html/css) so I will be extremely happy to see understanding although the problem seems to be basic enough.

Thank you for any ideas!

答:
updated
 check the solution without flex demo here

Try this

check demo here

add the following styles to your existing .image-hover class

CSS:

```<code>.image-hover {
    align-items: center;
    display: flex;
    flex-direction: column;
    justify-content: center;
}
</code>```

Title: Center form content vertically

Body:
I've got the following landing page form (I've cut all the unnecessary stuff I don't think matters leaving only minimum of style). Here is the code (I'm using Bootstrap 3.3.5):

  <form class="image-hover text-center">

Application name

      Label:
      <input class="form-control landing-page-input">

    <button class="btn">Submit</button>
  </form>

..and css

.image-hover {
  width: 300px;
  height: 300px;
  background-color: rgba(0, 0, 0, 0.7) !important;
  position: absolute;
  z-index: 100;
  color: #cccccc;
  margin: 0 auto;
  left: 0;
  right: 0;
  border-radius: 25px;
}

.landing-page-form-group {
  padding-top: 16px;
  padding-bottom: 16px;
}

.landing-page-label {
  width: 100px;
  vertical-align: middle;
}

.landing-page-input {
  width: 150px;
  display: inline-block;
}

.app-link {
  width: 300px;
  height: 300px;
  background-size: 100% 100%;
  border-radius: 25px;
}

.some-img {
  background-image: url("http://dl.hiapphere.com/data/icon/201511/HiAppHere_com_com.ludicside.mrsquare.png");
}

I want to center all the form inputs and etc vertically. I've tried such things as playing with position (relative on parent, absolute on child), vertical-align, top, maybe something else I don't remember right now as I spent lots of hours trying.

I'm not a great specialist in frontend development (I mean html/css) so I will be extremely happy to see understanding although the problem seems to be basic enough.

Thank you for any ideas!

Body:
updated
 check the solution without flex demo here

Try this

check demo here

add the following styles to your existing .image-hover class

CSS:

.image-hover {
    align-items: center;
    display: flex;
    flex-direction: column;
    justify-content: center;
}


问:
NHibernate ID Private Setter (any workaround)
Here is a "simplified" class that can be mapped using NHibernate;

```<code>public class Template
{
  public virtual int Id { get; private set; }
  public virtual string Name { get; set; }
}
</code>```

As the ID field has a private setter we can no longer have code like this in our application where we manually set the ID field;

```<code>var DefaultTemplate = new Template { ID = (int)TemplateEnum.Default, Name = "Default" }
</code>```

Here we are manually creating a DefaultTemplate object that we can assign to anything. Other Templates are manually created by users and saved to the database.

Any ideas how we can still achieve this kind of functionality?

Please note: C# Winforms, .NET 3.5 and we don't want to use Reflection for this.

答:
I would do it like this, if feasible:

```<code>public class Template
{
  public virtual int Id { get; private set; }
  public virtual string Name { get; set; }

  public static readonly Template Default = new Template() {ID = (int)TemplateEnum.Default, Name = "Default"};
}
</code>```

Then, you can always 'get' the default template, without having to instantiate it from the outside of the Template class:

```<code>Template t = Template.Default;
</code>```

ContentLicense: CC BY-SA 2.5

Body:
Here is a "simplified" class that can be mapped using NHibernate;

public class Template
{
  public virtual int Id { get; private set; }
  public virtual string Name { get; set; }
}

As the ID field has a private setter we can no longer have code like this in our application where we manually set the ID field;

var DefaultTemplate = new Template { ID = (int)TemplateEnum.Default, Name = "Default" }

Here we are manually creating a DefaultTemplate object that we can assign to anything. Other Templates are manually created by users and saved to the database.

Any ideas how we can still achieve this kind of functionality?

Please note: C# Winforms, .NET 3.5 and we don't want to use Reflection for this.

Body:
I would do it like this, if feasible:

public class Template
{
  public virtual int Id { get; private set; }
  public virtual string Name { get; set; }

  public static readonly Template Default = new Template() {ID = (int)TemplateEnum.Default, Name = "Default"};
}

Then, you can always 'get' the default template, without having to instantiate it from the outside of the Template class:

Template t = Template.Default;


问:
Is there a way I can get an Enum value by its number in the sequence?
I have this enum:

```<code>public enum PTI
{
    UserInput = 0,
    Five = 5,
    Ten = 10,
    Fifteen = 15
}

public static partial class Extensions
{
    public static string Text(this PTI time)
    {
        switch (time)
        {
            case PTI.UserInput: return "User Input";
            case PTI.Ten: return "10 seconds";
            case PTI.Five: return "5 seconds";
            case PTI.Fifteen: return "15 seconds";
        }
        return "";
    }
}
</code>```

It's a simple case but I am using it as an example. In my code I need to pass the value of the enum to a function so I came up with this:

```<code>if (selectedIndex == 1) App.DB.UpdateSetting(Settings.Pti, PTI.UserInput);
if (selectedIndex == 2) App.DB.UpdateSetting(Settings.Pti, PTI.Five);
if (selectedIndex == 3) App.DB.UpdateSetting(Settings.Pti, PTI.Ten);
if (selectedIndex == 4) App.DB.UpdateSetting(Settings.Pti, PTI.Fifteen);
</code>```

It's not ideal.  Maybe a Case would help here but my point is that all I get is a number from 1 to 4 and from this I need to get the ENUM value.

Is there some way that I could get the ENUM value from the value of selectedIndex without an if or case construct?

Background - Here's where the value of selectedIndex comes from. It's from a picker in a Xamarin Form XAML

```<code><Picker x:Name="ptiPicker" IsVisible="false" SelectedIndexChanged="ptiOnPickerSelectedIndexChanged">
                                            <Picker.Items>
                                                <x:String>User input</x:String>
                                                <x:String>5 seconds</x:String>
                                                <x:String>10 seconds</x:String>
                                                <x:String>15 seconds</x:String>
                                            </Picker.Items>
                                        </Picker>
</code>```

Note:

If it was possible I would be happy to add some extension method to the enum if that would help get what I needed. Just not sure how to do that.

答:
You can try to convert it as an integer to get the value.

Convert.ToInt32(PTI.Fifteen)

Picker items are in a form of string so what you can do is to get the text of the selected index of your picker and parse it to only get the number from item.

```<code>picker.Items [picker.SelectedIndex];
</code>```

e.g.

```<code>var selectedValue = "15 seconds"; //this will be your selected value in picker
var splitx = selectedValue.Split(' ');

Console.WriteLine(Convert.ToInt32(PTI.Fifteen));

if (Convert.ToInt32(splitx[0]) == Convert.ToInt32(PTI.Fifteen))
{
    Console.WriteLine("selected value is - 15 seconds");
}
</code>```

You can also try to do a Dictionary like in the Xamarin example here

Hope this helps you...

Body:
I have this enum:

public enum PTI
{
    UserInput = 0,
    Five = 5,
    Ten = 10,
    Fifteen = 15
}

public static partial class Extensions
{
    public static string Text(this PTI time)
    {
        switch (time)
        {
            case PTI.UserInput: return "User Input";
            case PTI.Ten: return "10 seconds";
            case PTI.Five: return "5 seconds";
            case PTI.Fifteen: return "15 seconds";
        }
        return "";
    }
}

It's a simple case but I am using it as an example. In my code I need to pass the value of the enum to a function so I came up with this:

if (selectedIndex == 1) App.DB.UpdateSetting(Settings.Pti, PTI.UserInput);
if (selectedIndex == 2) App.DB.UpdateSetting(Settings.Pti, PTI.Five);
if (selectedIndex == 3) App.DB.UpdateSetting(Settings.Pti, PTI.Ten);
if (selectedIndex == 4) App.DB.UpdateSetting(Settings.Pti, PTI.Fifteen);

It's not ideal.  Maybe a Case would help here but my point is that all I get is a number from 1 to 4 and from this I need to get the ENUM value.

Is there some way that I could get the ENUM value from the value of selectedIndex without an if or case construct?

Background - Here's where the value of selectedIndex comes from. It's from a picker in a Xamarin Form XAML

<Picker x:Name="ptiPicker" IsVisible="false" SelectedIndexChanged="ptiOnPickerSelectedIndexChanged">
                                            <Picker.Items>
                                                <x:String>User input</x:String>
                                                <x:String>5 seconds</x:String>
                                                <x:String>10 seconds</x:String>
                                                <x:String>15 seconds</x:String>
                                            </Picker.Items>
                                        </Picker>

Note:

If it was possible I would be happy to add some extension method to the enum if that would help get what I needed. Just not sure how to do that.

Body:
You can try to convert it as an integer to get the value.

Convert.ToInt32(PTI.Fifteen)

Picker items are in a form of string so what you can do is to get the text of the selected index of your picker and parse it to only get the number from item.

picker.Items [picker.SelectedIndex];

e.g.

var selectedValue = "15 seconds"; //this will be your selected value in picker
var splitx = selectedValue.Split(' ');

Console.WriteLine(Convert.ToInt32(PTI.Fifteen));

if (Convert.ToInt32(splitx[0]) == Convert.ToInt32(PTI.Fifteen))
{
    Console.WriteLine("selected value is - 15 seconds");
}

You can also try to do a Dictionary like in the Xamarin example here

Hope this helps you...


答:
Simplest method would be to use

```<code>.image-hover {
    display: flex;
    align-items : center;
    justify-content: center;
}
</code>```

The align-items takes care of vertical centering, and justify-contents, the horizontal centering.

Title: Center form content vertically

Body:
Simplest method would be to use

.image-hover {
    display: flex;
    align-items : center;
    justify-content: center;
}

The align-items takes care of vertical centering, and justify-contents, the horizontal centering.


问:
Prevent Serialization of parent class Java
Is there a way where I can prevent the parent class to be serialized?

When we do a serialization of the subclass all the way up till the parent class the serialization is performed.

Can I restrict the serialization of the parent classes and serialize the only sub class I am working on?

答:
It is possible. Just declare your class as implements Externalizable and write exactly what you need in the writeExternal() method, taking care not to serialize anything from the superclass, and read exactly that back in the readExternal() method.

Or, just implement Serializable and provide your own readObject()/writeObject() methods, again taking care not to serialize anything from the superclass, and in this case also not calling defaultWriteObject() or defaultReadObject().

In both cases the actual serialization of the current class's data is entirely up to you.


问:
How to add new QEMU machine types without modifying the mainline source code?
Can a new machine type be added for qemu-system-arm -M <MachineType> without having to recompile qemu or write code? Are there docs to do this? I would like to be able to emulate raspberry pi and pandaboard using qemu.

I know that meego's fork of qemu supports pandaboard, but I am trying to stick with the main stream qemu that I can manage from the apt-get package manager. the main stream qemu now supports beagleboard rev C and beagleboard xm that were previously supported only in the meego fork.

答:
I've been able to emulate the Pi with -M versatilepb: https://raspberrypi.stackexchange.com/questions/165/emulation-on-a-linux-pc/53991#53991 and -M raspi2 has was later added in QEMU 2.6.

Maybe this feature is feasible to implement, see my experience with adding a new platform device: How to add a new device in QEMU source code?

There, I only needed to add a single line to attach a new device to versatilepb:

```<code>sysbus_create_simple("lkmc_platform_device", 0x101e9000, pic[18]);
</code>```

so maybe we could have a config file containing lines of type:

```<code>type    name                  regid        irq
sysbus  lkmc_platform_device  0x101e9000   18
</code>```

Related: out-of-tree devices: How to create out-of-tree QEMU devices?

Body:
I've been able to emulate the Pi with -M versatilepb: https://raspberrypi.stackexchange.com/questions/165/emulation-on-a-linux-pc/53991#53991 and -M raspi2 has was later added in QEMU 2.6.

Maybe this feature is feasible to implement, see my experience with adding a new platform device: How to add a new device in QEMU source code?

There, I only needed to add a single line to attach a new device to versatilepb:

sysbus_create_simple("lkmc_platform_device", 0x101e9000, pic[18]);

so maybe we could have a config file containing lines of type:

type    name                  regid        irq
sysbus  lkmc_platform_device  0x101e9000   18

Related: out-of-tree devices: How to create out-of-tree QEMU devices?


问:
No matching client found for package name 'com.google.firebase.udacity.friendlychat'
I'm getting an error about my android project,
enter code herehere the error :

Error:Execution failed for task ':app:processDebugGoogleServices'. > No matching client found for package name 'com.google.firebase.udacity.friendlychat'

答: If you are downloading the code from firebase. Make sure that all the dependencies and filenames are correct. Like your filename should be same as the downloaded filename. </p>


问:
PHP - String gets chopped after nbsp character
I'm having a hard time using a combination of TinyMCE, Ajax and PHP Post to an ExpressionEngine database. The TinyMCE area collects the data from my database when the website loads, and I can edit it with rich text.

However, when I save these changes using ajax and POST to PHP, the string gets chopped off whenever the string contains  . I haven't tried any other special characters, but it accepts
 and

PHP code looks like this:

```<code>$tinyMCEData = $_POST['tinyMCEData'];
</code>```

And when I echo this out, it's chopped off at this point. I've tried to replace the nbsp before it's sent off via Ajax, but I've no luck yet. I don't really care if there's a nbsp in there either, as long as it's accepted.

I've also tried htmlentities, like this:

```<code>$tinyMCEData = htmlentities($_POST['tinyMCEData']);
</code>```

No luck there either. So why is this happening? I'm guessing there's a reason for this. Any help much appreciated!

Edit: My case looks exactly like the example from this question:
TinyMCE + Jquery + PHP + AJAX Special chars issue

Only the bottom two screenshots of the alert boxes. All I have in my tinyMCE editor are more than once space in the text.

Edit2: Here's what the javascript looks like:

```<code>var tinyMCEData = tinyMCE.activeEditor.getContent();
var pars = 'tinyMCEData=' + tinyMCEData;

var myAjax = new Ajax.Request(url, {
   method: 'post',
   postBody: 'pars,
   onSuccess: success,
   onFailure: failure
});
</code>```

At this point, the data that's being sent looks like this for example:

```<code><p>One two  three   four</p>
</code>```

What the value is after php post:

```<code><p>One two
</code>```

答:
Another solution for those who still have an issue with this (And especially if you want to submit more details)...

I separated the text data from the other variables instead of using a datastring. Then make sure one of the variables contains your text

```<code>data: {var1: var1,
       var2: var2,
       var3: var3}
</code>```

Body:
I'm having a hard time using a combination of TinyMCE, Ajax and PHP Post to an ExpressionEngine database. The TinyMCE area collects the data from my database when the website loads, and I can edit it with rich text.

However, when I save these changes using ajax and POST to PHP, the string gets chopped off whenever the string contains  . I haven't tried any other special characters, but it accepts
 and

PHP code looks like this:

$tinyMCEData = $_POST['tinyMCEData'];

And when I echo this out, it's chopped off at this point. I've tried to replace the nbsp before it's sent off via Ajax, but I've no luck yet. I don't really care if there's a nbsp in there either, as long as it's accepted.

I've also tried htmlentities, like this:

$tinyMCEData = htmlentities($_POST['tinyMCEData']);

No luck there either. So why is this happening? I'm guessing there's a reason for this. Any help much appreciated!

Edit: My case looks exactly like the example from this question:
TinyMCE + Jquery + PHP + AJAX Special chars issue

Only the bottom two screenshots of the alert boxes. All I have in my tinyMCE editor are more than once space in the text.

Edit2: Here's what the javascript looks like:

var tinyMCEData = tinyMCE.activeEditor.getContent();
var pars = 'tinyMCEData=' + tinyMCEData;

var myAjax = new Ajax.Request(url, {
   method: 'post',
   postBody: 'pars,
   onSuccess: success,
   onFailure: failure
});

At this point, the data that's being sent looks like this for example:

One two  three   four

What the value is after php post:

One two

Body:
Another solution for those who still have an issue with this (And especially if you want to submit more details)...

I separated the text data from the other variables instead of using a datastring. Then make sure one of the variables contains your text

data: {var1: var1,
       var2: var2,
       var3: var3}


问:
Getting OAuth2 access token for Youtube API through Swift
I am working on an iOS mobile application where I need to upload videos using the Youtube Data API. In general, I understand the workflow needed:

1) Send a request to an authentication endpoint using clientId, clientSecret, and other details.

2) The service authenticates the client, and sends back a request to a client-specified callbackURL containing the access token.

3) The client provides the token in the header whenever he/she wants sends future requests.

I've successfully uploaded Youtube videos using node.js script, but I'm having a lot of trouble understanding how to implement this in Swift. In my VideoManagementController, I have a button that triggers the upload of a sample.mp4 file:

```<code>   let headers = ["Authorization": "Bearer \(self.newToken))"]

        let path = Bundle.main.path(forResource: "sample", ofType: ".mp4")

        let videodata : NSData = NSData.dataWithContentsOfMappedFile(path!)! as! NSData
        print("TOKEN: \(String(describing: token))")
        Alamofire.request("https://www.googleapis.com/upload/youtube/v3/videos?part=id", method: .post, parameters: nil, encoding: JSONEncoding.default, headers: headers).responseJSON { (response) in

            print(response)
        }
</code>```

I am attempting to retrieve my access token in the viewDidLoad() stage of the controller:

```<code>  let authorizationEndpoint = URL(string: "https://accounts.google.com/o/oauth2/v2/auth")
    let tokenEndpoint = URL(string: "https://www.googleapis.com/oauth2/v4/token")
    let configuration = OIDServiceConfiguration(authorizationEndpoint: authorizationEndpoint!, tokenEndpoint: tokenEndpoint!)

    let request = OIDAuthorizationRequest(configuration: configuration, clientId: self.kClientID, scopes: [OIDScopeOpenID, OIDScopeProfile], redirectURL: self.KRedirectURI!, responseType: OIDResponseTypeCode, additionalParameters: nil)

    let appDelegate: AppDelegate? = (UIApplication.shared.delegate as? AppDelegate)
    print("REACHED")

    appDelegate?.currentAuthorizationFlow = OIDAuthState.authState(byPresenting: request, presenting: self, callback: {(_ authState: OIDAuthState?, _ error: Error?) -> Void in
        if (authState != nil) {
            print("TOKEN: Got authorization tokens. Access token: \(String(describing: authState?.lastTokenResponse?.accessToken))")
            self.newToken = authState?.lastTokenResponse?.accessToken
            self.authState = authState
        }
        else {
            print("TOKEN: Authorization error: \(String(describing: error?.localizedDescription))")
            self.authState = nil
        }
    })
</code>```

The issue is that my access token retrieval code essentially hangs and never completes. It reaches the print statement "REACHED" but never comes out of this following portion of code:

```<code>appDelegate?.currentAuthorizationFlow = OIDAuthState.authState(byPresenting: request, presenting: self, callback: {(_ authState: OIDAuthState?, _ error: Error?) -> Void in
        if (authState != nil) {
            print("TOKEN: Got authorization tokens. Access token: \(String(describing: authState?.lastTokenResponse?.accessToken))")
            self.newToken = authState?.lastTokenResponse?.accessToken

        }
        else {
            print("TOKEN: Authorization error: \(String(describing: error?.localizedDescription))")
            self.authState = nil
        }
</code>```

I do not either get a new token or get the authorization error print out.

I suspect it has something to do with my callbackURL. I don't think Swift knows where to "listen" to get my access token from. A callbackURL endpoint is relatively easy to set up server-side in node.js, for example, but how do I do this in Swift? Or is this even the real issue?

答:
i have tired in my code like this way , you also need to check sometime encoding type URLEncoding.httpBody hope it may help , it helps me in using through oauth

```<code> let headers = [
        "Content-Type": "application/x-www-form-urlencoded"
    ]

    Alamofire.request("https://accounts.google.com/o/oauth2/revoke?token={\(token)}", method: .post, parameters: parameters, encoding:  URLEncoding.httpBody, headers: headers).responseJSON { (response:DataResponse<Any>) in
</code>```

Body:
I am working on an iOS mobile application where I need to upload videos using the Youtube Data API. In general, I understand the workflow needed:

1) Send a request to an authentication endpoint using clientId, clientSecret, and other details.

2) The service authenticates the client, and sends back a request to a client-specified callbackURL containing the access token.

3) The client provides the token in the header whenever he/she wants sends future requests.

I've successfully uploaded Youtube videos using node.js script, but I'm having a lot of trouble understanding how to implement this in Swift. In my VideoManagementController, I have a button that triggers the upload of a sample.mp4 file:

   let headers = ["Authorization": "Bearer \(self.newToken))"]

        let path = Bundle.main.path(forResource: "sample", ofType: ".mp4")

        let videodata : NSData = NSData.dataWithContentsOfMappedFile(path!)! as! NSData
        print("TOKEN: \(String(describing: token))")
        Alamofire.request("https://www.googleapis.com/upload/youtube/v3/videos?part=id", method: .post, parameters: nil, encoding: JSONEncoding.default, headers: headers).responseJSON { (response) in

            print(response)
        }

I am attempting to retrieve my access token in the viewDidLoad() stage of the controller:

  let authorizationEndpoint = URL(string: "https://accounts.google.com/o/oauth2/v2/auth")
    let tokenEndpoint = URL(string: "https://www.googleapis.com/oauth2/v4/token")
    let configuration = OIDServiceConfiguration(authorizationEndpoint: authorizationEndpoint!, tokenEndpoint: tokenEndpoint!)

    let request = OIDAuthorizationRequest(configuration: configuration, clientId: self.kClientID, scopes: [OIDScopeOpenID, OIDScopeProfile], redirectURL: self.KRedirectURI!, responseType: OIDResponseTypeCode, additionalParameters: nil)

    let appDelegate: AppDelegate? = (UIApplication.shared.delegate as? AppDelegate)
    print("REACHED")

    appDelegate?.currentAuthorizationFlow = OIDAuthState.authState(byPresenting: request, presenting: self, callback: {(_ authState: OIDAuthState?, _ error: Error?) -> Void in
        if (authState != nil) {
            print("TOKEN: Got authorization tokens. Access token: \(String(describing: authState?.lastTokenResponse?.accessToken))")
            self.newToken = authState?.lastTokenResponse?.accessToken
            self.authState = authState
        }
        else {
            print("TOKEN: Authorization error: \(String(describing: error?.localizedDescription))")
            self.authState = nil
        }
    })

The issue is that my access token retrieval code essentially hangs and never completes. It reaches the print statement "REACHED" but never comes out of this following portion of code:

appDelegate?.currentAuthorizationFlow = OIDAuthState.authState(byPresenting: request, presenting: self, callback: {(_ authState: OIDAuthState?, _ error: Error?) -> Void in
        if (authState != nil) {
            print("TOKEN: Got authorization tokens. Access token: \(String(describing: authState?.lastTokenResponse?.accessToken))")
            self.newToken = authState?.lastTokenResponse?.accessToken

        }
        else {
            print("TOKEN: Authorization error: \(String(describing: error?.localizedDescription))")
            self.authState = nil
        }

I do not either get a new token or get the authorization error print out.

I suspect it has something to do with my callbackURL. I don't think Swift knows where to "listen" to get my access token from. A callbackURL endpoint is relatively easy to set up server-side in node.js, for example, but how do I do this in Swift? Or is this even the real issue?

Body:
i have tired in my code like this way , you also need to check sometime encoding type URLEncoding.httpBody hope it may help , it helps me in using through oauth

 let headers = [
        "Content-Type": "application/x-www-form-urlencoded"
    ]

    Alamofire.request("https://accounts.google.com/o/oauth2/revoke?token={\(token)}", method: .post, parameters: parameters, encoding:  URLEncoding.httpBody, headers: headers).responseJSON { (response:DataResponse<Any>) in


问:
Why does git uses 2 different commands to show HEAD?
I noticed there are 2 HEADs:

.git\HEAD

.git\refs\remotes\origin\HEAD

When I use git show-ref HEAD, it only gives me this:

```<code>ce0762c073b407d794f54f0b5d2a50375fdcb609 refs/remotes/origin/HEAD
</code>```

Whle when I use git rev-parse HEAD, it gives me the value of .git\HEAD:

```<code>a758e523fe40e799194878bac567b7f4b8eec2b9
</code>```

Why Git use 2 different commands to show HEAD? Any strong reason?

答:
.git/HEAD is used by Git to hold the current ref. So when you're on master, it will be ref: refs/heads/master. When you are on detached HEAD, it will be a commit's hash.

.git/refs/remotes/origin/HEAD is actually a remote ref that points to the default branch on remote. When master is the default remote branch, it will be ref: refs/remotes/origin/master (if your remote is origin). It's possible to have a default remote branch other than master but I have noticed that it will not correctly reflect that.

But

```<code>$ git remote show github
</code>```

will always tell you the correct default remote branch.

See this answer of How does origin/HEAD get set? for more details.

git show-ref shows you refs, which are local branches, remote branches, tags, stash refs.

With

```<code>git show-ref HEAD
</code>```

Git is using the "HEAD" as pattern

```<code>git show-ref [-q|--quiet] [--verify] [--head] [-d|--dereference]
         [-s|--hash[=<n>]] [--abbrev[=<n>]] [--tags]
         [--heads] [--] [<pattern>…]
</code>```

and only showing refs that match.

See git-show-ref doc.

I mostly use git branch with -a or -r options to see branches, git tag to see tags, and rarely use git show-ref.

ContentLicense: CC BY-SA 4.0

Body:
I noticed there are 2 HEADs:

.git\HEAD

.git\refs\remotes\origin\HEAD

When I use git show-ref HEAD, it only gives me this:

ce0762c073b407d794f54f0b5d2a50375fdcb609 refs/remotes/origin/HEAD

Whle when I use git rev-parse HEAD, it gives me the value of .git\HEAD:

a758e523fe40e799194878bac567b7f4b8eec2b9

Why Git use 2 different commands to show HEAD? Any strong reason?

Body:
.git/HEAD is used by Git to hold the current ref. So when you're on master, it will be ref: refs/heads/master. When you are on detached HEAD, it will be a commit's hash.

.git/refs/remotes/origin/HEAD is actually a remote ref that points to the default branch on remote. When master is the default remote branch, it will be ref: refs/remotes/origin/master (if your remote is origin). It's possible to have a default remote branch other than master but I have noticed that it will not correctly reflect that.

But

$ git remote show github

will always tell you the correct default remote branch.

See this answer of How does origin/HEAD get set? for more details.

git show-ref shows you refs, which are local branches, remote branches, tags, stash refs.

With

git show-ref HEAD

Git is using the "HEAD" as pattern

git show-ref [-q|--quiet] [--verify] [--head] [-d|--dereference]
         [-s|--hash[=<n>]] [--abbrev[=<n>]] [--tags]
         [--heads] [--] [<pattern>…]

and only showing refs that match.

See git-show-ref doc.

I mostly use git branch with -a or -r options to see branches, git tag to see tags, and rarely use git show-ref.


问:
What is `cdk` in Angular Material 2 components
In multiple places within angular material source, there are elements/ css classes that have cdk as their prefix.

Does anyone know what the abbreviation for cdk in angular material context?

答:
CDK (Component Development Kit) is a standalone package.

The goal of the CDK is to give developers more tools to build awesome components for the web. This will be especially useful for projects that want to take advantage of the features of Angular Material without adopting the Material Design visual language.

Checkout the repo from Google for CDK

```<code>https://github.com/angular/material2/tree/master/src/cdk
</code>```

Body:
CDK (Component Development Kit) is a standalone package.

The goal of the CDK is to give developers more tools to build awesome components for the web. This will be especially useful for projects that want to take advantage of the features of Angular Material without adopting the Material Design visual language.

Checkout the repo from Google for CDK

https://github.com/angular/material2/tree/master/src/cdk


问:
Is request.user.is_authenticated() necessary here?
I am writing a view only for staff users.

```<code>def my_view(request):
    if request.user.is_staff:
        # show something to staff
    else:
        return my_view_404(request)
</code>```

It this permission check enough? Any flaw? Or should I check request.user.is_authenticated()?

答: No need as request.user.is_staff will check both authentication and staff status.</p>

Body:
I am writing a view only for staff users.

def my_view(request):
    if request.user.is_staff:
        # show something to staff
    else:
        return my_view_404(request)

It this permission check enough? Any flaw? Or should I check request.user.is_authenticated()?


问:
How to access Sharepoint 2010 word automation services from remote server?
Basically i am trying to access the sharepoint server 2010 which is installed on remote machine to do some word operations. But when i am trying to connect with the remote server using SPSite(), it is throwing the below exception:

System.IO.FileNotFoundException was unhandled
  Message=The Web application at "http://RemoteServer" could not be found. Verify that you have typed the URL correctly. If the URL should be serving existing content, the system administrator may need to add a new request URL mapping to the intended application.

Don't know how to connect with remote server using SPSite().

答: It's impossible. SPSite and, generally, the whole object model does not support connecting to a remote SharePoint farm. All you can do is access the local SharePoint farm.


问:
Cannot understand the Output of this Code
```<code>void abc(int n) {
    if (n <= 10) {
        abc(++n);
        printf("%d\n", n);
    }
}

void main() {
    int m = 5;
    abc(m);
}
</code>```

The output shows:

```<code>11
10
9
8
7
6
</code>```

I cannot understand the output. Please explain. I am a novice code lover.

答:
I would first suggest you to read basics of recursion. It will be good for you.

Now about All the recursive calling, it will be like as bellow:

abc(5);

This will call the function abc with value 5.
Now before printing it, it will make the recursive call to abc but before calling it will increment the value of n from 5 to 6. The same will happen in the next call from 6 to 7, 7 to 8, 8 to 9, 9 to 10 and 10 to 11. Now on the call for n=11, the if condition will fail and recursion will stop. On returning from recursive calls, it will print increment values but from last call to first,i.e. for 11 than 10 and so on till 6.

Body:
void abc(int n) {
    if (n <= 10) {
        abc(++n);
        printf("%d\n", n);
    }
}

void main() {
    int m = 5;
    abc(m);
}

The output shows:

11
10
9
8
7
6

I cannot understand the output. Please explain. I am a novice code lover.


问:
Delete a row from subreport in MS-Access
I am trying to Delete a row from a subreport (my subreport used different columns values from different tables). But I've got a Data type mismatch error!

Below is the code I used:

```<code>CurrentDb.Execute "DELETE FROM StateBudget " & " WHERE S_ID = " & _
                   DLookup("ID", "States", "State='" & _
                   Me.subformStateBudget.Form.Recordset.Fields("State") & "'")
</code>```

I think S_ID is a text value, so how can I change DLookup value to string or text?

答:
You don't need to change the DLookUp value to a string, you need to pass it to SQL as a string (in quotes):</p>

```<code>CurrentDb.Execute "DELETE FROM StateBudget " & " WHERE S_ID = """ & _
                   DLookup("ID", "States", "State='" & _
                   Me.subformStateBudget.Form.Recordset.Fields("State") & "'") & """"
</code>```

Body:
I am trying to Delete a row from a subreport (my subreport used different columns values from different tables). But I've got a Data type mismatch error!

Below is the code I used:

CurrentDb.Execute "DELETE FROM StateBudget " & " WHERE S_ID = " & _
                   DLookup("ID", "States", "State='" & _
                   Me.subformStateBudget.Form.Recordset.Fields("State") & "'")

I think S_ID is a text value, so how can I change DLookup value to string or text?

Body:
You don't need to change the DLookUp value to a string, you need to pass it to SQL as a string (in quotes):

CurrentDb.Execute "DELETE FROM StateBudget " & " WHERE S_ID = """ & _
                   DLookup("ID", "States", "State='" & _
                   Me.subformStateBudget.Form.Recordset.Fields("State") & "'") & """"


问:
Serializing ManyToManyField in DjangoRestFramework
I have 2 models here Tag and Question. All i want is to serialize the Tag Model without explicitly inside the Question Serializer where Tag model is related by ManyToMany relation with Question model.

```<code>class Question(models.Model):
    question = models.TextField(blank=False, null=False)
    question_image = models.ImageField(blank=True, null=True, upload_to='question')
    opt_first = models.CharField(max_length=50, blank=False, null=False)
    opt_second = models.CharField(max_length=50, blank=False, null=False)
    opt_third = models.CharField(max_length=50, blank=False, null=False)
    opt_forth = models.CharField(max_length=50, blank=False, null=False)
    answer = models.CharField(max_length=1, choices=(('1','1'),('2','2'),('3','3'),('4','4')))
    description = models.TextField(blank=True,null=True )
    tag = models.ManyToManyField(Tag)
    created_on  = models.DateTimeField(default= timezone.now)

class Tag(models.Model):
    name = models.CharField(max_length = 50, null=False, unique=True)
</code>```

And I have serializers classes for these two models

```<code>class TagSerializer(serializers.ModelSerializer):
    class Meta:
        model = Tag
        fields = ('name',)

class QuestionSerializer(serializers.ModelSerializer):
     # tag = TagSerializer(many=True)
    def to_representation(self, obj):
        rep = super(QuestionSerializer, self).to_representation(obj)
        rep['tag'] = []
        for i in obj.tag.all():
           # rep['tag'].append({'id':i.id,'name':i.name})
           # Below doesn't give JSON representation produces an error instead
           rep['tag'].append(TagSerializer(i))
        return rep

    class Meta:
        model = Question
        fields = ('question', 'question_image', 'opt_first', 'opt_second', 'opt_third', 'opt_forth', 'answer', 'description', 'tag')
        read_only_fields = ('created_on',)
</code>```

Here on using TagSerializer in the to_repesentation method of QuestionSerializer doesn't serialize the tag object. Instead produces error

    ExceptionValue : TagSerializer(<Tag: Geography>):
    name = CharField(max_length=50, validators=[<UniqueValidator(queryset=Tag.objects.all())>]) is not JSON serializable

答:
You are trying to serialize TagSerializer class. Try to change code to serialize data:

```<code>for i in obj.tag.all():
       # rep['tag'].append({'id':i.id,'name':i.name})
       # Below doesn't give JSON representation produces an error instead
       ser = TagSerializer(i)
       rep['tag'].append(ser.data)
</code>```

Also I didn't get why you are override to_representation method.
Try just to define tag field in QuestionSerializer:

```<code>tag = TagSerializer(read_only=True, many=True)
</code>```

Body:
I have 2 models here Tag and Question. All i want is to serialize the Tag Model without explicitly inside the Question Serializer where Tag model is related by ManyToMany relation with Question model.

class Question(models.Model):
    question = models.TextField(blank=False, null=False)
    question_image = models.ImageField(blank=True, null=True, upload_to='question')
    opt_first = models.CharField(max_length=50, blank=False, null=False)
    opt_second = models.CharField(max_length=50, blank=False, null=False)
    opt_third = models.CharField(max_length=50, blank=False, null=False)
    opt_forth = models.CharField(max_length=50, blank=False, null=False)
    answer = models.CharField(max_length=1, choices=(('1','1'),('2','2'),('3','3'),('4','4')))
    description = models.TextField(blank=True,null=True )
    tag = models.ManyToManyField(Tag)
    created_on  = models.DateTimeField(default= timezone.now)

class Tag(models.Model):
    name = models.CharField(max_length = 50, null=False, unique=True)

And I have serializers classes for these two models

class TagSerializer(serializers.ModelSerializer):
    class Meta:
        model = Tag
        fields = ('name',)

class QuestionSerializer(serializers.ModelSerializer):
     # tag = TagSerializer(many=True)
    def to_representation(self, obj):
        rep = super(QuestionSerializer, self).to_representation(obj)
        rep['tag'] = []
        for i in obj.tag.all():
           # rep['tag'].append({'id':i.id,'name':i.name})
           # Below doesn't give JSON representation produces an error instead
           rep['tag'].append(TagSerializer(i))
        return rep

    class Meta:
        model = Question
        fields = ('question', 'question_image', 'opt_first', 'opt_second', 'opt_third', 'opt_forth', 'answer', 'description', 'tag')
        read_only_fields = ('created_on',)

Here on using TagSerializer in the to_repesentation method of QuestionSerializer doesn't serialize the tag object. Instead produces error

    ExceptionValue : TagSerializer(<Tag: Geography>):
    name = CharField(max_length=50, validators=[<UniqueValidator(queryset=Tag.objects.all())>]) is not JSON serializable

Body:
You are trying to serialize TagSerializer class. Try to change code to serialize data:

for i in obj.tag.all():
       # rep['tag'].append({'id':i.id,'name':i.name})
       # Below doesn't give JSON representation produces an error instead
       ser = TagSerializer(i)
       rep['tag'].append(ser.data)

Also I didn't get why you are override to_representation method.
Try just to define tag field in QuestionSerializer:

tag = TagSerializer(read_only=True, many=True)


问:
format ‘%d’ expects argument of type ‘int’, but argument 3 has type ‘int *’
I'm trying to create a program that will show elements from the int array. But I keep getting the warning. This is probably going to get really downvoted but I don't know where I made a mistake.

Here is the code:

```<code>#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <string.h>
#include <math.h>
#include <time.h>

int main() {
     int counter;
     int elements[3] = { 22, 52, 95 };

     for (counter = 1; counter <= 3; counter++) {
         printf("Element %d: %d\n", counter, elements);
     }
     return 0;
}
</code>```

答:
The problem here is that you are trying to print an int but elements is not an int;

it is an array!

You want to use [] to retrieve one int at a time

Array in C are 0-indexed. So it means that you should access them starting from the 0th element.

Check the following:

```<code>for(counter = 0; counter < 3; counter++)
     printf("Element %d: %d\n", counter, elements[counter]);
</code>```

Body:
I'm trying to create a program that will show elements from the int array. But I keep getting the warning. This is probably going to get really downvoted but I don't know where I made a mistake.

Here is the code:

#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <string.h>
#include <math.h>
#include <time.h>

int main() {
     int counter;
     int elements[3] = { 22, 52, 95 };

     for (counter = 1; counter <= 3; counter++) {
         printf("Element %d: %d\n", counter, elements);
     }
     return 0;
}

Body:
The problem here is that you are trying to print an int but elements is not an int;

it is an array!

You want to use [] to retrieve one int at a time

Array in C are 0-indexed. So it means that you should access them starting from the 0th element.

Check the following:

for(counter = 0; counter < 3; counter++)
     printf("Element %d: %d\n", counter, elements[counter]);


问:
How to unzip multiple pssword protected zip files in an directory which has same password using java?
I am very new to java and I am trying to write an java program to unzip all zip files in an directory all of which have same password.
I have written an program which unzips an particular zip file by giving the password.

```<code>import java.io.OutputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.PathMatcher;
import java.nio.file.Paths;
import java.util.List;
import java.util.stream.Stream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;

//import java.util.zip.ZipFile;
import net.lingala.zip4j.core.ZipFile;
import net.lingala.zip4j.model.FileHeader;

public class Extraction {
     public Extraction() {

     try {

     ZipFile zipFile = new
     ZipFile("C:\\Users\\Desktop\\ZipFile\\myzip.zip");

     if (zipFile.isEncrypted()) {

     zipFile.setPassword("MYPASS!");
     }

     List fileHeaderList = zipFile.getFileHeaders();

     for (int i = 0; i < fileHeaderList.size(); i++) {
     FileHeader fileHeader = (FileHeader) fileHeaderList.get(i);

     zipFile.extractFile(fileHeader, "C:\\Users\\Desktop\\ZipFile");
     System.out.println("Extracted");
     }

     } catch (Exception e) {
     System.out.println("Please Try Again");
     }

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

        }
}
</code>```

I have also written an code which unzips all the zip files (Which are not password protected) in an folder.

```<code>import java.io.OutputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.PathMatcher;
import java.nio.file.Paths;
import java.util.List;
import java.util.stream.Stream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;

//import java.util.zip.ZipFile;
import net.lingala.zip4j.core.ZipFile;
import net.lingala.zip4j.model.FileHeader;

public class Extraction {

    public static void main(String[] args) {
        Extraction unzipper = new Extraction();
        unzipper.unzipZipsInDirTo(Paths.get("D:/"), Paths.get("D:/unzipped"));

    }

    public void unzipZipsInDirTo(Path searchDir, Path unzipTo) {

        final PathMatcher matcher = searchDir.getFileSystem().getPathMatcher("glob:**/*.zip");
        try (final Stream<Path> stream = Files.list(searchDir)) {
            stream.filter(matcher::matches).forEach(zipFile -> unzip(zipFile, unzipTo));
        } catch (Exception e) {
            System.out.println("Something went wrong, Please try again!!");
        }
    }

    public void unzip(Path zipFile, Path outputPath) {
        try (ZipInputStream zis = new ZipInputStream(Files.newInputStream(zipFile))) {

            ZipEntry entry = zis.getNextEntry();

            while (entry != null) {

                Path newFilePath = outputPath.resolve(entry.getName());
                if (entry.isDirectory()) {
                    Files.createDirectories(newFilePath);
                } else {
                    if (!Files.exists(newFilePath.getParent())) {
                        Files.createDirectories(newFilePath.getParent());
                    }
                    try (OutputStream bos = Files.newOutputStream(outputPath.resolve(newFilePath))) {
                        byte[] buffer = new byte[Math.toIntExact(entry.getSize())];

                        int location;

                        while ((location = zis.read(buffer)) != -1) {
                            bos.write(buffer, 0, location);
                        }
                    }
                }
                entry = zis.getNextEntry();
            }
        } catch (Exception e1) {
            System.out.println("Please try again");
        }
    }

}
</code>```

I am bit confused how to integrate these 2 codes to make an program which unzips all the zip files in an directory which are password protected and has the same password.
Can anyone of you help me in integrating these 2 codes.
I searched a lot but did not get proper resolution so I am posting this.
I hope my question is clear.

答:
Thanks guys although none answered my question. I found the answer I am posting this as there might be someone else who might be looking for the similar answer.</p>

```<code>import java.io.File;
import java.util.List;

import javax.swing.filechooser.FileNameExtensionFilter;

import net.lingala.zip4j.core.ZipFile;
import net.lingala.zip4j.model.FileHeader;

public class SamExtraction {

    public static void main(String[] args) {

        final FileNameExtensionFilter extensionFilter = new FileNameExtensionFilter("N/A", "zip");
        //Folder where zip file is present
        final File file = new File("C:/Users/Desktop/ZipFile");
        for (final File child : file.listFiles()) {
            try {
                ZipFile zipFile = new ZipFile(child);
                if (extensionFilter.accept(child)) {
                    if (zipFile.isEncrypted()) {
                        //Your ZIP password
                        zipFile.setPassword("MYPASS!");
                    }
                    List fileHeaderList = zipFile.getFileHeaders();

                    for (int i = 0; i < fileHeaderList.size(); i++) {
                        FileHeader fileHeader = (FileHeader) fileHeaderList.get(i);
                        //Path where you want to Extract
                        zipFile.extractFile(fileHeader, "C:/Users/Desktop/ZipFile");
                        System.out.println("Extracted");
                    }
                }
            } catch (Exception e) {
                System.out.println("Please Try Again");
            }
        }

    }
}
</code>```

Body:
I am very new to java and I am trying to write an java program to unzip all zip files in an directory all of which have same password.
I have written an program which unzips an particular zip file by giving the password.

import java.io.OutputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.PathMatcher;
import java.nio.file.Paths;
import java.util.List;
import java.util.stream.Stream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;

//import java.util.zip.ZipFile;
import net.lingala.zip4j.core.ZipFile;
import net.lingala.zip4j.model.FileHeader;

public class Extraction {
     public Extraction() {

     try {

     ZipFile zipFile = new
     ZipFile("C:\\Users\\Desktop\\ZipFile\\myzip.zip");

     if (zipFile.isEncrypted()) {

     zipFile.setPassword("MYPASS!");
     }

     List fileHeaderList = zipFile.getFileHeaders();

     for (int i = 0; i < fileHeaderList.size(); i++) {
     FileHeader fileHeader = (FileHeader) fileHeaderList.get(i);

     zipFile.extractFile(fileHeader, "C:\\Users\\Desktop\\ZipFile");
     System.out.println("Extracted");
     }

     } catch (Exception e) {
     System.out.println("Please Try Again");
     }

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

        }
}

I have also written an code which unzips all the zip files (Which are not password protected) in an folder.

import java.io.OutputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.PathMatcher;
import java.nio.file.Paths;
import java.util.List;
import java.util.stream.Stream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;

//import java.util.zip.ZipFile;
import net.lingala.zip4j.core.ZipFile;
import net.lingala.zip4j.model.FileHeader;

public class Extraction {

    public static void main(String[] args) {
        Extraction unzipper = new Extraction();
        unzipper.unzipZipsInDirTo(Paths.get("D:/"), Paths.get("D:/unzipped"));

    }

    public void unzipZipsInDirTo(Path searchDir, Path unzipTo) {

        final PathMatcher matcher = searchDir.getFileSystem().getPathMatcher("glob:**/*.zip");
        try (final Stream<Path> stream = Files.list(searchDir)) {
            stream.filter(matcher::matches).forEach(zipFile -> unzip(zipFile, unzipTo));
        } catch (Exception e) {
            System.out.println("Something went wrong, Please try again!!");
        }
    }

    public void unzip(Path zipFile, Path outputPath) {
        try (ZipInputStream zis = new ZipInputStream(Files.newInputStream(zipFile))) {

            ZipEntry entry = zis.getNextEntry();

            while (entry != null) {

                Path newFilePath = outputPath.resolve(entry.getName());
                if (entry.isDirectory()) {
                    Files.createDirectories(newFilePath);
                } else {
                    if (!Files.exists(newFilePath.getParent())) {
                        Files.createDirectories(newFilePath.getParent());
                    }
                    try (OutputStream bos = Files.newOutputStream(outputPath.resolve(newFilePath))) {
                        byte[] buffer = new byte[Math.toIntExact(entry.getSize())];

                        int location;

                        while ((location = zis.read(buffer)) != -1) {
                            bos.write(buffer, 0, location);
                        }
                    }
                }
                entry = zis.getNextEntry();
            }
        } catch (Exception e1) {
            System.out.println("Please try again");
        }
    }

}

I am bit confused how to integrate these 2 codes to make an program which unzips all the zip files in an directory which are password protected and has the same password.
Can anyone of you help me in integrating these 2 codes.
I searched a lot but did not get proper resolution so I am posting this.
I hope my question is clear.

Body:
Thanks guys although none answered my question. I found the answer I am posting this as there might be someone else who might be looking for the similar answer.

import java.io.File;
import java.util.List;

import javax.swing.filechooser.FileNameExtensionFilter;

import net.lingala.zip4j.core.ZipFile;
import net.lingala.zip4j.model.FileHeader;

public class SamExtraction {

    public static void main(String[] args) {

        final FileNameExtensionFilter extensionFilter = new FileNameExtensionFilter("N/A", "zip");
        //Folder where zip file is present
        final File file = new File("C:/Users/Desktop/ZipFile");
        for (final File child : file.listFiles()) {
            try {
                ZipFile zipFile = new ZipFile(child);
                if (extensionFilter.accept(child)) {
                    if (zipFile.isEncrypted()) {
                        //Your ZIP password
                        zipFile.setPassword("MYPASS!");
                    }
                    List fileHeaderList = zipFile.getFileHeaders();

                    for (int i = 0; i < fileHeaderList.size(); i++) {
                        FileHeader fileHeader = (FileHeader) fileHeaderList.get(i);
                        //Path where you want to Extract
                        zipFile.extractFile(fileHeader, "C:/Users/Desktop/ZipFile");
                        System.out.println("Extracted");
                    }
                }
            } catch (Exception e) {
                System.out.println("Please Try Again");
            }
        }

    }
}


问:
Why do I get "Pair cannot be cast to java.lang.Comparable" error?
I have this class:

```<code>public class Pair<V> implements Map.Entry<V,V> {
    private V first;
    private V second;
    public Pair(){

    }
    public Pair (V first, V second){
        this.first = first;
        this.second = second;
    }

    @Override
    public V getKey() {
        return first;
    }

    @Override
    public V getValue() {
        return second;
    }

    @Override
    public V setValue(V value) {
        this.second = value;
        return null;
    }

    @Override
    public String toString() {
        return "Pair{" +
                "first=" + first +
                ", second=" + second +
                '}';
    }
}
</code>```

Inside Program class I have this method:

```<code>public static <K,V extends Comparable> Pair<V> minmax(Map<K,V> map) {
    List<V> values = new ArrayList<V>(map.values());
    List<K> keys = new ArrayList<K>(map.keySet());
    V min = (V)min(values);
    V max = (V)max(values);
    V minKey = (V)map.get(min);
    V maxKey = (V)map.get(max);

    Pair minPair = new Pair(minKey,min);
    Pair maxPair = new Pair(maxKey,max);
    return new Pair((V)minPair,(V)maxPair);
}
</code>```

Here the row that calls the method above:

```<code>    Pair minMax2 = minmax(mapGrades);
</code>```

But on this row:

```<code> return new Pair((V)minPair,(V)maxPair);
</code>```

I get this error:

```<code>Exception in thread "main" java.lang.ClassCastException: Pair cannot be cast to java.lang.Comparable
    at Program.minmax(Program.java:35)
    at Program.main(Program.java:14)
</code>```

Any idea why I get the error above and how to fix it?

答:
minPair and maxPair are of type Pair (well you could define them as Pair<V>). You can't cast them to V.

The type of new Pair(minPair,maxPair) can be Pair<Pair<V>>, not Pair<V>.

Besides, since your method should return a Pair<V>, it can return

```<code>Pair<V> minPair = new Pair<>(minKey,min);
</code>```

or

```<code>Pair<V> maxPair = new Pair<>(maxKey,max);
</code>```

but not new Pair(minPair,maxPair).

Body:
I have this class:

public class Pair<V> implements Map.Entry<V,V> {
    private V first;
    private V second;
    public Pair(){

    }
    public Pair (V first, V second){
        this.first = first;
        this.second = second;
    }

    @Override
    public V getKey() {
        return first;
    }

    @Override
    public V getValue() {
        return second;
    }

    @Override
    public V setValue(V value) {
        this.second = value;
        return null;
    }

    @Override
    public String toString() {
        return "Pair{" +
                "first=" + first +
                ", second=" + second +
                '}';
    }
}

Inside Program class I have this method:

public static <K,V extends Comparable> Pair<V> minmax(Map<K,V> map) {
    List<V> values = new ArrayList<V>(map.values());
    List<K> keys = new ArrayList<K>(map.keySet());
    V min = (V)min(values);
    V max = (V)max(values);
    V minKey = (V)map.get(min);
    V maxKey = (V)map.get(max);

    Pair minPair = new Pair(minKey,min);
    Pair maxPair = new Pair(maxKey,max);
    return new Pair((V)minPair,(V)maxPair);
}

Here the row that calls the method above:

    Pair minMax2 = minmax(mapGrades);

But on this row:

 return new Pair((V)minPair,(V)maxPair);

I get this error:

Exception in thread "main" java.lang.ClassCastException: Pair cannot be cast to java.lang.Comparable
    at Program.minmax(Program.java:35)
    at Program.main(Program.java:14)

Any idea why I get the error above and how to fix it?

Body:
minPair and maxPair are of type Pair (well you could define them as Pair<V>). You can't cast them to V.

The type of new Pair(minPair,maxPair) can be Pair<Pair<V>>, not Pair<V>.

Besides, since your method should return a Pair<V>, it can return

Pair<V> minPair = new Pair<>(minKey,min);

or

Pair<V> maxPair = new Pair<>(maxKey,max);

but not new Pair(minPair,maxPair).


问:
Can i have a child div hide its parent div along with it when clicked?
For example :

```<code><div id="parent">
      <div id="child">Click here</div>
</div>
</code>```

when i click on child, both div will disappear or hidden

答:
Try this using jQuery

```<code>$("#child").on('click',function(){
    $(this).parent().hide();
});
</code>```

Link for reference
hope this helps...

Body:
For example :

Click here

when i click on child, both div will disappear or hidden

Body:
Try this using jQuery

$("#child").on('click',function(){
    $(this).parent().hide();
});

Link for reference
hope this helps...


问:
sqlite3 .dump inserts replace function in dump (change from 3.18 to 3.19)
In sqlite3 3.19.3 the dump file produced by sqlite3 .dump  or by sqlite3 with .mode insert t_objects (where t_objects is the name of a table) followed by SELECT * FROM t_objects; uses the replace function for newline characters. See sqlite3 file ext/misc/dbdump.c function output_quoted_escaped_string near line 370.

But in sqlite3 3.18 the behavior was to output newline characters as is, which I prefer.

So with 3.18 my dump contained:

```<code> CREATE TABLE t_objects
   (ob_id VARCHAR(30) PRIMARY KEY ASC NOT NULL UNIQUE,
    ob_mtim REAL NOT NULL,
    ob_content TEXT NOT NULL,
    ob_paylkind VARCHAR(30) NOT NULL,
    ob_paylinit TEXT NOT NULL,
    ob_paylcontent TEXT NOT NULL);
</code>```

later followed with

```<code> INSERT INTO t_objects VALUES('_0UsE4ep7mY5_3M6VTOn9Doe',1497676631.12,'
 ///$c

 ','named','c','@NAMEDPROXY: __');
</code>```

but with 3.19.3 the same INSERT statement (for the same row content) became

```<code> INSERT INTO t_objects VALUES('_0UsE4ep7mY5_3M6VTOn9Doe',1497676631.1199998855,
   replace('\n///$c\n\n','\n',char(10)),'named','c','@NAMEDPROXY: __');
</code>```

(I added a newline after the last comma of the first line for readability here; but it was not there)

It is a documented change

Changes carried forward from version 3.19.0 (2017-05-22):

Use replace() instead of char() for escaping newline and carriage-return characters embedded in strings in the .dump output from the command-line shell.

But I dislike it (because I had to write a specialized dumping program dumpsqlmonimelt.cc)

Is there some way (e.g. some option or sqlite3 directive) to get back, using, sqlite 3.19.3, that old sqlite 3.18 behavior and format in dump.

The reason I am asking is that I actually keep that dump in git (e.g. this mom_user.sql file) with the sqlite3 dump and restore done by git pre-commit and post-merge hooks. And I really like these newlines characters appearing as-is in dump files (that was one of my reasons to choose sqlite3, hence having a git friendly dump).

FWIW the sqlite3 is the one from Linux/Debian/Sid/x86-64 (package version 3.19.3-3)

addenda

It could happen that sqlite 3.20 would improve that issue (at least for .dump). See its release log and my sqlite-user message of July 14th

答:
The sqlite3 command-line shell is not considered a part of the SQLite library itself, and has no API stability guarantee.

There is no option to go back to the 3.18 behaviour. You have to revert that change manually, or use your own dumping program.

Body:
In sqlite3 3.19.3 the dump file produced by sqlite3 .dump  or by sqlite3 with .mode insert t_objects (where t_objects is the name of a table) followed by SELECT * FROM t_objects; uses the replace function for newline characters. See sqlite3 file ext/misc/dbdump.c function output_quoted_escaped_string near line 370.

But in sqlite3 3.18 the behavior was to output newline characters as is, which I prefer.

So with 3.18 my dump contained:

 CREATE TABLE t_objects
   (ob_id VARCHAR(30) PRIMARY KEY ASC NOT NULL UNIQUE,
    ob_mtim REAL NOT NULL,
    ob_content TEXT NOT NULL,
    ob_paylkind VARCHAR(30) NOT NULL,
    ob_paylinit TEXT NOT NULL,
    ob_paylcontent TEXT NOT NULL);

later followed with

 INSERT INTO t_objects VALUES('_0UsE4ep7mY5_3M6VTOn9Doe',1497676631.12,'
 ///$c

 ','named','c','@NAMEDPROXY: __');

but with 3.19.3 the same INSERT statement (for the same row content) became

 INSERT INTO t_objects VALUES('_0UsE4ep7mY5_3M6VTOn9Doe',1497676631.1199998855,
   replace('\n///$c\n\n','\n',char(10)),'named','c','@NAMEDPROXY: __');

(I added a newline after the last comma of the first line for readability here; but it was not there)

It is a documented change

Changes carried forward from version 3.19.0 (2017-05-22):

Use replace() instead of char() for escaping newline and carriage-return characters embedded in strings in the .dump output from the command-line shell.

But I dislike it (because I had to write a specialized dumping program dumpsqlmonimelt.cc)

Is there some way (e.g. some option or sqlite3 directive) to get back, using, sqlite 3.19.3, that old sqlite 3.18 behavior and format in dump.

The reason I am asking is that I actually keep that dump in git (e.g. this mom_user.sql file) with the sqlite3 dump and restore done by git pre-commit and post-merge hooks. And I really like these newlines characters appearing as-is in dump files (that was one of my reasons to choose sqlite3, hence having a git friendly dump).

FWIW the sqlite3 is the one from Linux/Debian/Sid/x86-64 (package version 3.19.3-3)

addenda

It could happen that sqlite 3.20 would improve that issue (at least for .dump). See its release log and my sqlite-user message of July 14th


问:
C# process start focus issue

When I start a new process, it automatically gets the focus. how can I prevent it from getting the focus or instead get back the focus to my application?

here is the code I'm using:

```<code>string path = @"c:\temp\myprocess.exe";
ProcessStartInfo info = new ProcessStartInfo(path);
info.WorkingDirectory = path;
Process p = Process.Start(info);
</code>```

I just need the executed process not to get the focus.

Thank you very much,

Adi Barda

答:
If you don't need to show the process at all, try this:

```<code>string path = @"c:\temp\myprocess.exe";
ProcessStartInfo info = new ProcessStartInfo(path);
info.WorkingDirectory = path;
info.WindowStyle = ProcessWindowStyle.Hidden;
</code>```

Or set WindowStyle to ProcessWindowStyle.Minimized if you want it visible but minimized, as Uwe Keim said.

Title: C# process start focus issue

Body:
When I start a new process, it automatically gets the focus. how can I prevent it from getting the focus or instead get back the focus to my application?

here is the code I'm using:

string path = @"c:\temp\myprocess.exe";
ProcessStartInfo info = new ProcessStartInfo(path);
info.WorkingDirectory = path;
Process p = Process.Start(info);

I just need the executed process not to get the focus.

Thank you very much,

Adi Barda

Body:
If you don't need to show the process at all, try this:

string path = @"c:\temp\myprocess.exe";
ProcessStartInfo info = new ProcessStartInfo(path);
info.WorkingDirectory = path;
info.WindowStyle = ProcessWindowStyle.Hidden;

Or set WindowStyle to ProcessWindowStyle.Minimized if you want it visible but minimized, as Uwe Keim said.


问:
Can't get auto layout to make two buttons side by side stay there
I'm at the point where I'm going crazy, I've tried everything to get these two buttons to stay where they are even if the device is changed. Any help at all would be amazing, this has been driving me crazy for hours.

答:
Pin each button accordingly

Left button at leading end

Right button at trailing end

Left & right button at bottom

Left button horizontal spacing to right button

Left button width equals right button width

Left button height equals right button height

Set the left button height to something e.g 64


问:
After file type validation using JS for an HTML Form, control should stay on the same page if invalid
I have an html form where for file types I want only pdf, docx and doc files. I am successfully able to validate, but on click of OK button, I do not want to post the form if it is invalid. Currently, it is going to connection.php. It should only go to connection.php when I have passed the validation successfully.

```<code><form method="POST" action="connection.php" enctype="multipart/form-data" onsubmit="function()">
<input type="text" id="name" name="bookname" placeholder="Book Name" required/>
<textarea cols="25" rows="4" name="bookdesc" placeholder="Book Description" required></textarea>
<input type="text" id="password" name="bookauthor" placeholder="Book Author"/ required>
<input type="file" name="bookfile" id="bookfile" required/>
</form>
    <script>
        $(document).ready(function () {
        $('input[type=file]').change(function () {
        var val = $(this).val().toLowerCase();
        var regex = new RegExp("(.*?)\.(docx|doc|pdf)$");
         if(!(regex.test(val))) {
        $(this).val('');
        alert('Please select correct file format');
        } }); });
    </script>
</code>```

答:
```<code><form method="POST" action="connection.php" enctype="multipart/form-data" id="myform">
<input type="text" id="name" name="bookname" placeholder="Book Name" required/>
<textarea cols="25" rows="4" name="bookdesc" placeholder="Book Description" required></textarea>
<input type="text" id="password" name="bookauthor" placeholder="Book Author"/ required>
<input type="file" name="bookfile" id="bookfile" required/>
</form>
    <script>
        var isValid = false;
        $(document).ready(function () {
        $('input[type=file]').change(function () {
        var val = $(this).val().toLowerCase();
        var regex = new RegExp("(.*?)\.(docx|doc|pdf)$");
        isValid = !!(regex.test(val));
         if(!isValid) {
        $(this).val('');
        alert('Please select correct file format');
        } }); });
        $("#myform").submit(function(e) {
            if (!isValid) {
                e.preventDefault();
            }
        });
    </script>
</code>```

I have added an id to your form. Using this id as a selector I have created a submit handler for the form. This handler checks whether isValid is false and if so, calls e.preventDefault(), which prevents the form from submitting. If isValid was true, then e.preventDefault() will not be called, therefore the form submits. isValid is initialized with false and is evaluated on input[type=file] change.

Body:
I have an html form where for file types I want only pdf, docx and doc files. I am successfully able to validate, but on click of OK button, I do not want to post the form if it is invalid. Currently, it is going to connection.php. It should only go to connection.php when I have passed the validation successfully.

<form method="POST" action="connection.php" enctype="multipart/form-data" onsubmit="function()">
<input type="text" id="name" name="bookname" placeholder="Book Name" required/>
<textarea cols="25" rows="4" name="bookdesc" placeholder="Book Description" required></textarea>
<input type="text" id="password" name="bookauthor" placeholder="Book Author"/ required>
<input type="file" name="bookfile" id="bookfile" required/>
</form>

Body:
<form method="POST" action="connection.php" enctype="multipart/form-data" id="myform">
<input type="text" id="name" name="bookname" placeholder="Book Name" required/>
<textarea cols="25" rows="4" name="bookdesc" placeholder="Book Description" required></textarea>
<input type="text" id="password" name="bookauthor" placeholder="Book Author"/ required>
<input type="file" name="bookfile" id="bookfile" required/>
</form>
    <script>
        var isValid = false;
        $(document).ready(function () {
        $('input[type=file]').change(function () {
        var val = $(this).val().toLowerCase();
        var regex = new RegExp("(.*?)\.(docx|doc|pdf)$");
        isValid = !!(regex.test(val));
         if(!isValid) {
        $(this).val('');
        alert('Please select correct file format');
        } }); });
        $("#myform").submit(function(e) {
            if (!isValid) {
                e.preventDefault();
            }
        });
    </script>

I have added an id to your form. Using this id as a selector I have created a submit handler for the form. This handler checks whether isValid is false and if so, calls e.preventDefault(), which prevents the form from submitting. If isValid was true, then e.preventDefault() will not be called, therefore the form submits. isValid is initialized with false and is evaluated on input[type=file] change.


问:
Dropdownlist SelectedItemChanged Event in MVC4 Razor?
Is there any event available for Dropdownlist like onChange, etc. in MVC4? Do we have to use Javascript/jQuery in order to make some manipulations like DropwowlistSelectedItemChanged, etc? Or there is a way only using the Razor or MVC4 features?

On the other hand, could you please give me some examples how can I retrieve data and change a label's text with this data according to a Dropdownlist Selected Value? For example when selecting a City from Dropdownlist, I want to get an address data from database by using the selected city id and then show retrieved address on a label. I would be appreciated if you clarify me about the issue above and give me an example to achieve this.

Controller:

```<code>private void PopulateMeetingsDropDownList(object selectedMeetings = null)
    {
        var meetingsQuery = repository.Meetings
            .Join(repository.Cities, m => m.MeetingCityId, c => c.CityID,
                (m, c) => new
                {
                    CityID = c.CityID,
                    CityName = c.CityName,
                    MeetingDate = m.MeetingStartDate
                }
            )
            .OrderBy(x => x.CityID)
            .AsEnumerable()
            .Select(
                i => new
                {
                    CityID = i.CityID,
                    DisplayValue = string.Format(
                        "{0} ({1:dd MMMM yyyy})",
                        i.CityName, i.MeetingDate)
                }
            ).ToList();
        ViewData["MeetingId"] = new SelectList(meetingsQuery, "CityID", "DisplayValue", selectedMeetings);
    }
</code>```

View:

```<code><label>Meeting</label>
@Html.DropDownListFor(m => m.MeetingId, ViewData["MeetingId"] as SelectList,"---- Select ----", new { name = "meetingId", id = "meetingId"})
</code>```

答:
You must use onchange property in a new {} side of declaring class property like this example </p>

<p>[@Html.DropDownListFor(model => model.IpoId, new SelectList(Model.IpoList, "Value", "Text", Model.IpoId), "--انتخاب کنید--", new {@class = "chzn-select chzn-rtl", @onchange = "IpoFilterOnChange();" })]</p>

Body:
Is there any event available for Dropdownlist like onChange, etc. in MVC4? Do we have to use Javascript/jQuery in order to make some manipulations like DropwowlistSelectedItemChanged, etc? Or there is a way only using the Razor or MVC4 features?

On the other hand, could you please give me some examples how can I retrieve data and change a label's text with this data according to a Dropdownlist Selected Value? For example when selecting a City from Dropdownlist, I want to get an address data from database by using the selected city id and then show retrieved address on a label. I would be appreciated if you clarify me about the issue above and give me an example to achieve this.

Controller:

private void PopulateMeetingsDropDownList(object selectedMeetings = null)
    {
        var meetingsQuery = repository.Meetings
            .Join(repository.Cities, m => m.MeetingCityId, c => c.CityID,
                (m, c) => new
                {
                    CityID = c.CityID,
                    CityName = c.CityName,
                    MeetingDate = m.MeetingStartDate
                }
            )
            .OrderBy(x => x.CityID)
            .AsEnumerable()
            .Select(
                i => new
                {
                    CityID = i.CityID,
                    DisplayValue = string.Format(
                        "{0} ({1:dd MMMM yyyy})",
                        i.CityName, i.MeetingDate)
                }
            ).ToList();
        ViewData["MeetingId"] = new SelectList(meetingsQuery, "CityID", "DisplayValue", selectedMeetings);
    }

View:

Meeting
@Html.DropDownListFor(m => m.MeetingId, ViewData["MeetingId"] as SelectList,"---- Select ----", new { name = "meetingId", id = "meetingId"})

Body:
You must use onchange property in a new {} side of declaring class property like this example

[@Html.DropDownListFor(model => model.IpoId, new SelectList(Model.IpoList, "Value", "Text", Model.IpoId), "--انتخاب کنید--", new {@class = "chzn-select chzn-rtl", @onchange = "IpoFilterOnChange();" })]


问:
how to return number as float number es6
Well, im trying to return all my number in a specific format

```<code>Number(parseFloat(number).toFixed(fractionalDigits || 2))
</code>```

this  works fine but in some cases fails,  here are some result

1.111 returns "1.11" and after converting it to number it will be returned 1.11
 as float which is right,
but 2.2 returns "2.20" and after converting it to number it will be 2.2  i need it to be 2.20 as float

100 returns "100.00" because of toFixed Function and after converting it to number it back to 100 i need it 100.00 but as float

how can i do that ?

答:
You can't.

Floats are numeric values, and there is no numerical difference between 2.2 and 2.20.

When outputting a float, it is converted to a string for display, and that will be the number in its simplest form. That is, 2.2, since the trailing 0 has no significance.

You wouldn't want 00000002.20000000, would you? Leading zeroes are just as useless.

If you want trailing zeroes to be displayed, use toFixed(). That's what the function is for. What you have right now is converting some arbitrary input (which for all we know is already numerical) into a float, then from a float to a string with a fixed number of decimal places, then back to a float again. All you've achieved is to truncate the number.

Body:
Well, im trying to return all my number in a specific format

Number(parseFloat(number).toFixed(fractionalDigits || 2))

this  works fine but in some cases fails,  here are some result

1.111 returns "1.11" and after converting it to number it will be returned 1.11
 as float which is right,
but 2.2 returns "2.20" and after converting it to number it will be 2.2  i need it to be 2.20 as float

100 returns "100.00" because of toFixed Function and after converting it to number it back to 100 i need it 100.00 but as float

how can i do that ?


问:
Fallback Route in ASP MVC if action doesn't exist
The default route in MVC {controller}/{action}/{id} is for the most part quite helpful as is being able to set a default if the incoming url doesn't include a parameter but is there also a way to specify a default action for when an action doesn't exist on a controller?

What I want to achieve is being able to have controllers with several specific actions and then its own catchall which uses the url to grab content from a basic CMS.

For example a products controller would be something like:

```<code>public class ProductsController: Controller{
    public ActionResult ProductInfo(int id){...}
    public ActionResult AddProduct(){...}
    public ActionResult ContentFromCms(string url){...}
}
</code>```

Where the default route would handle /Products/ProductInfo/54 etc but a request url of /Products/Suppliers/Acme would return ContentFromCms("Suppliers/Acme"); (sending the url as a parameter would be nicer but not needed and a parameterless method where I get it from Request would be fine).

Currently I can think of two possible ways to achieve this, either:

Create a new constraint which reflects over a controller to see if it does have an action of a given name and use this in the {controller}/{action}/{id} route thus allowing me to have a more general catchall like {controller}/{*url}.

Override HandleUnknownAction on the controller.

The first approach seems like it would be quite a roundabout way of checking this while for the second I don't know the internals of MVC and Routing well enough to know how to proceed.

Update

There's not been any replies but I thought I'd leave my solution incase anyone finds this in future or for people to suggest improvements/better ways

For the controllers I that wanted to have their own catchall I gave them an interface

```<code>interface IHasDefaultController
{
    public string DefaultRouteName { get; }
    System.Web.Mvc.ActionResult DefaultAction();
}
</code>```

I then derived from the ControllerActionInvoker and overrode FindAction. This calls the base FindAction then, if the base returns null and the controller impliments the interface I call FindAction again with the default actionname.

```<code>protected override ActionDescriptor FindAction(ControllerContext controllerContext, ControllerDescriptor controllerDescriptor, string actionName)
    {
        ActionDescriptor foundAction = base.FindAction(controllerContext, controllerDescriptor, actionName);
        if (foundAction == null && controllerDescriptor.ControllerType.GetInterface("Kingsweb.Controllers.IWikiController") != null)
        {
            foundAction = base.FindAction(controllerContext, controllerDescriptor, "WikiPage");
        }
        return foundAction;
    }
</code>```

As I also want parameters from the routing I also replace the RouteData at the start of the default Actionresult on the controller

```<code>ControllerContext.RouteData = Url.RouteCollection[DefaultRouteName].GetRouteData(HttpContext);
</code>```

答:
You approach is quite fine. As a side-note:

replace

```<code>controllerDescriptor.ControllerType.GetInterface("Kingsweb.Controllers.IWikiController") != null
</code>```

with

```<code>typeof(Kingsweb.Controllers.IWikiController).IsAssignableFrom(controllerDescriptor.ControllerType)
</code>```

this is more strongly-typed way then passing in the name of the interface via string: what if you change the namespace tomorrow?..

Body:
The default route in MVC {controller}/{action}/{id} is for the most part quite helpful as is being able to set a default if the incoming url doesn't include a parameter but is there also a way to specify a default action for when an action doesn't exist on a controller?

What I want to achieve is being able to have controllers with several specific actions and then its own catchall which uses the url to grab content from a basic CMS.

For example a products controller would be something like:

public class ProductsController: Controller{
    public ActionResult ProductInfo(int id){...}
    public ActionResult AddProduct(){...}
    public ActionResult ContentFromCms(string url){...}
}

Where the default route would handle /Products/ProductInfo/54 etc but a request url of /Products/Suppliers/Acme would return ContentFromCms("Suppliers/Acme"); (sending the url as a parameter would be nicer but not needed and a parameterless method where I get it from Request would be fine).

Currently I can think of two possible ways to achieve this, either:

Create a new constraint which reflects over a controller to see if it does have an action of a given name and use this in the {controller}/{action}/{id} route thus allowing me to have a more general catchall like {controller}/{*url}.

Override HandleUnknownAction on the controller.

The first approach seems like it would be quite a roundabout way of checking this while for the second I don't know the internals of MVC and Routing well enough to know how to proceed.

Update

There's not been any replies but I thought I'd leave my solution incase anyone finds this in future or for people to suggest improvements/better ways

For the controllers I that wanted to have their own catchall I gave them an interface

interface IHasDefaultController
{
    public string DefaultRouteName { get; }
    System.Web.Mvc.ActionResult DefaultAction();
}

I then derived from the ControllerActionInvoker and overrode FindAction. This calls the base FindAction then, if the base returns null and the controller impliments the interface I call FindAction again with the default actionname.

protected override ActionDescriptor FindAction(ControllerContext controllerContext, ControllerDescriptor controllerDescriptor, string actionName)
    {
        ActionDescriptor foundAction = base.FindAction(controllerContext, controllerDescriptor, actionName);
        if (foundAction == null && controllerDescriptor.ControllerType.GetInterface("Kingsweb.Controllers.IWikiController") != null)
        {
            foundAction = base.FindAction(controllerContext, controllerDescriptor, "WikiPage");
        }
        return foundAction;
    }

As I also want parameters from the routing I also replace the RouteData at the start of the default Actionresult on the controller

ControllerContext.RouteData = Url.RouteCollection[DefaultRouteName].GetRouteData(HttpContext);

Body:
You approach is quite fine. As a side-note:

replace

controllerDescriptor.ControllerType.GetInterface("Kingsweb.Controllers.IWikiController") != null

with

typeof(Kingsweb.Controllers.IWikiController).IsAssignableFrom(controllerDescriptor.ControllerType)

this is more strongly-typed way then passing in the name of the interface via string: what if you change the namespace tomorrow?..


问:
How to read if a checkbox is checked in PHP?
How to read if a checkbox is checked in PHP?</p>

答:
I've been using this trick for several years and it works perfectly without any problem for checked/unchecked checkbox status while using with PHP and Database.

HTML Code: (for Add Page)

```<code><input name="status" type="checkbox" value="1" checked>
</code>```

Hint: remove checked if you want to show it as unchecked by default

HTML Code: (for Edit Page)

```<code><input name="status" type="checkbox" value="1"
<?php if ($row['status'] == 1) { echo "checked='checked'"; } ?>>
</code>```

PHP Code: (use for Add/Edit pages)

```<code>$status = $_POST['status'];
if ($status == 1) {
$status = 1;
} else {
$status = 0;
}
</code>```

Hint: There will always be empty value unless user checked it. So, we already have PHP code to catch it else keep the value to 0. Then, simply use the $status variable for database.

Body:
I've been using this trick for several years and it works perfectly without any problem for checked/unchecked checkbox status while using with PHP and Database.

HTML Code: (for Add Page)

<input name="status" type="checkbox" value="1" checked>

Hint: remove checked if you want to show it as unchecked by default

HTML Code: (for Edit Page)

<input name="status" type="checkbox" value="1"
<?php if ($row['status'] == 1) { echo "checked='checked'"; } ?>>

PHP Code: (use for Add/Edit pages)

$status = $_POST['status'];
if ($status == 1) {
$status = 1;
} else {
$status = 0;
}

Hint: There will always be empty value unless user checked it. So, we already have PHP code to catch it else keep the value to 0. Then, simply use the $status variable for database.


问:
How to: Google marker url open in a new tab
I want to make my map marker opening the map in the new tab. Dou you have any advices?

```<code>var map = $that.data('googleMap');

                            google.maps.event.addListener(marker, 'click',
function() {
                                infowindow.open(map, marker);
                            });
                        } else if(params.url) {
                            google.maps.event.addListener(marker, 'click',
function() {
                                document.location = params.url;
                            });
                        }
</code>```

In footer.tpl I have this:

```<code>$("#mapContact").addMarker({
      coords: [49.004674, 14.770050],
      icon: '/themes/organie4/img/dorado/contact/location-pin.png',
      url: 'https://www.google.com/maps/place/Husova+75,+Třeboň+I,+379+01+Třeboň/'
    });
</code>```

Thank you!

答:
With something like this :

```<code>var map = ... // Map declaration

var marker = new google.maps.Marker({
    position: {lat: 49.004674, lng: 14.770050},
    map: map,
    icon: '/themes/organie4/img/dorado/contact/location-pin.png',
    url: 'https://www.google.com/maps/place/Husova+75,+Třeboň+I,+379+01+Třeboň/'
});

var infowindow = new google.maps.InfoWindow({
    content: "Some text"
});

marker.addListener('click', function() {
    if (this.url) {
        document.location = this.url;
        // Or like this if you want a new tab : window.open(this.url, '_blank');
    } else {
        infowindow.open(map, this);
    }
});
</code>```

I hope this will help you.

Edit :
1)

```<code>    google.maps.event.addListener(marker, 'click', function() {
       infowindow.open(map, marker);
    });
} else if(params.url) {
    google.maps.event.addListener(marker, 'click', function() {
        document.location = params.url;
    });
}
</code>```

Is replace by :

```<code>marker.addListener('click', function() {
    if (this.url) {
        document.location = this.url;
        // Or like this if you want a new tab : window.open(this.url, '_blank');
    } else {
        infowindow.open(map, this);
    }
});
</code>```

2)

```<code>$("#mapContact").addMarker({
    coords: [49.004674, 14.770050],
    icon: '/themes/organie4/img/dorado/contact/location-pin.png',
    url: 'https://www.google.com/maps/place/Husova+75,+Třeboň+I,+379+01+Třeboň/'
});
</code>```

Is equivalent of (but with a "marker" variable) :

```<code>var marker = new google.maps.Marker({
    position: {lat: 49.004674, lng: 14.770050},
    map: map,
    icon: '/themes/organie4/img/dorado/contact/location-pin.png',
    url: 'https://www.google.com/maps/place/Husova+75,+Třeboň+I,+379+01+Třeboň/'
});
</code>```

3)

I don't know what is that :

```<code>var map = $that.data('googleMap');
</code>```

Here's an example of map declaration :

```<code>var map = new google.maps.Map(document.getElementById('map'), {
    center: {lat: 49.004674, lng: 14.770050},
    zoom: 7
});
</code>```

4)

I don't know where is your "infowindow" declaration but here's a simple example :

```<code>var infowindow = new google.maps.InfoWindow({
    content: "Some text"
});
</code>```

Body:
I want to make my map marker opening the map in the new tab. Dou you have any advices?

var map = $that.data('googleMap');

                            google.maps.event.addListener(marker, 'click',
function() {
                                infowindow.open(map, marker);
                            });
                        } else if(params.url) {
                            google.maps.event.addListener(marker, 'click',
function() {
                                document.location = params.url;
                            });
                        }

In footer.tpl I have this:

$("#mapContact").addMarker({
      coords: [49.004674, 14.770050],
      icon: '/themes/organie4/img/dorado/contact/location-pin.png',
      url: 'https://www.google.com/maps/place/Husova+75,+Třeboň+I,+379+01+Třeboň/'
    });

Thank you!

Body:
With something like this :

var map = ... // Map declaration

var marker = new google.maps.Marker({
    position: {lat: 49.004674, lng: 14.770050},
    map: map,
    icon: '/themes/organie4/img/dorado/contact/location-pin.png',
    url: 'https://www.google.com/maps/place/Husova+75,+Třeboň+I,+379+01+Třeboň/'
});

var infowindow = new google.maps.InfoWindow({
    content: "Some text"
});

marker.addListener('click', function() {
    if (this.url) {
        document.location = this.url;
        // Or like this if you want a new tab : window.open(this.url, '_blank');
    } else {
        infowindow.open(map, this);
    }
});

I hope this will help you.

Edit :
1)

    google.maps.event.addListener(marker, 'click', function() {
       infowindow.open(map, marker);
    });
} else if(params.url) {
    google.maps.event.addListener(marker, 'click', function() {
        document.location = params.url;
    });
}

Is replace by :

marker.addListener('click', function() {
    if (this.url) {
        document.location = this.url;
        // Or like this if you want a new tab : window.open(this.url, '_blank');
    } else {
        infowindow.open(map, this);
    }
});

2)

$("#mapContact").addMarker({
    coords: [49.004674, 14.770050],
    icon: '/themes/organie4/img/dorado/contact/location-pin.png',
    url: 'https://www.google.com/maps/place/Husova+75,+Třeboň+I,+379+01+Třeboň/'
});

Is equivalent of (but with a "marker" variable) :

var marker = new google.maps.Marker({
    position: {lat: 49.004674, lng: 14.770050},
    map: map,
    icon: '/themes/organie4/img/dorado/contact/location-pin.png',
    url: 'https://www.google.com/maps/place/Husova+75,+Třeboň+I,+379+01+Třeboň/'
});

3)

I don't know what is that :

var map = $that.data('googleMap');

Here's an example of map declaration :

var map = new google.maps.Map(document.getElementById('map'), {
    center: {lat: 49.004674, lng: 14.770050},
    zoom: 7
});

4)

I don't know where is your "infowindow" declaration but here's a simple example :

var infowindow = new google.maps.InfoWindow({
    content: "Some text"
});


问:
Cannot load module coreData as CoreData
I get this error on my app delegate where I import CoreData. From what I've read, it is because I named a project coreData. However I changed the name of the project, then deleted it, and I've deleted everything inside /Library/Developer/Xcode/DerivedData. If I create a project with CoreData, I get the same error.
I have also deleted the contents of /var/folders/

Any info on how to fix this?

(Xcode 7.2)

答: Maybe you should create new project with CoreData, because i think you forgot to turn on core data module.</p>

Title: Cannot load module coreData as CoreData