问:
Removing the file extension from URLs, like .php or .html
I want to remove my any extension of file from URLs of my website.

For example: www.example.ml/dash/logins/sign.php

to: www.example/dash/logins/sign/

I had done a lot of googling, but none of the answers worked for me.
I think it didn't work, because in the logins folder I have not a single file.

There are many other files, like index.php, sign.php, etc. Do I have to keep each file in a separate folder or sing.php can change to sign/.  Also, what would happen to this:

```<code>sign.php?usercode=1
</code>```

Will it get converted to

```<code>sign/usercode=1
</code>```

?

I already have some code present in .htaccess, so please give your answer after referring this code.

```<code>php_value display_errors Off
php_flag magic_quotes 1
php_flag magic_quotes_gpc 1
php_value mbstring.http_input auto
php_value date.timezone America/New_York

Options -Indexes

RewriteEngine On

RewriteCond %{HTTP_HOST} !^www.example.ml$ [NC]

RewriteRule ^(.*)$ https://www.example.ml/$1 [L,R=301]
</code>```

答:
Add this line to your .htaccess file:</p>

```<code>RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ([^\.]+)$ $1.php [NC,L]
</code>```

Body:
I want to remove my any extension of file from URLs of my website.

For example: www.example.ml/dash/logins/sign.php

to: www.example/dash/logins/sign/

I had done a lot of googling, but none of the answers worked for me.
I think it didn't work, because in the logins folder I have not a single file.

There are many other files, like index.php, sign.php, etc. Do I have to keep each file in a separate folder or sing.php can change to sign/.  Also, what would happen to this:

sign.php?usercode=1

Will it get converted to

sign/usercode=1

?

I already have some code present in .htaccess, so please give your answer after referring this code.

php_value display_errors Off
php_flag magic_quotes 1
php_flag magic_quotes_gpc 1
php_value mbstring.http_input auto
php_value date.timezone America/New_York

Options -Indexes

RewriteEngine On

RewriteCond %{HTTP_HOST} !^www.example.ml$ [NC]

RewriteRule ^(.*)$ https://www.example.ml/$1 [L,R=301]

Body:
Add this line to your .htaccess file:

RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ([^\.]+)$ $1.php [NC,L]


来源: stackexchange

问:
Jquery document.ready is not responding
The document.ready function is not responding while my page load.
And also i am facing problem with .submit function. Please help.
Please help me to rewrite this code.
I just want to design a form in php to check whether the given email id is already present in the database or not using jquery ajax
Please help .... ! I am getting late in my school project.

```<code> $(document).ready(function(){
                alert("Working..");
                $("#userSubmit").submit(function(){
                    alert("Working ..");
                    var email=document.getElementById("userEamil").value;
                    $.ajax({
                        type:'POST',
                        data:"SELECT * FROM user WHERE userEmail='"+email+"'",
                        url:'common1.php',
                        success:function(data)
                        {
                            $result=$.parseJSON($data);
                            alert($result);
                            return false;
                        },
                        error:function(data)
                        {
                            alert(data);
                            return false;
                        }
                    });
                });
            });
</code>```

答:
```<code><script>
   $(document).ready(function() {
      //alert("Working..");
      $("#userSubmit").submit(function() {
           //alert("Working ..");
                  var email = $(this).closest("form").find("input[name='emailbox']").val();
                  console.log(email);
                  $.ajax({
                    type: 'POST',
                    data: "SELECT * FROM user WHERE userEmail='" + email + "'",
                    url: 'common1.php',
                    success: function(data) {
                      $result = $.parseJSON($data);
                      alert($result);
                      return false;
                    },
                    error: function(data) {
                      alert(data);
                      return false;
                    }
                  });
                });
              });
            </script>

<html>
    <body>
        <form id="userSubmit">
            <input type="email" id="userEmail" name="emailbox">
            <input type="submit" value="Submit">
        </form>
    </body>
</html>
</code>```

ContentLicense: CC BY-SA 3.0

Title: Jquery document.ready is not responding

Body:
The document.ready function is not responding while my page load.
And also i am facing problem with .submit function. Please help.
Please help me to rewrite this code.
I just want to design a form in php to check whether the given email id is already present in the database or not using jquery ajax
Please help .... ! I am getting late in my school project.

 $(document).ready(function(){
                alert("Working..");
                $("#userSubmit").submit(function(){
                    alert("Working ..");
                    var email=document.getElementById("userEamil").value;
                    $.ajax({
                        type:'POST',
                        data:"SELECT * FROM user WHERE userEmail='"+email+"'",
                        url:'common1.php',
                        success:function(data)
                        {
                            $result=$.parseJSON($data);
                            alert($result);
                            return false;
                        },
                        error:function(data)
                        {
                            alert(data);
                            return false;
                        }
                    });
                });
            });


问:
C# how to load a form with marquee progress bar?
I created a loadingForm with only a progress bar with marquee style. In my mainForm I'm trying to do this:

```<code>//before downloading
loadingForm lf = new loadingForm();
lf.Show();
//start downloading
//finishdownloading
lf.Close();
</code>```

The loadingForm was shown but the progress bar didn't appear, and the form looked like it was crash. after finishing downloading, the loadingForm was closed and my app continued to run normally. In loadingForm I only have:

```<code>void loadingForm_Load(object sender, EventArgs e)
{
     progressbar1.visible = true;
}
</code>```

I already set progressbar1 style to marquee in loadingForm.design. How do I fix this? thanks for your help in advance.

答: This is most likely because the download and the form with the progress bar are run on the same thread. You could use a BackgroundWorker to perform the download in a different thread than the form.</p>

ContentLicense: CC BY-SA 2.5

Body:
I created a loadingForm with only a progress bar with marquee style. In my mainForm I'm trying to do this:

//before downloading
loadingForm lf = new loadingForm();
lf.Show();
//start downloading
//finishdownloading
lf.Close();

The loadingForm was shown but the progress bar didn't appear, and the form looked like it was crash. after finishing downloading, the loadingForm was closed and my app continued to run normally. In loadingForm I only have:

void loadingForm_Load(object sender, EventArgs e)
{
     progressbar1.visible = true;
}

I already set progressbar1 style to marquee in loadingForm.design. How do I fix this? thanks for your help in advance.


问:
clicking text should click the radio button in HTML
I have this radio button,

```<code> <form class="w3-container w3-card-4">
  <h2>Radio Buttons</h2>
  <p>
  <input class="w3-radio" type="radio" name="gender"  value="male" checked>
  <label >Male</label></p>
  <p>
  <input class="w3-radio" type="radio" name="gender"  value="female">
  <label >Female</label></p>
  <p>
  <input class="w3-radio" type="radio" name="gender" value="" disabled>
   <label>Don't know (Disabled)</label></p>
 </form>
</code>```

The problem is when I click on the label text the radio button is not selected. is there a way to fix this?

答:
Your form inputs need an ID and your labels need to reference that.

So for example:

```<code><input class="w3-radio" type="radio" name="gender"  value="male" checked id="gender-male">
<label for="gender-male">Male</label></p>
</code>```

From the spec

The for attribute may be specified to indicate a form control with which the caption is to be associated. If the attribute is specified, the attribute's value must be the ID of a labelable element in the same Document as the label element. If the attribute is specified and there is an element in the Document whose ID is equal to the value of the for attribute, and the first such element is a labelable element, then that element is the label element's labeled control.

Body:
I have this radio button,

 <form class="w3-container w3-card-4">

Radio Buttons

  <input class="w3-radio" type="radio" name="gender"  value="male" checked>
  Male

  <input class="w3-radio" type="radio" name="gender"  value="female">
  Female

  <input class="w3-radio" type="radio" name="gender" value="" disabled>
   Don't know (Disabled)

 </form>

The problem is when I click on the label text the radio button is not selected. is there a way to fix this?

Body:
Your form inputs need an ID and your labels need to reference that.

So for example:

<input class="w3-radio" type="radio" name="gender"  value="male" checked id="gender-male">
<label for="gender-male">Male</label></p>

From the spec

The for attribute may be specified to indicate a form control with which the caption is to be associated. If the attribute is specified, the attribute's value must be the ID of a labelable element in the same Document as the label element. If the attribute is specified and there is an element in the Document whose ID is equal to the value of the for attribute, and the first such element is a labelable element, then that element is the label element's labeled control.


问:
Why does the Node.JS community generally favor NoSQL over relational databases?
Why is MongoDB usually used in conjunction with NodeJS?, Is it just coincidental or are there good engineering reasons behind this combination?</p>

答:
There is no direct relation between Node.js and Mongodb. MongoDB is a
document based database which will give data as a JSON directly and it is schema less.To develop the rapid applications now a days MEAN stack apps are very famous.Actually Node.js is not limited to MongoDB it can be connected with different databases.</p>


答:
Just add id for the radio buttons and for keyword near label boxes.

```<code>  <form class="w3-container w3-card-4">
   <h2>Radio Buttons</h2>
   <p>
   <input class="w3-radio" type="radio" name="gender" id="m1" value="male" checked>
   <label for="m1">Male</label></p>
   <p>
   <input class="w3-radio" type="radio" name="gender" id="m2" value="female">
   <label for="m2">Female</label></p>
   <p>
   <input class="w3-radio" type="radio" name="gender" value="" disabled>
   <label>Don't know (Disabled)</label></p>
 </form>
</code>```

Now you click the text label the radio button gets selected.

Title: clicking text should click the radio button in HTML

Body:
Just add id for the radio buttons and for keyword near label boxes.

  <form class="w3-container w3-card-4">
   <h2>Radio Buttons</h2>
   <p>
   <input class="w3-radio" type="radio" name="gender" id="m1" value="male" checked>
   <label for="m1">Male</label></p>
   <p>
   <input class="w3-radio" type="radio" name="gender" id="m2" value="female">
   <label for="m2">Female</label></p>
   <p>
   <input class="w3-radio" type="radio" name="gender" value="" disabled>
   <label>Don't know (Disabled)</label></p>
 </form>

Now you click the text label the radio button gets selected.


问:
JSLint warning in Brackets how to fix it for running javascript?
I trying to write javascript code on Brackets IDE. But it shows error every time I run the code. JSLint problem

```<code>console.log(a);
</code>```

Says that 'console' was used before it was defined. console.log(a);
I do not know how to fix it. Please can somebody help me fix this issue with Brackets.

答:
If you use

/*global document, window, alert, console, require*/

at the top of your file, it fixes this issue.

Body:
I trying to write javascript code on Brackets IDE. But it shows error every time I run the code. JSLint problem

console.log(a);

Says that 'console' was used before it was defined. console.log(a);
I do not know how to fix it. Please can somebody help me fix this issue with Brackets.


问:
docker nginx appear "502".1 upstream server temporarily disabled while connecting to upstream
I use nginx in the docker,this is my nginx configure

```<code>server {    listen  80;     server_name saber;

    location / {
       root /usr/share/nginx;
       index index.html;
}

    location /saber {
        proxy_pass http://localhost:8080;
        proxy_redirect off;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_buffer_size 4k;
        proxy_buffers 4 32k;
        proxy_busy_buffers_size 64k;
        proxy_connect_timeout 90;
    }

}
</code>```

when I use "http://localhost/saber/blog/getBlog.do" in browser ，browser give me a error with "502".
and nginx`s error.log have new.

```<code>2017/07/09 05:16:18 [warn] 5#5: *1 upstream server temporarily disabled while connecting to upstream, client: 172.17.0.1, server: saber, request: "GET /saber/blog/getBlog.do HTTP/1.1", upstream: "http://127.0.0.1:8080/saber/blog/getBlog.do", host: "localhost"
</code>```

I can promise the "http://127.0.0.1:8080/saber/blog/getBlog.do" have response success in browser.
  I try search answer in other question,i find a answer is "/usr/sbin/setsebool httpd_can_network_connect true",this is question url "nginx proxy server localhost permission denied",but I use the docker in win10,the nginx container dont hava setsebool,because the container dont find SELinux.
    This all,Thank you in advance.

答: Localhost inside each container (like the nginx container) is different from localhost outside on your container. Each container gets its own networking namespace by default. Instead of pointing to localhost, you need to place your containers on the same docker network (not the default bridge network) and use the container or service name with Docker's built in DNS to connect. The target port will also be the container port, not the published port on your host.</p>

Body:
I use nginx in the docker,this is my nginx configure

server {    listen  80;     server_name saber;

    location / {
       root /usr/share/nginx;
       index index.html;
}

    location /saber {
        proxy_pass http://localhost:8080;
        proxy_redirect off;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_buffer_size 4k;
        proxy_buffers 4 32k;
        proxy_busy_buffers_size 64k;
        proxy_connect_timeout 90;
    }

}

when I use "http://localhost/saber/blog/getBlog.do" in browser ，browser give me a error with "502".
and nginx`s error.log have new.

2017/07/09 05:16:18 [warn] 5#5: *1 upstream server temporarily disabled while connecting to upstream, client: 172.17.0.1, server: saber, request: "GET /saber/blog/getBlog.do HTTP/1.1", upstream: "http://127.0.0.1:8080/saber/blog/getBlog.do", host: "localhost"

I can promise the "http://127.0.0.1:8080/saber/blog/getBlog.do" have response success in browser.
  I try search answer in other question,i find a answer is "/usr/sbin/setsebool httpd_can_network_connect true",this is question url "nginx proxy server localhost permission denied",but I use the docker in win10,the nginx container dont hava setsebool,because the container dont find SELinux.
    This all,Thank you in advance.


问:
iOS Colors Incorrect When Saving Animated Gif
I am having this very strange issue. I am creating animated gifs from UIImages and most of the time they come out correct. However when I start to get into larger size images my colors start to disappear. For example if I do a 4 frame 32 x 32 pixel image with no more than 10 colors no issue. If I scale the same image up to 832 x 832 I lose a pink color and my brown turns green.

@1x 32 x 32

@10x 320 x 320

@26x 832 x 832

Here is the code I use to create the gif...

```<code>var kFrameCount = 0

for smdLayer in drawingToUse!.layers{
    if !smdLayer.hidden {
        kFrameCount += 1
    }
}

let loopingProperty = [String(kCGImagePropertyGIFLoopCount): 0]
let fileProperties: [String: AnyObject] = [String(kCGImagePropertyGIFDictionary): loopingProperty as AnyObject];

let frameProperty = [String(kCGImagePropertyGIFDelayTime):  Float(speedLabel.text!)!]
let frameProperties: [String: AnyObject] = [String(kCGImagePropertyGIFDictionary): frameProperty as AnyObject];

let documentsDirectoryPath = "file://\(NSTemporaryDirectory())"

if let documentsDirectoryURL = URL(string: documentsDirectoryPath){

    let fileURL = documentsDirectoryURL.appendingPathComponent("\(drawing.name)\(getScaleString()).gif")
    let destination = CGImageDestinationCreateWithURL(fileURL as CFURL, kUTTypeGIF, kFrameCount, nil)!

    CGImageDestinationSetProperties(destination, fileProperties as CFDictionary);

    for smdLayer in drawingToUse!.layers{

        if !smdLayer.hidden{

            let image = UIImage(smdLayer: smdLayer, alphaBlend: useAlphaLayers, backgroundColor: backgroundColorButton.backgroundColor!, scale: scale)
            CGImageDestinationAddImage(destination, image.cgImage!, frameProperties as CFDictionary)
        }
    }

    if (!CGImageDestinationFinalize(destination)) {
        print("failed to finalize image destination")
    }
}
</code>```

I have put in a break point right before I call CGImageDestinationAddImage(destination, image.cgImage!, frameProperties as CFDictionary) and the image is perfectly fine with the correct colors. I hope someone out there knows what I am missing.

Update

Here is a sample project. Note that although it isn't animated in the preview it is saving an animated gif and I log out the location of the image in the console.

https://www.dropbox.com/s/pb52awaj8w3amyz/gifTest.zip?dl=0

答:
It seems that turning off the global color map fixes the problem:

```<code>let loopingProperty: [String: AnyObject] = [
    kCGImagePropertyGIFLoopCount as String: 0 as NSNumber,
    kCGImagePropertyGIFHasGlobalColorMap as String: false as NSNumber
]
</code>```

Note that unlike PNGs, GIFs can use only a 256 color map, without transparency. For animated GIFs there can be either a global or a per-frame color map.

Unfortunately, Core Graphics does not allow us to work with color maps directly, therefore there is some automatic color conversion when the GIF is encoded.

It seems that turning off the global color map is all what is needed. Also setting up color map explicitly for every frame using kCGImagePropertyGIFImageColorMap would probably work too.

Since this seems not to work reliably, let's create our own color map for every frame:

```<code>struct Color : Hashable {
    let red: UInt8
    let green: UInt8
    let blue: UInt8

    var hashValue: Int {
        return Int(red) + Int(green) + Int(blue)
    }

    public static func ==(lhs: Color, rhs: Color) -> Bool {
        return [lhs.red, lhs.green, lhs.blue] == [rhs.red, rhs.green, rhs.blue]
    }
}

struct ColorMap {
    var colors = Set<Color>()

    var exported: Data {
        let data = Array(colors)
            .map { [$0.red, $0.green, $0.blue] }
            .joined()

        return Data(bytes: Array(data))
    }
}
</code>```

Now let's update our methods:

```<code>func getScaledImages(_ scale: Int) -> [(CGImage, ColorMap)] {
    var sourceImages = [UIImage]()
    var result: [(CGImage, ColorMap)] = []

...

    var colorMap = ColorMap()
    let pixelData = imageRef.dataProvider!.data
    let rawData: UnsafePointer<UInt8> = CFDataGetBytePtr(pixelData)

    for y in 0 ..< imageRef.height{
        for _ in 0 ..< scale {
            for x in 0 ..< imageRef.width{
                 let offset = y * imageRef.width * 4 + x * 4

                 let color = Color(red: rawData[offset], green: rawData[offset + 1], blue: rawData[offset + 2])
                 colorMap.colors.insert(color)

                 for _ in 0 ..< scale {
                     pixelPointer[byteIndex] = rawData[offset]
                     pixelPointer[byteIndex+1] = rawData[offset+1]
                     pixelPointer[byteIndex+2] = rawData[offset+2]
                     pixelPointer[byteIndex+3] = rawData[offset+3]

                     byteIndex += 4
                }
            }
        }
    }

    let cgImage = context.makeImage()!
    result.append((cgImage, colorMap))
</code>```

and

```<code>func createAnimatedGifFromImages(_ images: [(CGImage, ColorMap)]) -> URL {

...

    for (image, colorMap) in images {
        let frameProperties: [String: AnyObject] = [
            String(kCGImagePropertyGIFDelayTime): 0.2 as NSNumber,
            String(kCGImagePropertyGIFImageColorMap): colorMap.exported as NSData
        ]

        let properties: [String: AnyObject] = [
            String(kCGImagePropertyGIFDictionary): frameProperties as AnyObject
        ];

        CGImageDestinationAddImage(destination, image, properties as CFDictionary);
    }
</code>```

Of course, this will work only if the number of colors is less than 256. I would really recommend a custom GIF library that can handle the color conversion correctly.

Body:
I am having this very strange issue. I am creating animated gifs from UIImages and most of the time they come out correct. However when I start to get into larger size images my colors start to disappear. For example if I do a 4 frame 32 x 32 pixel image with no more than 10 colors no issue. If I scale the same image up to 832 x 832 I lose a pink color and my brown turns green.

@1x 32 x 32

@10x 320 x 320

@26x 832 x 832

Here is the code I use to create the gif...

var kFrameCount = 0

for smdLayer in drawingToUse!.layers{
    if !smdLayer.hidden {
        kFrameCount += 1
    }
}

let loopingProperty = [String(kCGImagePropertyGIFLoopCount): 0]
let fileProperties: [String: AnyObject] = [String(kCGImagePropertyGIFDictionary): loopingProperty as AnyObject];

let frameProperty = [String(kCGImagePropertyGIFDelayTime):  Float(speedLabel.text!)!]
let frameProperties: [String: AnyObject] = [String(kCGImagePropertyGIFDictionary): frameProperty as AnyObject];

let documentsDirectoryPath = "file://\(NSTemporaryDirectory())"

if let documentsDirectoryURL = URL(string: documentsDirectoryPath){

    let fileURL = documentsDirectoryURL.appendingPathComponent("\(drawing.name)\(getScaleString()).gif")
    let destination = CGImageDestinationCreateWithURL(fileURL as CFURL, kUTTypeGIF, kFrameCount, nil)!

    CGImageDestinationSetProperties(destination, fileProperties as CFDictionary);

    for smdLayer in drawingToUse!.layers{

        if !smdLayer.hidden{

            let image = UIImage(smdLayer: smdLayer, alphaBlend: useAlphaLayers, backgroundColor: backgroundColorButton.backgroundColor!, scale: scale)
            CGImageDestinationAddImage(destination, image.cgImage!, frameProperties as CFDictionary)
        }
    }

    if (!CGImageDestinationFinalize(destination)) {
        print("failed to finalize image destination")
    }
}

I have put in a break point right before I call CGImageDestinationAddImage(destination, image.cgImage!, frameProperties as CFDictionary) and the image is perfectly fine with the correct colors. I hope someone out there knows what I am missing.

Update

Here is a sample project. Note that although it isn't animated in the preview it is saving an animated gif and I log out the location of the image in the console.

https://www.dropbox.com/s/pb52awaj8w3amyz/gifTest.zip?dl=0

Body:
It seems that turning off the global color map fixes the problem:

let loopingProperty: [String: AnyObject] = [
    kCGImagePropertyGIFLoopCount as String: 0 as NSNumber,
    kCGImagePropertyGIFHasGlobalColorMap as String: false as NSNumber
]

Note that unlike PNGs, GIFs can use only a 256 color map, without transparency. For animated GIFs there can be either a global or a per-frame color map.

Unfortunately, Core Graphics does not allow us to work with color maps directly, therefore there is some automatic color conversion when the GIF is encoded.

It seems that turning off the global color map is all what is needed. Also setting up color map explicitly for every frame using kCGImagePropertyGIFImageColorMap would probably work too.

Since this seems not to work reliably, let's create our own color map for every frame:

struct Color : Hashable {
    let red: UInt8
    let green: UInt8
    let blue: UInt8

    var hashValue: Int {
        return Int(red) + Int(green) + Int(blue)
    }

    public static func ==(lhs: Color, rhs: Color) -> Bool {
        return [lhs.red, lhs.green, lhs.blue] == [rhs.red, rhs.green, rhs.blue]
    }
}

struct ColorMap {
    var colors = Set<Color>()

    var exported: Data {
        let data = Array(colors)
            .map { [$0.red, $0.green, $0.blue] }
            .joined()

        return Data(bytes: Array(data))
    }
}

Now let's update our methods:

func getScaledImages(_ scale: Int) -> [(CGImage, ColorMap)] {
    var sourceImages = [UIImage]()
    var result: [(CGImage, ColorMap)] = []

...

    var colorMap = ColorMap()
    let pixelData = imageRef.dataProvider!.data
    let rawData: UnsafePointer<UInt8> = CFDataGetBytePtr(pixelData)

    for y in 0 ..< imageRef.height{
        for _ in 0 ..< scale {
            for x in 0 ..< imageRef.width{
                 let offset = y * imageRef.width * 4 + x * 4

                 let color = Color(red: rawData[offset], green: rawData[offset + 1], blue: rawData[offset + 2])
                 colorMap.colors.insert(color)

                 for _ in 0 ..< scale {
                     pixelPointer[byteIndex] = rawData[offset]
                     pixelPointer[byteIndex+1] = rawData[offset+1]
                     pixelPointer[byteIndex+2] = rawData[offset+2]
                     pixelPointer[byteIndex+3] = rawData[offset+3]

                     byteIndex += 4
                }
            }
        }
    }

    let cgImage = context.makeImage()!
    result.append((cgImage, colorMap))

and

func createAnimatedGifFromImages(_ images: [(CGImage, ColorMap)]) -> URL {

...

    for (image, colorMap) in images {
        let frameProperties: [String: AnyObject] = [
            String(kCGImagePropertyGIFDelayTime): 0.2 as NSNumber,
            String(kCGImagePropertyGIFImageColorMap): colorMap.exported as NSData
        ]

        let properties: [String: AnyObject] = [
            String(kCGImagePropertyGIFDictionary): frameProperties as AnyObject
        ];

        CGImageDestinationAddImage(destination, image, properties as CFDictionary);
    }

Of course, this will work only if the number of colors is less than 256. I would really recommend a custom GIF library that can handle the color conversion correctly.


问:
Draggable overlay that can go offscreen?

I have created an overlay menu that is a rectangle.

It displays on top of everything else while active. All other apps, the home screen, etc.

If you click anywhere outside of this rectangle your click hits
whatever is visible.

If you click the red part it allows you to drag the menu around the
screen. Clicking the green part performs some function.

I have created this rectangle from inflating layout xml. The rectangle itself is a relativeLayout and the green and red parts are both imageView children.

Since I'm unable to move the relativeView off screen and since the background needs to be clickable my only solution was to calculate margins and apply them to the relative view to imitate the desired effect.

However, the code to calculate these margins is almost 50 lines and fairly complex and hard to understand at a glance if someone else needs to refactor. I can post the code but I don't believe it's relevant to the actual problem's context.

Is there a much simpler way to do this that I'm missing? Is my approach wrong?

答: I hope this simple project may help you Android Floating Widget</p>


问:
How to send json response using plumber R
I need to send response from R using plumber package in below format

```<code>{
  "status": "SUCCESS",
  "code": "200",
  "output": {
    "studentid": "1001",
    "name": "Kevin"
  }
}
</code>```

But I am getting below format

```<code>[
  "{\n  \"status\": \"SUCCESS\",\n  \"code\": \"200\",\n  \"output\": {\n    \"studentid\": \"1001\",\n    \"name\": \"Kevin\"\n  }\n}"
]
</code>```

Please help me format this json properly

My Code

```<code>#* @post /sum
addTwo <- function(){
  library(jsonlite)
  x <- list(status = "SUCCESS", code = "200",output = list(studentid = "1001", name = "Kevin"))
  output<-toJSON(x,pretty = TRUE, auto_unbox = TRUE)
  return (output)
}
</code>```

答:
Just remove the toJSON() wrapper.
Plumber already does JSON serialisation so you are doing it twice by adding a toJSON function.

This should work.

```<code> addTwo <- function(){
  x <- list(status = "SUCCESS", code = "200",output = list(studentid = "1001", name = "Kevin"))
  return (x)
}
</code>```

Body:
I need to send response from R using plumber package in below format

{
  "status": "SUCCESS",
  "code": "200",
  "output": {
    "studentid": "1001",
    "name": "Kevin"
  }
}

But I am getting below format

[
  "{\n  \"status\": \"SUCCESS\",\n  \"code\": \"200\",\n  \"output\": {\n    \"studentid\": \"1001\",\n    \"name\": \"Kevin\"\n  }\n}"
]

Please help me format this json properly

My Code

#* @post /sum
addTwo <- function(){
  library(jsonlite)
  x <- list(status = "SUCCESS", code = "200",output = list(studentid = "1001", name = "Kevin"))
  output<-toJSON(x,pretty = TRUE, auto_unbox = TRUE)
  return (output)
}

Body:
Just remove the toJSON() wrapper.
Plumber already does JSON serialisation so you are doing it twice by adding a toJSON function.

This should work.

 addTwo <- function(){
  x <- list(status = "SUCCESS", code = "200",output = list(studentid = "1001", name = "Kevin"))
  return (x)
}


问:
Remove list bullets from

Can you help me how can i delete this purple thing?
I tried to add padding 0px; in css containers but it didn't work.

screen

答:
You can add via inline style,

```<code><ul style="list-style-type: none;">
</code>```

or via your css style sheet, this will remove the bullet from all ul

```<code><style>
ul {
  list-style-type: none;
}
</style>
</code>```

if you wish to affect only a specific list, you can add an id and hide it

```<code><ul id="testul">

<style>
ul {
  list-style-type: none;
}
</style>
</code>```

You can also add the following as well to remove indentation.

```<code><style>
ul {
  padding: 0;
  margin: 0;
}
</style>
</code>```

Title: Remove list bullets from <ul>

Body:
You can add via inline style,

<ul style="list-style-type: none;">

or via your css style sheet, this will remove the bullet from all ul

<style>
ul {
  list-style-type: none;
}
</style>

if you wish to affect only a specific list, you can add an id and hide it

<ul id="testul">

<style>
ul {
  list-style-type: none;
}
</style>

You can also add the following as well to remove indentation.

<style>
ul {
  padding: 0;
  margin: 0;
}
</style>


问:
Automatic e-mail with changes in the body - VBA
I have to create a VBA to send automatic e-mails (the body of the e-mail links the recipient to a specific project that he is responsible for). The problem that I encountered is the fact that a certain recipient (i.e. placed in "TO") can be responsible for more tasks. The VBA that I am using sends emails to each task (even if the person is responsible for more). What can I do to count through recipients, if it's greater than 1 to send the e-mail which includes all of the tasks. I really need your help.</p>

```<code><PRE>Sub SendEMail()
Dim OutApp As Object
Dim OutMail As Object
Dim lastRow As Long
Dim Ebody As String
lastRow = ThisWorkbook.Worksheets("Sheet1").Cells(Rows.Count, "B").End(xlUp).Row
For i = 2 To lastRow
Ebody = "<FONT SIZE = 4 name = Arial>" & "Dear " & Cells(i, "A").Value
& "<br>" _
& "<br>" _
& "Please note that the below mentioned projectd are in scope for reporting." & "<br>" _
& "<br>" _
& Cells(i, "C").Value & " - " & Cells(i, "E").Value & "<br>" _
& "xxxxx will investigate and action your notification according to priority and to ensure public safety." & "<br>" _
& "For further information, please phone xxxxx on 6111 and quote reference number:" & "<br>" _
& "Your original report can be seen below:" & "</Font>" & "<br>" _
Set OutApp = CreateObject("Outlook.Application")
Set OutMail = OutApp.CreateItem(0)
With OutMail
.To = Cells(i, "B").Value
.Cc = Cells(i, "D").Value
.Subject = "Your Registration Code"
.HtmlBody = Ebody
.Attachments.Add "C:\Test\Document.docx"
.Attachments.Add "C:\Test\Document1.docx"
.SentOnBehalfOfName = "Financial@yahoo.com"
.Display
End With
Next
End Sub ```
</code>```

答:
```<code>Sub Emailer()
    Dim OutApp As Object
    Dim OutMail As Object
    Dim cell As Range, y, sbody
    Dim eml As Worksheet, bd As Worksheet
    Dim underlyingary, ISINarray, Accountarray, i

    Set eml = Sheets("Emailer"): Set bd = Sheets("Body"): Set OutApp = CreateObject("Outlook.Application")

    For Each y In eml.Range("A2:A" & eml.Range("A1000000").End(xlUp).Row)

    If eml.Range("F" & y.Row) <> "" Then
        underlyingary = Split(eml.Range("F" & y.Row), ",")
        Accountarray = Split(eml.Range("G" & y.Row), ",")
        ISINarray = Split(eml.Range("H" & y.Row), ",")
            For i = 0 To UBound(underlyingary)
                sbody = sbody & vbNewLine & "Underlying: " & WorksheetFunction.Proper(Trim(underlyingary(i))) & " Account Number: " & WorksheetFunction.Proper(Trim(Accountarray(i))) & " ISIN: " & WorksheetFunction.Proper(Trim(ISINarray(i))) & "<br>" & "<br>"
            Next i
    Else
            sbody = sbody & vbNewLine & "Underlying: " & WorksheetFunction.Proper(Trim(eml.Range("C" & y.Row))) & " Account Number: " & WorksheetFunction.Proper(Trim(eml.Range("D" & y.Row))) & " ISIN: " & WorksheetFunction.Proper(Trim(eml.Range("E" & y.Row))) & "<br>"
    End If

    On Error GoTo cleanup
            Set OutMail = OutApp.CreateItem(0)
            On Error Resume Next
            With OutMail
                .To = eml.Range("A" & y.Row)
                .Subject = bd.Range("B2")
                .cc = eml.Range("I" & y.Row)
                .htmlBody = bd.Range("A2") _
                    & "<br>" & "<br>" & _
                        bd.Range("A3") & _
                        Trim(eml.Range("B" & y.Row)) & _
                        bd.Range("A4") _
                    & "<br>" & "<br>" & _
                        sbody _
                    & "<br>" & _
                        bd.Range("A5") _
                    & "<br>" & "<br>" & "<li>" & _
                        bd.Range("A6").Text & "</li>" & _
                     "<br>" & "<br>" & "<li>" & _
                        bd.Range("A7").Text & "</li>" & _
                     "<br>" & "<br>" & "<li>" & _
                        bd.Range("A8").Text & "</li>" & _
                     "<br>" & "<br>" & _
                        bd.Range("A9") _
                    & "<br>" & bd.Range("A10")
                .display
            End With

            On Error GoTo 0
            Set OutMail = Nothing
    Next y
cleanup:
    Set OutApp = Nothing

End Sub
</code>```

Body:
I have to create a VBA to send automatic e-mails (the body of the e-mail links the recipient to a specific project that he is responsible for). The problem that I encountered is the fact that a certain recipient (i.e. placed in "TO") can be responsible for more tasks. The VBA that I am using sends emails to each task (even if the person is responsible for more). What can I do to count through recipients, if it's greater than 1 to send the e-mail which includes all of the tasks. I really need your help.

Sub SendEMail()
Dim OutApp As Object
Dim OutMail As Object
Dim lastRow As Long
Dim Ebody As String
lastRow = ThisWorkbook.Worksheets("Sheet1").Cells(Rows.Count, "B").End(xlUp).Row
For i = 2 To lastRow
Ebody = "" & "Dear " & Cells(i, "A").Value
& "
" _
& "
" _
& "Please note that the below mentioned projectd are in scope for reporting." & "
" _
& "
" _
& Cells(i, "C").Value & " - " & Cells(i, "E").Value & "
" _
& "xxxxx will investigate and action your notification according to priority and to ensure public safety." & "
" _
& "For further information, please phone xxxxx on 6111 and quote reference number:" & "
" _
& "Your original report can be seen below:" & "" & "
" _
Set OutApp = CreateObject("Outlook.Application")
Set OutMail = OutApp.CreateItem(0)
With OutMail
.To = Cells(i, "B").Value
.Cc = Cells(i, "D").Value
.Subject = "Your Registration Code"
.HtmlBody = Ebody
.Attachments.Add "C:\Test\Document.docx"
.Attachments.Add "C:\Test\Document1.docx"
.SentOnBehalfOfName = "Financial@yahoo.com"
.Display
End With
Next
End Sub


问:
Android Studio - Bottom navigation crash when changing between fragments
I am creating and app and so far everything was good. Today I was dealing with the data in a fragment to reach my webservice and return the json and then insert that data into my sqlite and after that show it in a listview and update the data second by second.

Everything was right until i find that if I click too fast in the bottom navigation where the items from the fragments are, it will crash the aplication while it is doing the transaction on the fragment. it only occurs when I click between that fragment and more 1 of the other 4.

So my question is, is there anyway I can deal with this problem? like if I click in another item from bottom navigation the transitions from the last item stops? if so how?

答:
I found that 'compile 'com.android.volley:volley:1.0.0'' version of volley had this error and google (or the people that made the volley) didn't update volley in google library since then.

The way to work around this was work with a non-official version:
'compile 'com.mcxiaoke.volley:library:1.0.19''

This version had this "bugs" from volley already corrected.
For the future if anyone wanna know more about this there is the link from mcxiaoke:
https://github.com/mcxiaoke/android-volley

and a link to how to use it:
https://www.thorntech.com/2016/03/parsing-json-android-using-volley-library/


问:
Is there a security risk running web apps in debug="true"?
There are plenty of performance reasons why apps shouldn't be run in debug="true" mode (good rundown from Scott Gu), but are there any attack vectors exposed by this practice? It's not a question of "should you or shouldn't you", that much is clear, it's a question of whether it introduces any specific vulnerabilities.

I'm inclined to think that the ability to remotely detect it combined with the known performance issues could lead to an exploit against service availability but I'd like something a bit more definite. Does anyone know of a specific attack that can be orchestrated against an app running debug="true"?

答: I think you should transfer all debugging operations to a custom-made console to prevent debgugging hints make attackers able to misuse vulnerabilities of you app.</p>


问:
Embed multiple view controllers in a container view
I have a base view controller which is like my "blueprint" to create more view controllers to show the user (register/login/reset password/etc.). This base view controller has a container view.

I have many little view controllers that I would like for the container view of my base view controller, like so:

How do I use different view controllers for the container view? How do I specify which mini view controller I can use in my container view? I could probably use the storyboard ID/segues but I don't know how. Any tips?

答:
You can only have one embed segue from a container view to another view controller. So the best way is that you can have that one view controller showing dynamic contents.

However, if you prefer to have static view controllers on storyboard, what you can do is to embed a tab bar controller to your container view. You have have all your view controllers as one of the tabs. After that, all you need to do is to first hide the tab bar, then decide which tab to show up using tabBarController.selectedIndex = yourIndex


问:
override supportRtl value
I'd like to override a supportRtl=true value that is set by some library I plan to integrate.

I assume something of the following statement will do the trick

```<code><meta-data
   android:name="supportRtl"
   android:value="false"
   tools:replace="android:value" />
</code>```

Looking for the exact syntax.

答:
android:supportsRtl is an attribute of the <application> tag.

```<code><application
    android:supportsRtl="false"
    tools:replace="android:supportsRtl" />
</code>```

Title: override supportRtl value

Body:
I'd like to override a supportRtl=true value that is set by some library I plan to integrate.

I assume something of the following statement will do the trick

<meta-data
   android:name="supportRtl"
   android:value="false"
   tools:replace="android:value" />

Looking for the exact syntax.

Body:
android:supportsRtl is an attribute of the <application> tag.

<application
    android:supportsRtl="false"
    tools:replace="android:supportsRtl" />


问:
How to store user information in one place after login and access in multiple WEB API controllers
I am working on Web API with AngularJS. I had implemented Web API token mechanism few days ago and able to login the application using the access token. I have used external DB table instead of ASP.NET identity table to authorize user.

I want to store user information in class so that it can be accessed easily from different controllers after User logged in. Currently I am using ClaimsIdentity in Controller Class to get the user information.

UserIdentityViewModel.cs

```<code>public class UserIdentityViewModel
    {
        public string UserName { get; set; }
        public Guid UserId { get; set; }
    }
</code>```

Startup.cs

```<code>public class Startup
    {
        public void Configuration(IAppBuilder app)
        {
            app.UseCors(Microsoft.Owin.Cors.CorsOptions.AllowAll);
            var myProvider = new AuthorizationServerProvider();
            OAuthAuthorizationServerOptions options = new OAuthAuthorizationServerOptions
            {
                AllowInsecureHttp = true,
                TokenEndpointPath = new PathString("/Token"),
                AccessTokenExpireTimeSpan = TimeSpan.FromDays(1),
                Provider = myProvider
            };
            app.UseOAuthAuthorizationServer(options);

            app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions());
        }
    }
</code>```

AuthorizationServerProvider.cs

```<code>public class AuthorizationServerProvider : OAuthAuthorizationServerProvider
    {
        public override async Task ValidateClientAuthentication(OAuthValidateClientAuthenticationContext context)
        {
            context.Validated(); //
        }

        public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
        {
            string userId = context.UserName;
            string password = context.Password;

            EmployeeAccessBLL chkEmpAccessBLL = new EmployeeAccessBLL();
            EmployeeAccessViewModel vmEmployeeAccess = chkEmpAccessBLL.CheckEmployeeAccess(Convert.ToInt32(userId), password);

            if(vmEmployeeAccess != null)
            {
                var identity = new ClaimsIdentity(context.Options.AuthenticationType);
                identity.AddClaim(new Claim("username", vmEmployeeAccess.EmpName));
                identity.AddClaim(new Claim("userid", Convert.ToString(vmEmployeeAccess.EmployeeId)));

                UserIdentityViewModel vmUser = new UserIdentityViewModel();
                vmUser.UserId = vmEmployeeAccess.EmployeeId;
                vmUser.UserName = vmEmployeeAccess.EmpName;

                context.Validated(identity);
            }
            else
            {
                context.SetError("invalid_grant", "Provided username and password is incorrect");
                return;
            }
        }
    }
</code>```

EventController.cs

```<code> public class StreamEventController : ApiController
    {
        [Authorize]
        [Route("api/addevent")]
        [HttpPost]
        public List<string> AddEvent(StreamEventViewModel vmEvent)
        {
            //Able to get User Information from Identity.Claims
            var identity = (ClaimsIdentity)User.Identity;
            string userId = identity.Claims
                            .Where(c => c.Type == "userid")
                            .Select(c => c.Value).FirstOrDefault();

            //Not able to get User Information from following as new object instance gets created
            UserIdentityViewModel vmUser = new UserIdentityViewModel();

            vmEvent.CreatedBy = vmUser.UserId;
            vmEvent.ModifiedBy = vmUser.UserId;
       }
}
</code>```

Instead of writing "Identity.Claims" in each method of every controller I want to use simple get/set approach or any other methodology to get User Information . The use of Static class is also bad in my opinion as it will store one information of user and multiple user login information gets missed.

Please help me and share with me the best approach that has been used in other Web API projects for login.

答:
You can add a private variable which will be set in the constructor of the controller, like this:

```<code>// Should only be used in protected methods.
private ClaimsIdentity ThisUser = null;

public MyController()
{
    if (User.Identity.IsAuthenticated)
        ThisUser = (ClaimsIdentity)User.Identity;
}

[Authorize]
[Route("api/addevent")]
[HttpPost]
public List<string> AddEvent(StreamEventViewModel vmEvent)
{
    string userId = ThisUser.FindFirstValue("userid");

}
</code>```

Or create a User class where you load all properties:

```<code>private UserClass ThisUser = null;

public MyController()
{
    if (User.Identity.IsAuthenticated)
        ThisUser = new UserClass(User);
}

[Authorize]
[Route("api/addevent")]
[HttpPost]
public List<string> AddEvent(StreamEventViewModel vmEvent)
{
    string userId = ThisUser.UserId;

}
</code>```

Where UserClass is something like:

```<code>public class UserClass
{
    public string UserId { get; private set; }

    public UserClass(IPrincipal user)
    {
        UserId = user.FindFirstValue("userid");
    }
}
</code>```

But this is just overhead for the same thing.
You can consider to move things to an extension. In that case you get something like:

```<code>public static class RequestExtensions
{
    public static UserClass GetUser(this HttpRequestMessage request)
    {
        return new UserClass(request.GetOwinContext().Authentication.User);
    }

    public static ClaimsIdentiy GetUser2(this HttpRequestMessage request)
    {
        return new (ClaimsIdentity)request.GetOwinContext().Authentication.User;
    }
}
</code>```

Which you can call:

```<code>[Authorize]
[Route("api/addevent")]
[HttpPost]
public List<string> AddEvent(StreamEventViewModel vmEvent)
{
    string userId = Request.GetUser.UserId;

    string userId2 = Request.GetUser2.FindFirstValue("userid");

}
</code>```

I think I would go for Request.GetUser2.FindFirstValue("userid");

The code is meant to give you an idea. I didn't test the code but I think it should work.

Body:
I am working on Web API with AngularJS. I had implemented Web API token mechanism few days ago and able to login the application using the access token. I have used external DB table instead of ASP.NET identity table to authorize user.

I want to store user information in class so that it can be accessed easily from different controllers after User logged in. Currently I am using ClaimsIdentity in Controller Class to get the user information.

UserIdentityViewModel.cs

public class UserIdentityViewModel
    {
        public string UserName { get; set; }
        public Guid UserId { get; set; }
    }

Startup.cs

public class Startup
    {
        public void Configuration(IAppBuilder app)
        {
            app.UseCors(Microsoft.Owin.Cors.CorsOptions.AllowAll);
            var myProvider = new AuthorizationServerProvider();
            OAuthAuthorizationServerOptions options = new OAuthAuthorizationServerOptions
            {
                AllowInsecureHttp = true,
                TokenEndpointPath = new PathString("/Token"),
                AccessTokenExpireTimeSpan = TimeSpan.FromDays(1),
                Provider = myProvider
            };
            app.UseOAuthAuthorizationServer(options);

            app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions());
        }
    }

AuthorizationServerProvider.cs

public class AuthorizationServerProvider : OAuthAuthorizationServerProvider
    {
        public override async Task ValidateClientAuthentication(OAuthValidateClientAuthenticationContext context)
        {
            context.Validated(); //
        }

        public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
        {
            string userId = context.UserName;
            string password = context.Password;

            EmployeeAccessBLL chkEmpAccessBLL = new EmployeeAccessBLL();
            EmployeeAccessViewModel vmEmployeeAccess = chkEmpAccessBLL.CheckEmployeeAccess(Convert.ToInt32(userId), password);

            if(vmEmployeeAccess != null)
            {
                var identity = new ClaimsIdentity(context.Options.AuthenticationType);
                identity.AddClaim(new Claim("username", vmEmployeeAccess.EmpName));
                identity.AddClaim(new Claim("userid", Convert.ToString(vmEmployeeAccess.EmployeeId)));

                UserIdentityViewModel vmUser = new UserIdentityViewModel();
                vmUser.UserId = vmEmployeeAccess.EmployeeId;
                vmUser.UserName = vmEmployeeAccess.EmpName;

                context.Validated(identity);
            }
            else
            {
                context.SetError("invalid_grant", "Provided username and password is incorrect");
                return;
            }
        }
    }

EventController.cs

 public class StreamEventController : ApiController
    {
        [Authorize]
        [Route("api/addevent")]
        [HttpPost]
        public List<string> AddEvent(StreamEventViewModel vmEvent)
        {
            //Able to get User Information from Identity.Claims
            var identity = (ClaimsIdentity)User.Identity;
            string userId = identity.Claims
                            .Where(c => c.Type == "userid")
                            .Select(c => c.Value).FirstOrDefault();

            //Not able to get User Information from following as new object instance gets created
            UserIdentityViewModel vmUser = new UserIdentityViewModel();

            vmEvent.CreatedBy = vmUser.UserId;
            vmEvent.ModifiedBy = vmUser.UserId;
       }
}

Instead of writing "Identity.Claims" in each method of every controller I want to use simple get/set approach or any other methodology to get User Information . The use of Static class is also bad in my opinion as it will store one information of user and multiple user login information gets missed.

Please help me and share with me the best approach that has been used in other Web API projects for login.

Body:
You can add a private variable which will be set in the constructor of the controller, like this:

// Should only be used in protected methods.
private ClaimsIdentity ThisUser = null;

public MyController()
{
    if (User.Identity.IsAuthenticated)
        ThisUser = (ClaimsIdentity)User.Identity;
}

[Authorize]
[Route("api/addevent")]
[HttpPost]
public List<string> AddEvent(StreamEventViewModel vmEvent)
{
    string userId = ThisUser.FindFirstValue("userid");

}

Or create a User class where you load all properties:

private UserClass ThisUser = null;

public MyController()
{
    if (User.Identity.IsAuthenticated)
        ThisUser = new UserClass(User);
}

[Authorize]
[Route("api/addevent")]
[HttpPost]
public List<string> AddEvent(StreamEventViewModel vmEvent)
{
    string userId = ThisUser.UserId;

}

Where UserClass is something like:

public class UserClass
{
    public string UserId { get; private set; }

    public UserClass(IPrincipal user)
    {
        UserId = user.FindFirstValue("userid");
    }
}

But this is just overhead for the same thing.
You can consider to move things to an extension. In that case you get something like:

public static class RequestExtensions
{
    public static UserClass GetUser(this HttpRequestMessage request)
    {
        return new UserClass(request.GetOwinContext().Authentication.User);
    }

    public static ClaimsIdentiy GetUser2(this HttpRequestMessage request)
    {
        return new (ClaimsIdentity)request.GetOwinContext().Authentication.User;
    }
}

Which you can call:

[Authorize]
[Route("api/addevent")]
[HttpPost]
public List<string> AddEvent(StreamEventViewModel vmEvent)
{
    string userId = Request.GetUser.UserId;

    string userId2 = Request.GetUser2.FindFirstValue("userid");

}

I think I would go for Request.GetUser2.FindFirstValue("userid");

The code is meant to give you an idea. I didn't test the code but I think it should work.


问:
sudo command not found on Cygwin
I am currently trying to install and update a few packages on a Windows OS. The only matter is that I am using Cygwin in order to type the commands through a terminal (as I'm aware, I can type in Linux type commands such as cd, ls etc. on Cygwin - I may be wrong). However, when I try to install a package like:

```<code>sudo apt-get install paparazzi-dev
</code>```

I get the reply:

```<code>-sh: sudo: command not found.
</code>```

Does anyone have an idea as to how I can fix this problem?

答:
I think I tried steps below after doing some research & succeeded (on windows)

1.Install scoop using powershell 3 (iex (new-object net.webclient).downloadstring('https://get.scoop.sh'))
2. do scoop install --global sudo
3. make sure paths (C:\Users\\scoop\shims & C:\ProgramData\scoop\shims) added in environmental path variable.

Title: sudo command not found on Cygwin

Body:
I am currently trying to install and update a few packages on a Windows OS. The only matter is that I am using Cygwin in order to type the commands through a terminal (as I'm aware, I can type in Linux type commands such as cd, ls etc. on Cygwin - I may be wrong). However, when I try to install a package like:

sudo apt-get install paparazzi-dev

I get the reply:

-sh: sudo: command not found.

Does anyone have an idea as to how I can fix this problem?


问:
Pure functions: state content vs. state reference
In this pen, I am having a hard time understanding why when using the push function on a newly created const (line 24) it matters whether one uses the spread operator or simply copies "state" over. How is it that replacing [...state] with state causes state to be overwritten with the content of newState?

Am I correct in assuming that it is the reference to state which is overwritten if state is directly passed to newState? I.e. in the case of const newState = state

答:
I assume this is the section or the pen you are referencing:

```<code>const newState = [...state]; // copy contents of state, NOT the reference to it (state)
newState.push(action.payload);
return newState;
</code>```

Let's look at the difference between what this code is doing now, and what it would do if const newState = state was used instead.

```<code>const newState = [...state];
</code>```

This line creates a new array, called newState with the contents of state.  It is essentially a one liner for:

```<code>const newState = [];

for (let i = 0; i < state.length; i++) {
    newState.push(state[i]);
}
</code>```

When newState.push(action.payload) is called, the state array is unchanged, while newState has an extra element pushed into it.

```<code>const newState = state;
</code>```

This line sets the variable newState to the same reference as state, so there is only one array in play.

When newState.push(action.payload) is called, the new element is pushed into the array, so both newState and state have changed.

Body:
I assume this is the section or the pen you are referencing:

const newState = [...state]; // copy contents of state, NOT the reference to it (state)
newState.push(action.payload);
return newState;

Let's look at the difference between what this code is doing now, and what it would do if const newState = state was used instead.

const newState = [...state];

This line creates a new array, called newState with the contents of state.  It is essentially a one liner for:

const newState = [];

for (let i = 0; i < state.length; i++) {
    newState.push(state[i]);
}

When newState.push(action.payload) is called, the state array is unchanged, while newState has an extra element pushed into it.

const newState = state;

This line sets the variable newState to the same reference as state, so there is only one array in play.

When newState.push(action.payload) is called, the new element is pushed into the array, so both newState and state have changed.


问:
Import searchbar component with props.navigation
I'm trying to import a searchbar component into my containers but the onSearch function does not work. It returns an error 'undefined is not an object (evaluating 'this.props.navigation.navigate'). What am I missing?

In my container, I have:

```<code>import SearchBar from '../Components/SearchBar'
</code>```

and inside the render function I have

```<code><SearchBar />
</code>```

In SearchBar.js:

```<code>  onSearch(terms) {
      console.log(terms);
      this.props.navigation.navigate('ProductsGrid', {searchTerms: terms})
  }

  render () {
    return (
      <View style={styles.container}>
        <TextInput
          ref='searchText'
          value={this.props.searchTerm}
          onSubmitEditing={(event) => this.onSearch(event.nativeEvent.text)}
          returnKeyType={'search'}
          autoCorrect={false}
        />
      </View>
    )
  }
</code>```

答:
Needed to add {...this.props} inside of  to pass the props.</p>

```<code><SearchBar {...this.props} />
</code>```

Body:
I'm trying to import a searchbar component into my containers but the onSearch function does not work. It returns an error 'undefined is not an object (evaluating 'this.props.navigation.navigate'). What am I missing?

In my container, I have:

import SearchBar from '../Components/SearchBar'

and inside the render function I have

<SearchBar />

In SearchBar.js:

  onSearch(terms) {
      console.log(terms);
      this.props.navigation.navigate('ProductsGrid', {searchTerms: terms})
  }

  render () {
    return (
      <View style={styles.container}>
        <TextInput
          ref='searchText'
          value={this.props.searchTerm}
          onSubmitEditing={(event) => this.onSearch(event.nativeEvent.text)}
          returnKeyType={'search'}
          autoCorrect={false}
        />
      </View>
    )
  }

Body:
Needed to add {...this.props} inside of  to pass the props.

<SearchBar {...this.props} />


问:
Android what is the name of standard drawable 3 lines vertical
I need to know what is the name of the attached icon in R.android.drawable resources to use it in my app

答:
in case you are using v4/v7 support library, you should find it with below name :
         android.support.v7.appcompat.R.drawable.abc_ic_menu_moreoverflow_mtrl_alpha
  or
  android.support.v7.appcompat.R.drawable.abc_ic_menu_overflow_material

in case of design libary :
  android.support.design.R.drawable.abc_ic_menu_overflow_material


问:
how can i get recent chat of a user from coreData swift
I have two entities Friend and Message
now i want to get the latest message of friend how can i do this

Friend contain these things

```<code>Friend{
  name:String
  id:Int
  email:String
}
</code>```

and Message Contain these thing and also have one to many relationShip from friend to message

```<code>   Message{
     id:String
     text:String
     created_at:Date
     /...// and many things

}
</code>```

答:
You can get the latest message of user by sort Descriptor like this:-

```<code>let fetchRequest = NSFetchRequest<Message>.init(entityName: "Message")
fetchRequest.sortDescriptors = [NSSortDescriptor.init(key: "created_at", ascending: false)]
let predicate = NSPredicate.init(format: "friend.id = %@","1")// pass the id of friend for you want to access latest message
fetchRequest.predicate = predicate
</code>```

now you can fetch this request

Body:
I have two entities Friend and Message
now i want to get the latest message of friend how can i do this

Friend contain these things

Friend{
  name:String
  id:Int
  email:String
}

and Message Contain these thing and also have one to many relationShip from friend to message

   Message{
     id:String
     text:String
     created_at:Date
     /...// and many things

}

Body:
You can get the latest message of user by sort Descriptor like this:-

let fetchRequest = NSFetchRequest<Message>.init(entityName: "Message")
fetchRequest.sortDescriptors = [NSSortDescriptor.init(key: "created_at", ascending: false)]
let predicate = NSPredicate.init(format: "friend.id = %@","1")// pass the id of friend for you want to access latest message
fetchRequest.predicate = predicate

now you can fetch this request


问:
Register a service to eureka with preferred networks configuration not work
I want to register a service to eureka, the server has two ip:

```<code>eth0: 192.168.121.74
eth1: 10.254.102.243
</code>```

I want the service to be registered with ip 10.254.102.243, so my appliction.yml comes like this:

```<code>eureka:
  client:
    serviceUrl:
      defaultZone: http://10.254.102.12:1111/eureka/
  instance:
    preferIpAddress: true

spring:
  application:
    name: item-service
  jpa:
    hibernate.ddl-auto: none
    database-platform: org.hibernate.dialect.MySQLDialect
  datasource:
    url: {url}
    username: {username}
    password: {password}
  cloud:
    inetutils:
      preferredNetworks:
        - 10.254
</code>```

But this didn't work, the service still registered with ip 192.168.121.74.

When I run my the service like this:

```<code>java -Dspring.cloud.inetutils.preferredNetworks=10.254 -jar item-web-0.0.1-SNAPSHOT.war
</code>```

The service logs show the ip was 10.254.102.250 but actually ip was 127.0.0.1 which I found in the eureka server web page.

```<code>2017-07-09 15:44:06.658  INFO 24322 --- [nfoReplicator-0] com.netflix.discovery.DiscoveryClient    : DiscoveryClient_ITEM-SERVICE/10.254.102.250:item-service: registering service...
2017-07-09 15:44:06.828  INFO 24322 --- [nfoReplicator-0] com.netflix.discovery.DiscoveryClient    : DiscoveryClient_ITEM-SERVICE/10.254.102.250:item-service - registration status: 204
</code>```

So how can I make the service registered with ip 10.254.102.243?

update:

When I move preferredNetworks into bootstrap.yml, it work like using -Dspring.cloud.inetutils.preferredNetworks in command line. In the eureka server web page the actual ip in the eureka web page still 127.0.0.1.

答:
Try to define the following properties in boostrap.yml instead of application.yml. You can add addition interfaces that you want to ignore.

```<code>spring:
  cloud:
    inetutils:
      ignoredInterfaces:
        - lo
        - lo*
        - eth0*
</code>```

Body:
I want to register a service to eureka, the server has two ip:

eth0: 192.168.121.74
eth1: 10.254.102.243

I want the service to be registered with ip 10.254.102.243, so my appliction.yml comes like this:

eureka:
  client:
    serviceUrl:
      defaultZone: http://10.254.102.12:1111/eureka/
  instance:
    preferIpAddress: true

spring:
  application:
    name: item-service
  jpa:
    hibernate.ddl-auto: none
    database-platform: org.hibernate.dialect.MySQLDialect
  datasource:
    url: {url}
    username: {username}
    password: {password}
  cloud:
    inetutils:
      preferredNetworks:
        - 10.254

But this didn't work, the service still registered with ip 192.168.121.74.

When I run my the service like this:

java -Dspring.cloud.inetutils.preferredNetworks=10.254 -jar item-web-0.0.1-SNAPSHOT.war

The service logs show the ip was 10.254.102.250 but actually ip was 127.0.0.1 which I found in the eureka server web page.

2017-07-09 15:44:06.658  INFO 24322 --- [nfoReplicator-0] com.netflix.discovery.DiscoveryClient    : DiscoveryClient_ITEM-SERVICE/10.254.102.250:item-service: registering service...
2017-07-09 15:44:06.828  INFO 24322 --- [nfoReplicator-0] com.netflix.discovery.DiscoveryClient    : DiscoveryClient_ITEM-SERVICE/10.254.102.250:item-service - registration status: 204

So how can I make the service registered with ip 10.254.102.243?

update:

When I move preferredNetworks into bootstrap.yml, it work like using -Dspring.cloud.inetutils.preferredNetworks in command line. In the eureka server web page the actual ip in the eureka web page still 127.0.0.1.

Body:
Try to define the following properties in boostrap.yml instead of application.yml. You can add addition interfaces that you want to ignore.

spring:
  cloud:
    inetutils:
      ignoredInterfaces:
        - lo
        - lo*
        - eth0*


问:
A makefile recipe runs every time even when target is more recent than dependency
Makefile:

```<code>node_modules: package.json ## Run npm install
        @npm install
</code>```

Why does make node_modules excecute the receipe npm install every time I run make node_modules?

I believe the recipe should not get executed if my file package.json is not more recent that the directory node_modules.

答:
The link that @IsmailBadawi provided in comments is the key here.

Make determines if a target is out of date based on its last-modified time (mtime).  However, a directory is only considered to be modified when one of its direct children are added/removed/renamed (at least on Unix-like systems).

This is insufficient in your case.  Imagine the following sequence:

Run make for the first time.

Rule is not skipped.

mtime(node_modules) > mtime(package.json).

Run make again.

Rule is skipped.

Change a dependency version in package.json.

mtime(node_modules) < mtime(package.json).

Run make again.

Rule is not skipped.

Dependency is updated in node_modules.

But mtime(node_modules) is unaffected.

Run make again.

Rule is not skipped.

... and so on forever ...

You can probably fix this by adding touch -m node_modules to your recipe.

Body:
Makefile:

node_modules: package.json ## Run npm install
        @npm install

Why does make node_modules excecute the receipe npm install every time I run make node_modules?

I believe the recipe should not get executed if my file package.json is not more recent that the directory node_modules.


问:
htaccess url folder redirect
I am trying to change my url to try to stop it from showing the language folder in the url for example:

change from
www.site.com/en

change to
www.site.com

so I am looking to remove the

en

from the url but still accessing that directory. This is what I have so far but it does not seem to do the trick:

```<code>RewriteEngine on
RewriteBase /mysite/

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule .+ en=$0 [L,QSA]
</code>```

Thank you.

答:
This should do it: </p>

```<code>RewriteEngine on

RewriteBase /mysite/

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d

RewriteRule ^(.*)$ en/$1 [L,QSA]
</code>```

Title: htaccess url folder redirect

Body:
I am trying to change my url to try to stop it from showing the language folder in the url for example:

change from
www.site.com/en

change to
www.site.com

so I am looking to remove the

en

from the url but still accessing that directory. This is what I have so far but it does not seem to do the trick:

RewriteEngine on
RewriteBase /mysite/

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule .+ en=$0 [L,QSA]

Thank you.

Body:
This should do it:

RewriteEngine on

RewriteBase /mysite/

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d

RewriteRule ^(.*)$ en/$1 [L,QSA]


问:
Dropdowm menu in Vanilla JavaScript - for unknown number of buttons
please, can you give me a hint with Vanilla JS?

I have dropdown menu opening via button click and have 2 issues:

1) Dropdown is opening by clicking on button with unique ID. I need to get it working on Class name, because it have to be working on multiple buttons - and the number of them is unknown (they will load from REST API).
In jQuery is it working, but I need it in Vanilla JS.

If I try to select button by Class name, it will return array of buttons, but I don't know how to select from array, which button was being clicked on.

2) Dropdown menu is opening only on the second click on the button (and then it is toggling like it should), but the first click doesn't do anything.

My code is here:

```<code>// select Button - now by ID - but I need unknown number of buttons - from REST API - and the code working for all of them
var btn = document.getElementById("dropBtn1");

// select Dropdown menu - next to the button - to be sure it will open the right menu no matter which button will be pressed
var menu = btn.nextSibling;
while(menu && menu.nodeType != 1) {
    menu = menu.nextSibling
}

//toggle dropdown menu open/close
btn.addEventListener("click", function() {
  if (menu.style.display == 'none') {
    menu.style.display = 'block';
  }
  else {
    menu.style.display = 'none';
  }
});
</code>```

And working prototype is here on Codepen:
https://codepen.io/vlastapolach/pen/EXdLMy

Please, do you have any ideas how to fix this?

Thank you!

答:
Quite easy, you need a general function that works on the context (=this):

```<code>//toggle dropdown menu open/close
function toggle() {
  var btn=this;

  var menu = btn.nextSibling;
  while(menu && menu.nodeType != 1) {
     menu = menu.nextSibling
  }

  if(!menu) return;

  if (menu.style.display != 'block') {//fix 2)
    menu.style.display = 'block';
  }  else {
    menu.style.display = 'none';
  }
});
</code>```

Now you can assign this functions as an event handler onto all your elements:

```<code>window.addEventListener("DOMContentLoaded",function(){

  document.querySelectorAll(".sth").forEach(function(btn){
     btn.addEventListener("click",toggle,true);
  });
});
</code>```

Note that NodeList.forEach is quite new, may use [].slice to create a real array...

And you need to assign the Handlers to the newly added elements manually, or you need to listen on window and trace back the target:

```<code>window.onclick=function(event){
  if(event.target.classList.contains("sth")){
   toggle.call(event.target);
  }
};
</code>```

Body:
please, can you give me a hint with Vanilla JS?

I have dropdown menu opening via button click and have 2 issues:

1) Dropdown is opening by clicking on button with unique ID. I need to get it working on Class name, because it have to be working on multiple buttons - and the number of them is unknown (they will load from REST API).
In jQuery is it working, but I need it in Vanilla JS.

If I try to select button by Class name, it will return array of buttons, but I don't know how to select from array, which button was being clicked on.

2) Dropdown menu is opening only on the second click on the button (and then it is toggling like it should), but the first click doesn't do anything.

My code is here:

// select Button - now by ID - but I need unknown number of buttons - from REST API - and the code working for all of them
var btn = document.getElementById("dropBtn1");

// select Dropdown menu - next to the button - to be sure it will open the right menu no matter which button will be pressed
var menu = btn.nextSibling;
while(menu && menu.nodeType != 1) {
    menu = menu.nextSibling
}

//toggle dropdown menu open/close
btn.addEventListener("click", function() {
  if (menu.style.display == 'none') {
    menu.style.display = 'block';
  }
  else {
    menu.style.display = 'none';
  }
});

And working prototype is here on Codepen:
https://codepen.io/vlastapolach/pen/EXdLMy

Please, do you have any ideas how to fix this?

Thank you!

Body:
Quite easy, you need a general function that works on the context (=this):

//toggle dropdown menu open/close
function toggle() {
  var btn=this;

  var menu = btn.nextSibling;
  while(menu && menu.nodeType != 1) {
     menu = menu.nextSibling
  }

  if(!menu) return;

  if (menu.style.display != 'block') {//fix 2)
    menu.style.display = 'block';
  }  else {
    menu.style.display = 'none';
  }
});

Now you can assign this functions as an event handler onto all your elements:

window.addEventListener("DOMContentLoaded",function(){

  document.querySelectorAll(".sth").forEach(function(btn){
     btn.addEventListener("click",toggle,true);
  });
});

Note that NodeList.forEach is quite new, may use [].slice to create a real array...

And you need to assign the Handlers to the newly added elements manually, or you need to listen on window and trace back the target:

window.onclick=function(event){
  if(event.target.classList.contains("sth")){
   toggle.call(event.target);
  }
};


问:
How to use accelerator table in a subclassed control?
I am subclassing a control and at this point I want to add some keyboard shortcuts to it. There's about a dozen of them defined in an accelerator table in the resource.

I know that I can utilize these accelerators from the main app, by calling TranslateAccelerator and then TranslateMessage and DispatchMessage from its main loop.

But can I check if accelerator key sequence is pressed from a subclassed control from within WndProc itself?

EDIT: In other words, would it be bad to do something like this?

```<code>LRESULT CSubclassedWnd::WindowProc(UINT message, WPARAM wParam, LPARAM lParam)
{
    // TODO: Add your specialized code here and/or call the base class

    if(message == WM_KEYDOWN ||
        message == WM_CHAR ||
        message == WM_SYSKEYDOWN ||
        message == WM_SYSCHAR)
    {
        if(hAccel)
        {
            CRect rcThis;
            this->GetWindowRect(&rcThis);
            this->ScreenToClient(&rcThis);
            POINT pnt = {(rcThis.right + rcThis.left) / 2, (rcThis.bottom + rcThis.top) / 2};

            MSG msg = {this->GetSafeHwnd(), message, wParam, lParam, ::GetTickCount(), pnt};
            if(::TranslateAccelerator(this->GetSafeHwnd(), hAccel, &msg))
            {
                //Accelerator was recognized and sent as WM_COMMAND message to the same window
                return 0;
            }
        }
    }

    switch(message)
    {
    case WM_COMMAND:
        {
            //Special accelerator commands
            if(HIWORD(wParam) == 1 &&
                lParam == 0)
            {
                //See which command was it
                switch(LOWORD(wParam))
                {
                case ID_MY_ACCELERATOR_ID1:
                    {
                        //Do work...
                    }
                    return 0;

                case ID_MY_ACCELERATOR_ID2:
                    {
                        //Do work...
                    }
                    return 0;
                }
            }
        }
        break;

    case WM_ERASEBKGND:
        //process it
        return TRUE;
    case WM_PAINT:
        //process it
        return TRUE;
    case WM_KEYDOWN:
        //process it
        break;

    //etc.
    }

    return CWnd::WindowProc(message, wParam, lParam);
}
</code>```

答:
I believe the standard Windows controls just use WM_KEYDOWN/CHAR and GetKeyState but I don't see why you can't use TranslateAccelerator.

TranslateAccelerator is in some ways better because it knows how to handle Alt.Gr but it will also ignore the key if the mouse is captured (IIRC) so it depends on your needs.

Calling TranslateAccelerator on the top-level window after GetMessage is of course the best option because it will check the window menu to see if the command is disabled...

Body:
I am subclassing a control and at this point I want to add some keyboard shortcuts to it. There's about a dozen of them defined in an accelerator table in the resource.

I know that I can utilize these accelerators from the main app, by calling TranslateAccelerator and then TranslateMessage and DispatchMessage from its main loop.

But can I check if accelerator key sequence is pressed from a subclassed control from within WndProc itself?

EDIT: In other words, would it be bad to do something like this?

LRESULT CSubclassedWnd::WindowProc(UINT message, WPARAM wParam, LPARAM lParam)
{
    // TODO: Add your specialized code here and/or call the base class

    if(message == WM_KEYDOWN ||
        message == WM_CHAR ||
        message == WM_SYSKEYDOWN ||
        message == WM_SYSCHAR)
    {
        if(hAccel)
        {
            CRect rcThis;
            this->GetWindowRect(&rcThis);
            this->ScreenToClient(&rcThis);
            POINT pnt = {(rcThis.right + rcThis.left) / 2, (rcThis.bottom + rcThis.top) / 2};

            MSG msg = {this->GetSafeHwnd(), message, wParam, lParam, ::GetTickCount(), pnt};
            if(::TranslateAccelerator(this->GetSafeHwnd(), hAccel, &msg))
            {
                //Accelerator was recognized and sent as WM_COMMAND message to the same window
                return 0;
            }
        }
    }

    switch(message)
    {
    case WM_COMMAND:
        {
            //Special accelerator commands
            if(HIWORD(wParam) == 1 &&
                lParam == 0)
            {
                //See which command was it
                switch(LOWORD(wParam))
                {
                case ID_MY_ACCELERATOR_ID1:
                    {
                        //Do work...
                    }
                    return 0;

                case ID_MY_ACCELERATOR_ID2:
                    {
                        //Do work...
                    }
                    return 0;
                }
            }
        }
        break;

    case WM_ERASEBKGND:
        //process it
        return TRUE;
    case WM_PAINT:
        //process it
        return TRUE;
    case WM_KEYDOWN:
        //process it
        break;

    //etc.
    }

    return CWnd::WindowProc(message, wParam, lParam);
}


问:
What is the importance of the question mark and what is the benefit of this code?
```<code>function nanogegreee(num7, isInteger) {
    if (isInteger === void 0) {
        isInteger = false;
    }
    return Math.floor(num7 * num7);
}

console.log(nanogegreee(4.6));
</code>```

答:
Since you tagged this as a TypeScript question, if by question mark, you are referring to interface construction or parameters, the question mark after the parameter means that it can be omitted from an object instantiation (if in an interface) or a function call (if a parameter in a function).

As far as the code, please be more specific in your question.


问:
Finding duplicate strings in array
guys! I have a database with IDs and names of my products. I need to find the different colors of each product - they're with duplicate names. I've tried so many things, but I still don't have any luck, since there might be 5+ colors of one product. It needs to be checked one row after another (since there might be a product in the beginning with the same name, which is not a different color, but a different product). Could someone help me, please? Thank you!

This:

```<code>array(
    0 => array('D41596', 'ДАМСКИ КОМПЛЕКТ БЛУЗА ТРИКО'),
    1 => array('D41597', 'ДАМСКИ КОМПЛЕКТ БЛУЗА ТРИКО С ПОЛА BALMAIN 5310'),
    2 => array('D41599', 'ДАМСКИ КОМПЛЕКТ БЛУЗА ТРИКО С ПОЛА BALMAIN 5310'),
    3 => array('D41600', 'ДАМСКИ КОМПЛЕКТ БЛУЗА С ПОЛА РАЕ 1736'),
    4 => array('D41601', 'ДАМСКИ КОМПЛЕКТ БЛУЗА С ГАЩЕРИЗОН 613 НА БОЛИНКИ'),
    5 => array('D41602', 'ДАМСКИ КОМПЛЕКТ БЛУЗА С ГАЩЕРИЗОН 613 НА БОЛИНКИ'),
    6 => array('D41603', 'ДАМСКИ КОМПЛЕКТ БЛУЗА С ПАНТАЛОН 615'),
    7 => array('D41604', 'ДАМСКИ КОМПЛЕКТ БЛУЗА С ПАНТАЛОН 615'),
    8 => array('D41605', 'ДАМСКИ КОМПЛЕКТ КЪС ПАНТАЛОН С ТОП САТЕН'),
    9 => array('D41606', 'ДАМСКИ КОМПЛЕКТ КЪС ПАНТАЛОН С ТОП САТЕН'),
    10 => array('D41607', 'ДАМСКИ КОМПЛЕКТ КЪС ПАНТАЛОН С ТОП САТЕН'),
    11 => array('D41608', 'ДАМСКИ КОМПЛЕКТ ДЪНКИ С БЛУЗА ТРИКО 062 ФЛАМИНГО'),
    12 => array('D41609', 'ДАМСКИ КОМПЛЕКТ КЪС ДЪНКОВ ПАНТАЛОН С БЛУЗА ТРИКО 085 КОЛИБРИ'),
    13 => array('D41610', 'ДАМСКИ КОМПЛЕКТ КЪС ДЪНКОВ ПАНТАЛОН С БЛУЗА ТРИКО 075 ЦВЕТЯ ОТ ПАЕТИ'),
    14 => array('D41611', 'ДАМСКИ КОМПЛЕКТ ДЪНКОВА ПОЛА С БЛУЗА ТРИКО 072 ЛИЛАВИ ЦВЕТЯ С ПАЕТИ')
);
</code>```

Should output:

```<code>array(
    'D41597' => 'D41597,D41599',
    'D41599' => 'D41597,D41599',
    'D41601' => 'D41601,D41602',
    'D41602' => 'D41601,D41602',
    'D41603' => 'D41603,D41604',
    'D41604' => 'D41603,D41604',
    'D41605' => 'D41605,D41606,D41607',
    'D41606' => 'D41605,D41606,D41607',
    'D41607' => 'D41605,D41606,D41607'
);
</code>```

答:
This code should do the trick. Basically, it loops over the IDs and checks for  occurrences with the same name, then adds found item IDs to the results table:</p>

```<code>$results = array();

foreach ($arr as $element) {

    list ($key, $value) = $element;
    $searchResults = array();

    foreach ($arr as $searchElement) {
        if ($searchElement[1] == $value) {
            $searchResults[] = $searchElement[0];
        }
    }

    if (sizeof($searchResults) > 1) {
        $results[$key] = implode(',', $searchResults);
    }
}

print_r($results);

Array
(
    [D41597] => D41597,D41599
    [D41599] => D41597,D41599
    [D41601] => D41601,D41602
    [D41602] => D41601,D41602
    [D41603] => D41603,D41604
    [D41604] => D41603,D41604
    [D41605] => D41605,D41606,D41607
    [D41606] => D41605,D41606,D41607
    [D41607] => D41605,D41606,D41607
)
</code>```

Title: Finding duplicate strings in array

Body:
guys! I have a database with IDs and names of my products. I need to find the different colors of each product - they're with duplicate names. I've tried so many things, but I still don't have any luck, since there might be 5+ colors of one product. It needs to be checked one row after another (since there might be a product in the beginning with the same name, which is not a different color, but a different product). Could someone help me, please? Thank you!

This:

array(
    0 => array('D41596', 'ДАМСКИ КОМПЛЕКТ БЛУЗА ТРИКО'),
    1 => array('D41597', 'ДАМСКИ КОМПЛЕКТ БЛУЗА ТРИКО С ПОЛА BALMAIN 5310'),
    2 => array('D41599', 'ДАМСКИ КОМПЛЕКТ БЛУЗА ТРИКО С ПОЛА BALMAIN 5310'),
    3 => array('D41600', 'ДАМСКИ КОМПЛЕКТ БЛУЗА С ПОЛА РАЕ 1736'),
    4 => array('D41601', 'ДАМСКИ КОМПЛЕКТ БЛУЗА С ГАЩЕРИЗОН 613 НА БОЛИНКИ'),
    5 => array('D41602', 'ДАМСКИ КОМПЛЕКТ БЛУЗА С ГАЩЕРИЗОН 613 НА БОЛИНКИ'),
    6 => array('D41603', 'ДАМСКИ КОМПЛЕКТ БЛУЗА С ПАНТАЛОН 615'),
    7 => array('D41604', 'ДАМСКИ КОМПЛЕКТ БЛУЗА С ПАНТАЛОН 615'),
    8 => array('D41605', 'ДАМСКИ КОМПЛЕКТ КЪС ПАНТАЛОН С ТОП САТЕН'),
    9 => array('D41606', 'ДАМСКИ КОМПЛЕКТ КЪС ПАНТАЛОН С ТОП САТЕН'),
    10 => array('D41607', 'ДАМСКИ КОМПЛЕКТ КЪС ПАНТАЛОН С ТОП САТЕН'),
    11 => array('D41608', 'ДАМСКИ КОМПЛЕКТ ДЪНКИ С БЛУЗА ТРИКО 062 ФЛАМИНГО'),
    12 => array('D41609', 'ДАМСКИ КОМПЛЕКТ КЪС ДЪНКОВ ПАНТАЛОН С БЛУЗА ТРИКО 085 КОЛИБРИ'),
    13 => array('D41610', 'ДАМСКИ КОМПЛЕКТ КЪС ДЪНКОВ ПАНТАЛОН С БЛУЗА ТРИКО 075 ЦВЕТЯ ОТ ПАЕТИ'),
    14 => array('D41611', 'ДАМСКИ КОМПЛЕКТ ДЪНКОВА ПОЛА С БЛУЗА ТРИКО 072 ЛИЛАВИ ЦВЕТЯ С ПАЕТИ')
);

Should output:

array(
    'D41597' => 'D41597,D41599',
    'D41599' => 'D41597,D41599',
    'D41601' => 'D41601,D41602',
    'D41602' => 'D41601,D41602',
    'D41603' => 'D41603,D41604',
    'D41604' => 'D41603,D41604',
    'D41605' => 'D41605,D41606,D41607',
    'D41606' => 'D41605,D41606,D41607',
    'D41607' => 'D41605,D41606,D41607'
);

Body:
This code should do the trick. Basically, it loops over the IDs and checks for  occurrences with the same name, then adds found item IDs to the results table:

$results = array();

foreach ($arr as $element) {

    list ($key, $value) = $element;
    $searchResults = array();

    foreach ($arr as $searchElement) {
        if ($searchElement[1] == $value) {
            $searchResults[] = $searchElement[0];
        }
    }

    if (sizeof($searchResults) > 1) {
        $results[$key] = implode(',', $searchResults);
    }
}

print_r($results);

Array
(
    [D41597] => D41597,D41599
    [D41599] => D41597,D41599
    [D41601] => D41601,D41602
    [D41602] => D41601,D41602
    [D41603] => D41603,D41604
    [D41604] => D41603,D41604
    [D41605] => D41605,D41606,D41607
    [D41606] => D41605,D41606,D41607
    [D41607] => D41605,D41606,D41607
)


问:
Unit testing cookies in PHP
The default practice for unit testing functionality that relies on session/cookie information is to use an abstraction library. But what if I want to write and unit test this abstraction library? The documentation for the PHP setcookiefunction says that the cookie will be available on the next request. Using a command line tool for testing, there is no such thing as a "request". So how can I unit test the correct cookie settings?

I want to test if all the parameters of the setcookie function are set correctly by my abstraction library. Those parameters will be set according to certain conditions and method calls.

The only solution I can think of is to mock the setcookie function with the runkit extension, which I don't want to install. Other ideas?

答:
I found another, very simple solution: A class wrapper around the PHP setcookie function that is so simple, it does not need to be unit tested:

```<code>/**
 * Wrapper around setcookie function for better testability
 */
class Cookiesetter {
  public function setcookie($name, $value = "",  $expire = 0,  $path = "",
    $domain = "", $secure = false, $httponly = false) {
    return setcookie($name, $value,  $expire, $path, $domain, $secure, $httponly);
  }
}
</code>```

The setcookie method can then be mocked. This has the additional benefit that I can implement other methods like expireCookie.

Title: Unit testing cookies in PHP

Body:
I found another, very simple solution: A class wrapper around the PHP setcookie function that is so simple, it does not need to be unit tested:

/**
 * Wrapper around setcookie function for better testability
 */
class Cookiesetter {
  public function setcookie($name, $value = "",  $expire = 0,  $path = "",
    $domain = "", $secure = false, $httponly = false) {
    return setcookie($name, $value,  $expire, $path, $domain, $secure, $httponly);
  }
}

The setcookie method can then be mocked. This has the additional benefit that I can implement other methods like expireCookie.


问:
Knockout Observable Array of Observable Array
I have passed a model to my View Model from .Net, which is a Object, containing a few fields, and a List, and each of those has another List.

So, an object with a List of Lists.

On my View, I represent this as some data, with a list of Tabs (The first list), and then each tab has a grid of data.

In my Knockout View model, I just have:

```<code>self.Name = ko.observable("");
self.Width = ko.observable(0);
self.Height = ko.observable(0);

self.TemplateGroups = ko.observableArray();
</code>```

So, my main object, with an observable array (the first list). But, the list within that, isn't observable.

So when rendering my tabls, I do:

```<code><div class="tab-content" data-bind="foreach: TemplateGroups">
</code>```

And that renders each tab. And then within each tab, I do this:

```<code><tbody data-bind="foreach: $data.Components">
      <tr  style="cursor: pointer" data-bind="click: $parents[1].ClickedIt">
</code>```

('Components' is the name of the list within the outer list)

Problem is, on my ClickIt function, I am displaying the Idof the row I clicked, and it works. And then I am just trying to change the 'Description' field of this outer list, but ... it's not a function, so, no observed:

```<code>self.ClickedIt = function () {
    alert(this.Id);
    this.Description("Craig");

}
</code>```

The alert shows the Id, but error on Description("Craig"), as it's not a function.

How can I make the list, within my ObservableArray, observable?

(To be clearer, my model I pass in is an object, which contains a List called TemplateGroups... and then each item in that list, contains a List called 'Components'. It's the Id of one of those Components that I am displaying, but I need to make that list Observable.

Edit: This seems to be what I am looking for (http://jsfiddle.net/rniemeyer/bZhCk/), but ... I am not defining my array the same way. Instead, they're being passed in from a .Net class (So, converted to JSON, I think). And that .Net class contains a List of another .Net class, which has a List).

Note, My load method:

```<code>self.loadData = function () {
        $.get("/api/PlateTemplate/Get", { id: self.TemplateId() }).done(function (data) {
            self.Name(data.Description);
            self.Width(data.Width);
            self.Height(data.Height);
            self.TemplateGroups(data.PlateTemplateGroups);
        });
    }
</code>```

答:
The content of self.TemplateGroups is data.PlateTemplateGroups, that is an array and its content are not observable properties (they are javascript objects).

If you want that this objects in this array become observables, you could use the Mapping Plugin:

```<code>self.loadData = function () {
    $.get("/api/PlateTemplate/Get", { id: self.TemplateId() }).done(function (data) {
        self.Name(data.Description);
        self.Width(data.Width);
        self.Height(data.Height);
        self.TemplateGroups(
          ko.mapping.fromJS(     //   <--- new
             data.PlateTemplateGroups));
    });
}
</code>```

This way, all properties become observables.

If you need to convert this data to a Json format you could use ko.mapping.toJS():

```<code>ko.mapping.toJS(self.TemplateGroups)
</code>```

Body:
I have passed a model to my View Model from .Net, which is a Object, containing a few fields, and a List, and each of those has another List.

So, an object with a List of Lists.

On my View, I represent this as some data, with a list of Tabs (The first list), and then each tab has a grid of data.

In my Knockout View model, I just have:

self.Name = ko.observable("");
self.Width = ko.observable(0);
self.Height = ko.observable(0);

self.TemplateGroups = ko.observableArray();

So, my main object, with an observable array (the first list). But, the list within that, isn't observable.

So when rendering my tabls, I do:

And that renders each tab. And then within each tab, I do this:

('Components' is the name of the list within the outer list)

Problem is, on my ClickIt function, I am displaying the Idof the row I clicked, and it works. And then I am just trying to change the 'Description' field of this outer list, but ... it's not a function, so, no observed:

self.ClickedIt = function () {
    alert(this.Id);
    this.Description("Craig");

}

The alert shows the Id, but error on Description("Craig"), as it's not a function.

How can I make the list, within my ObservableArray, observable?

(To be clearer, my model I pass in is an object, which contains a List called TemplateGroups... and then each item in that list, contains a List called 'Components'. It's the Id of one of those Components that I am displaying, but I need to make that list Observable.

Edit: This seems to be what I am looking for (http://jsfiddle.net/rniemeyer/bZhCk/), but ... I am not defining my array the same way. Instead, they're being passed in from a .Net class (So, converted to JSON, I think). And that .Net class contains a List of another .Net class, which has a List).

Note, My load method:

self.loadData = function () {
        $.get("/api/PlateTemplate/Get", { id: self.TemplateId() }).done(function (data) {
            self.Name(data.Description);
            self.Width(data.Width);
            self.Height(data.Height);
            self.TemplateGroups(data.PlateTemplateGroups);
        });
    }

Body:
The content of self.TemplateGroups is data.PlateTemplateGroups, that is an array and its content are not observable properties (they are javascript objects).

If you want that this objects in this array become observables, you could use the Mapping Plugin:

self.loadData = function () {
    $.get("/api/PlateTemplate/Get", { id: self.TemplateId() }).done(function (data) {
        self.Name(data.Description);
        self.Width(data.Width);
        self.Height(data.Height);
        self.TemplateGroups(
          ko.mapping.fromJS(     //   <--- new
             data.PlateTemplateGroups));
    });
}

This way, all properties become observables.

If you need to convert this data to a Json format you could use ko.mapping.toJS():

ko.mapping.toJS(self.TemplateGroups)


问:
How to include image on left side and text on the right side for rmarkdown presentation
How can this be done in Markdown?

I am using the beamer presentation in Rmarkdown, and I want an image on the left side of a slide and text on the right side of a slide.

Basically, what this does: https://tex.stackexchange.com/questions/165475/figure-next-to-text-in-beamer

But for Markdown not latex.

答:
Use the multicol package:

```<code>---
title: "Untitled"
author: "Martin"
date: "7/9/2017"
output:
  beamer_presentation:
    keep_tex: yes
header-includes:
  - \usepackage{multicol}
---

```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = FALSE)
```

## R Markdow

\begin{multicols}{2}

  \null \vfill
  \includegraphics[width=.3\textwidth]{unnamed.png}
  \vfill \null

\columnbreak

  \null \vfill
  \begin{itemize}
    \item Item 1
    \item Item 2
  \end{itemize}
  \vfill \null
\end{multicols}
</code>```

Body:
Use the multicol package:

---
title: "Untitled"
author: "Martin"
date: "7/9/2017"
output:
  beamer_presentation:
    keep_tex: yes
header-includes:
  - \usepackage{multicol}
---

```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = FALSE)
```

## R Markdow

\begin{multicols}{2}

  \null \vfill
  \includegraphics[width=.3\textwidth]{unnamed.png}
  \vfill \null

\columnbreak

  \null \vfill
  \begin{itemize}
    \item Item 1
    \item Item 2
  \end{itemize}
  \vfill \null
\end{multicols}


问:
C# how to load a form with marquee progress bar?
I created a loadingForm with only a progress bar with marquee style. In my mainForm I'm trying to do this:

```<code>//before downloading
loadingForm lf = new loadingForm();
lf.Show();
//start downloading
//finishdownloading
lf.Close();
</code>```

The loadingForm was shown but the progress bar didn't appear, and the form looked like it was crash. after finishing downloading, the loadingForm was closed and my app continued to run normally. In loadingForm I only have:

```<code>void loadingForm_Load(object sender, EventArgs e)
{
     progressbar1.visible = true;
}
</code>```

I already set progressbar1 style to marquee in loadingForm.design. How do I fix this? thanks for your help in advance.

答:
You should have a look at using BackgroundWorker Class for the time consuming actions, so that the UI can continue showing the progress while the background worker thread does the work.

How to: Use a Background Worker

BackgroundWorker Basics in C#

C# BackgroundWorker Tutorial

Body:
I created a loadingForm with only a progress bar with marquee style. In my mainForm I'm trying to do this:

//before downloading
loadingForm lf = new loadingForm();
lf.Show();
//start downloading
//finishdownloading
lf.Close();

The loadingForm was shown but the progress bar didn't appear, and the form looked like it was crash. after finishing downloading, the loadingForm was closed and my app continued to run normally. In loadingForm I only have:

void loadingForm_Load(object sender, EventArgs e)
{
     progressbar1.visible = true;
}

I already set progressbar1 style to marquee in loadingForm.design. How do I fix this? thanks for your help in advance.


问:
clicking text should click the radio button in HTML
I have this radio button,

```<code> <form class="w3-container w3-card-4">
  <h2>Radio Buttons</h2>
  <p>
  <input class="w3-radio" type="radio" name="gender"  value="male" checked>
  <label >Male</label></p>
  <p>
  <input class="w3-radio" type="radio" name="gender"  value="female">
  <label >Female</label></p>
  <p>
  <input class="w3-radio" type="radio" name="gender" value="" disabled>
   <label>Don't know (Disabled)</label></p>
 </form>
</code>```

The problem is when I click on the label text the radio button is not selected. is there a way to fix this?

答:
you need to include input inside label tag.

 <form class="w3-container w3-card-4">

Radio Buttons

   <input class="w3-radio" type="radio" name="gender"  value="male" checked>
  Male

   <input class="w3-radio" type="radio" name="gender"  value="female">
 Female

  <input class="w3-radio" type="radio" name="gender" value="" >
   Don't know (Disabled)

 </form>```

Body:
I have this radio button,

 <form class="w3-container w3-card-4">

Radio Buttons

  <input class="w3-radio" type="radio" name="gender"  value="male" checked>
  Male

  <input class="w3-radio" type="radio" name="gender"  value="female">
  Female

  <input class="w3-radio" type="radio" name="gender" value="" disabled>
   Don't know (Disabled)

 </form>

The problem is when I click on the label text the radio button is not selected. is there a way to fix this?

Body:
you need to include input inside label tag.

 <form class="w3-container w3-card-4">
  <h2>Radio Buttons</h2>
  <p>
  <label > <input class="w3-radio" type="radio" name="gender"  value="male" checked>
  Male</label></p>
  <p>
   <label ><input class="w3-radio" type="radio" name="gender"  value="female">
 Female</label></p>
  <p>
 <label> <input class="w3-radio" type="radio" name="gender" value="" >
   Don't know (Disabled)</label></p>
 </form>