问:
Sound making function silent when assigned to its own process
I'm working on a kivy app which is intended to parametrically produce ear training exercises on the spot and play them. The music is described using the mingus module, and played via its fluidsynth implementation. I have an exercise playing function, which works as intended when normally called, but since with that method everything else hangs while the drill is running (on an infinite while loop waiting to be manually stopped), that does not result in acceptable behaviour. I assigned the function to its own process using Process(), and based on the the output to the terminal it is looping as intended, but there's no sound. Another point worthy of note is that multiple presses to the start button results in multiple processes running in parallel, judging by the rhythms of the terminal activity. Here's the code of the python side of the interface:

```<code>from kivy.app import App
from kivy.uix.screenmanager import ScreenManager, Screen
from kivy.uix.recycleview import RecycleView
from kivy.uix.label import Label
from kivy.uix.button import Button
from kivy.config import Config
from classes import *
from multiprocessing import Process
import yaml
Config.set('graphics', 'width', '400')
Config.set('graphics', 'height', '700')

class Welcome(Screen):
    pass

class Builtin(Screen):
    pass

class DrillScreen(Screen):
    def __init__(self, **kwargs):
        super(DrillScreen, self).__init__(**kwargs)
        self.options = kwargs['options']
        self.desc = self.options.des
        self.thedrill = drill(self.options)
        desc = Label(
                text=self.options.des,
                size_hint_x=0.9,
                size_hint_y=1)
        button = Button(
                text = 'Start',
                size_hint=[0.4,0.1])
        button.bind(on_release=self.startdrill())
        self.add_widget(desc)
        self.add_widget(button)

    def startdrill(self):
        def starter(*args):
            proc = Process(target=self.thedrill.run)
            proc.start()
        return starter

class BuiltinView(RecycleView):
    def __init__(self, **kwargs):
        super(BuiltinView, self).__init__(**kwargs)
        with open('builtin.yaml', 'r') as builtin:
            self.drills = yaml.load(builtin)
        self.data = [ {'text': self.drills[i]['name'],
            'on_release': self.startermaker(i,self.drills[i])}
            for i in sorted(self.drills.keys()) ]

    def startermaker(self,num,options):
        def startdrill():
            options = drilloptions(self.drills[num])
            drillscreen = DrillScreen(name='drill', options=options)
            app = App.get_running_app()
            app.root.add_widget(drillscreen)
            app.root.current = 'drill'
            #drillscreen.thedrill.run()
        return startdrill

class Manager(ScreenManager):
    pass

class TestingApp(App):
    def build(self):
        return Manager()

TestingApp().run()
</code>```

The drill class holds some parameters in its attributes and enters a loop to endlessly generate exercises within those parameters when its .run() method is called. In the button.bind() statement of the DrillScreen class, if I directly put on_release=self.thedrill.run , I get the function working no problem. I don't know what I'm missing here. I can post code from other components of the project if needed. Thank you.

答:
Well, in trying to produce a small broken example, I stumbled upon a fix. I'm not really sure why it works one way and not the other. Previously fluidsynth was initialized in the .__init__() method of the drill class upon creation, I moved it to the .run() method. Very roughly in almost pseudocode:

Before:

```<code>class drill:
    def __init__(self, opt):
        #Some attribute setting
        self.ex = None #This will instantiate a class describing a single question
        fluidsynth.init(args)

    def run(self):
        while True:
            #Determining randomly the arguments to create Exercise instance

            self.ex = Exercise(args)
            self.ex.play()
</code>```

After:

```<code>class drill:
    def __init__(self, opt):
        #Some attribute setting
        self.ex = None

    def run(self):
        fluidsynth.init(args)
        while True:

            #Determining randomly the arguments to create Exercise instance

            self.ex = Exercise(args)
            self.ex.play()
</code>```

When I call .run() directly with the button.bind(), both versions work. When I assign it to its own process and hand that process to button.bind(), only the second version produces sound. So it seems that roughly what's happening is that an initialized fluidsynth isn't accessible from different processes.

I will delay accepting this answer in case someone delivers non-speculative understanding on the matter.

Body:
I'm working on a kivy app which is intended to parametrically produce ear training exercises on the spot and play them. The music is described using the mingus module, and played via its fluidsynth implementation. I have an exercise playing function, which works as intended when normally called, but since with that method everything else hangs while the drill is running (on an infinite while loop waiting to be manually stopped), that does not result in acceptable behaviour. I assigned the function to its own process using Process(), and based on the the output to the terminal it is looping as intended, but there's no sound. Another point worthy of note is that multiple presses to the start button results in multiple processes running in parallel, judging by the rhythms of the terminal activity. Here's the code of the python side of the interface:

from kivy.app import App
from kivy.uix.screenmanager import ScreenManager, Screen
from kivy.uix.recycleview import RecycleView
from kivy.uix.label import Label
from kivy.uix.button import Button
from kivy.config import Config
from classes import *
from multiprocessing import Process
import yaml
Config.set('graphics', 'width', '400')
Config.set('graphics', 'height', '700')

class Welcome(Screen):
    pass

class Builtin(Screen):
    pass

class DrillScreen(Screen):
    def __init__(self, **kwargs):
        super(DrillScreen, self).__init__(**kwargs)
        self.options = kwargs['options']
        self.desc = self.options.des
        self.thedrill = drill(self.options)
        desc = Label(
                text=self.options.des,
                size_hint_x=0.9,
                size_hint_y=1)
        button = Button(
                text = 'Start',
                size_hint=[0.4,0.1])
        button.bind(on_release=self.startdrill())
        self.add_widget(desc)
        self.add_widget(button)

    def startdrill(self):
        def starter(*args):
            proc = Process(target=self.thedrill.run)
            proc.start()
        return starter

class BuiltinView(RecycleView):
    def __init__(self, **kwargs):
        super(BuiltinView, self).__init__(**kwargs)
        with open('builtin.yaml', 'r') as builtin:
            self.drills = yaml.load(builtin)
        self.data = [ {'text': self.drills[i]['name'],
            'on_release': self.startermaker(i,self.drills[i])}
            for i in sorted(self.drills.keys()) ]

    def startermaker(self,num,options):
        def startdrill():
            options = drilloptions(self.drills[num])
            drillscreen = DrillScreen(name='drill', options=options)
            app = App.get_running_app()
            app.root.add_widget(drillscreen)
            app.root.current = 'drill'
            #drillscreen.thedrill.run()
        return startdrill

class Manager(ScreenManager):
    pass

class TestingApp(App):
    def build(self):
        return Manager()

TestingApp().run()

The drill class holds some parameters in its attributes and enters a loop to endlessly generate exercises within those parameters when its .run() method is called. In the button.bind() statement of the DrillScreen class, if I directly put on_release=self.thedrill.run , I get the function working no problem. I don't know what I'm missing here. I can post code from other components of the project if needed. Thank you.

Body:
Well, in trying to produce a small broken example, I stumbled upon a fix. I'm not really sure why it works one way and not the other. Previously fluidsynth was initialized in the .__init__() method of the drill class upon creation, I moved it to the .run() method. Very roughly in almost pseudocode:

Before:

class drill:
    def __init__(self, opt):
        #Some attribute setting
        self.ex = None #This will instantiate a class describing a single question
        fluidsynth.init(args)

    def run(self):
        while True:
            #Determining randomly the arguments to create Exercise instance

            self.ex = Exercise(args)
            self.ex.play()

After:

class drill:
    def __init__(self, opt):
        #Some attribute setting
        self.ex = None

    def run(self):
        fluidsynth.init(args)
        while True:

            #Determining randomly the arguments to create Exercise instance

            self.ex = Exercise(args)
            self.ex.play()

When I call .run() directly with the button.bind(), both versions work. When I assign it to its own process and hand that process to button.bind(), only the second version produces sound. So it seems that roughly what's happening is that an initialized fluidsynth isn't accessible from different processes.

I will delay accepting this answer in case someone delivers non-speculative understanding on the matter.


来源: stackexchange

问:
PHP - how to randomly get something from array
how can i get something randomly from a array for example i have this array I want to grab one of those lines randomly how can I do that using PHP?

```<code> $quizes = array(
        '3-1' => '2',
        '4+4' => '8',
        '7-5' => '2',
        '4+2' => '6',
        '9-3' => '6',
        '1+2' => '3',
        '9+9' => '18',
        '3+2' => '5',
        '2*3' => '6',
        '5*3' => '15',
        '6+6' => '12',
        '3+4' => '7',
        '7-4' => '3',
        '6+2' => '8',
        '3*2' => '6',
        '7+6' => '13',
        '1+1' => '2',
        '4*4' => '16',
        '10-3' => '7'
    );
</code>```

What i have tried

```<code>$rand_keys = array_rand($quizes, 2);
echo $quizes[$rand_keys[0]] . "\n";
echo $quizes[$rand_keys[1]] . "\n";
</code>```

but this only returns results such as 2 7, 15 2, 3 2 and more

Please help thank you

答:
Well, you are getting exactly what you are asking for - value that belongs to randomly chosen key.
To get key => value pair execute:

```<code>echo $rand_keys[0] . " => " . $quizes[$rand_keys[0]] . "\n";
</code>```

Of course you can format output however you'd like to.

ContentLicense: CC BY-SA 3.0

Body:
how can i get something randomly from a array for example i have this array I want to grab one of those lines randomly how can I do that using PHP?

 $quizes = array(
        '3-1' => '2',
        '4+4' => '8',
        '7-5' => '2',
        '4+2' => '6',
        '9-3' => '6',
        '1+2' => '3',
        '9+9' => '18',
        '3+2' => '5',
        '2*3' => '6',
        '5*3' => '15',
        '6+6' => '12',
        '3+4' => '7',
        '7-4' => '3',
        '6+2' => '8',
        '3*2' => '6',
        '7+6' => '13',
        '1+1' => '2',
        '4*4' => '16',
        '10-3' => '7'
    );

What i have tried

$rand_keys = array_rand($quizes, 2);
echo $quizes[$rand_keys[0]] . "\n";
echo $quizes[$rand_keys[1]] . "\n";

but this only returns results such as 2 7, 15 2, 3 2 and more

Please help thank you

Body:
Well, you are getting exactly what you are asking for - value that belongs to randomly chosen key.
To get key => value pair execute:

echo $rand_keys[0] . " => " . $quizes[$rand_keys[0]] . "\n";

Of course you can format output however you'd like to.


问:
What's the best way to set a single pixel in an HTML5 canvas?
The HTML5 Canvas has no method for explicitly setting a single pixel.

It might be possible to set a pixel using a very short line, but then antialiasing and line caps might interfere.

Another way might be to create a small ImageData object and using:

```<code>context.putImageData(data, x, y)
</code>```

to put it in place.

Can anyone describe an efficient and reliable way of doing this?

答:
Fast HTML Demo code:
Based on what I know about SFML C++ graphics library:

Save this as an HTML file with UTF-8 Encoding and run it.
Feel free to refactor, I just like using japanese variables because
they are concise and don't take up much space

Rarely are you going to want to set ONE arbitrary pixel and display
it on the screen. So use the

```<code>PutPix(x,y, r,g,b,a)
</code>```

method to draw numerous arbitrary pixels to a back-buffer. (cheap calls)

Then when ready to show, call the

```<code>Apply()
</code>```

method to display the changes. (expensive call)

Full .HTML file code below:

```<code><!DOCTYPE HTML >
<html lang="en">
<head>
    <title> back-buffer demo </title>
</head>
<body>

</body>

<script>
//Main function to execute once
//all script is loaded:
function main(){

    //Create a canvas:
    var canvas;
    canvas = attachCanvasToDom();

    //Do the pixel setting test:
    var test_type = FAST_TEST;
    backBufferTest(canvas, test_type);
}

//Constants:
var SLOW_TEST = 1;
var FAST_TEST = 2;

function attachCanvasToDom(){
    //Canvas Creation:
    //cccccccccccccccccccccccccccccccccccccccccc//
    //Create Canvas and append to body:
    var can = document.createElement('canvas');
    document.body.appendChild(can);

    //Make canvas non-zero in size,
    //so we can see it:
    can.width = 800;
    can.height= 600;

    //Get the context, fill canvas to get visual:
    var ctx = can.getContext("2d");
    ctx.fillStyle = "rgba(0, 0, 200, 0.5)";
    ctx.fillRect(0,0,can.width-1, can.height-1);
    //cccccccccccccccccccccccccccccccccccccccccc//

    //Return the canvas that was created:
    return can;
}

//THIS OBJECT IS SLOOOOOWW!
// 筆 == "pen"
//T筆 == "Type:Pen"
function T筆(canvas){

    //Publicly Exposed Functions
    //PEPEPEPEPEPEPEPEPEPEPEPEPEPEPEPEPEPEPEPEPE//
    this.PutPix = _putPix;
    //PEPEPEPEPEPEPEPEPEPEPEPEPEPEPEPEPEPEPEPEPE//

    if(!canvas){
        throw("[NilCanvasGivenToPenConstruct]");
    }

    var _ctx = canvas.getContext("2d");

    //Pixel Setting Test:
    // only do this once per page
    //絵  =="image"
    //資  =="data"
    //絵資=="image data"
    //筆  =="pen"
    var _絵資 = _ctx.createImageData(1,1);
    // only do this once per page
    var _筆  = _絵資.data;

    function _putPix(x,y,  r,g,b,a){
        _筆[0]   = r;
        _筆[1]   = g;
        _筆[2]   = b;
        _筆[3]   = a;
        _ctx.putImageData( _絵資, x, y );
    }
}

//Back-buffer object, for fast pixel setting:
//尻 =="butt,rear" using to mean "back-buffer"
//T尻=="type: back-buffer"
function T尻(canvas){

    //Publicly Exposed Functions
    //PEPEPEPEPEPEPEPEPEPEPEPEPEPEPEPEPEPEPEPEPE//
    this.PutPix = _putPix;
    this.Apply  = _apply;
    //PEPEPEPEPEPEPEPEPEPEPEPEPEPEPEPEPEPEPEPEPE//

    if(!canvas){
        throw("[NilCanvasGivenToPenConstruct]");
    }

    var _can = canvas;
    var _ctx = canvas.getContext("2d");

    //Pixel Setting Test:
    // only do this once per page
    //絵  =="image"
    //資  =="data"
    //絵資=="image data"
    //筆  =="pen"
    var _w = _can.width;
    var _h = _can.height;
    var _絵資 = _ctx.createImageData(_w,_h);
    // only do this once per page
    var _筆  = _絵資.data;

    function _putPix(x,y,  r,g,b,a){

        //Convert XY to index:
        var dex = ( (y*4) *_w) + (x*4);

        _筆[dex+0]   = r;
        _筆[dex+1]   = g;
        _筆[dex+2]   = b;
        _筆[dex+3]   = a;

    }

    function _apply(){
        _ctx.putImageData( _絵資, 0,0 );
    }

}

function backBufferTest(canvas_input, test_type){
    var can = canvas_input; //shorthand var.

    if(test_type==SLOW_TEST){
        var t筆 = new T筆( can );

        //Iterate over entire canvas,
        //and set pixels:
        var x0 = 0;
        var x1 = can.width - 1;

        var y0 = 0;
        var y1 = can.height -1;

        for(var x = x0; x <= x1; x++){
        for(var y = y0; y <= y1; y++){
            t筆.PutPix(
                x,y,
                x%256, y%256,(x+y)%256, 255
            );
        }}//next X/Y

    }else
    if(test_type==FAST_TEST){
        var t尻 = new T尻( can );

        //Iterate over entire canvas,
        //and set pixels:
        var x0 = 0;
        var x1 = can.width - 1;

        var y0 = 0;
        var y1 = can.height -1;

        for(var x = x0; x <= x1; x++){
        for(var y = y0; y <= y1; y++){
            t尻.PutPix(
                x,y,
                x%256, y%256,(x+y)%256, 255
            );
        }}//next X/Y

        //When done setting arbitrary pixels,
        //use the apply method to show them
        //on screen:
        t尻.Apply();

    }
}

main();
</script>
</html>
</code>```

ContentLicense: CC BY-SA 4.0

Body:
The HTML5 Canvas has no method for explicitly setting a single pixel.

It might be possible to set a pixel using a very short line, but then antialiasing and line caps might interfere.

Another way might be to create a small ImageData object and using:

context.putImageData(data, x, y)

to put it in place.

Can anyone describe an efficient and reliable way of doing this?

Body:
Fast HTML Demo code:
Based on what I know about SFML C++ graphics library:

Save this as an HTML file with UTF-8 Encoding and run it.
Feel free to refactor, I just like using japanese variables because
they are concise and don't take up much space

Rarely are you going to want to set ONE arbitrary pixel and display
it on the screen. So use the

PutPix(x,y, r,g,b,a)

method to draw numerous arbitrary pixels to a back-buffer. (cheap calls)

Then when ready to show, call the

Apply()

method to display the changes. (expensive call)

Full .HTML file code below:

<!DOCTYPE HTML >
<html lang="en">
<head>
    <title> back-buffer demo </title>
</head>
<body>

</body>

<script>
//Main function to execute once
//all script is loaded:
function main(){

    //Create a canvas:
    var canvas;
    canvas = attachCanvasToDom();

    //Do the pixel setting test:
    var test_type = FAST_TEST;
    backBufferTest(canvas, test_type);
}

//Constants:
var SLOW_TEST = 1;
var FAST_TEST = 2;

function attachCanvasToDom(){
    //Canvas Creation:
    //cccccccccccccccccccccccccccccccccccccccccc//
    //Create Canvas and append to body:
    var can = document.createElement('canvas');
    document.body.appendChild(can);

    //Make canvas non-zero in size,
    //so we can see it:
    can.width = 800;
    can.height= 600;

    //Get the context, fill canvas to get visual:
    var ctx = can.getContext("2d");
    ctx.fillStyle = "rgba(0, 0, 200, 0.5)";
    ctx.fillRect(0,0,can.width-1, can.height-1);
    //cccccccccccccccccccccccccccccccccccccccccc//

    //Return the canvas that was created:
    return can;
}

//THIS OBJECT IS SLOOOOOWW!
// 筆 == "pen"
//T筆 == "Type:Pen"
function T筆(canvas){

    //Publicly Exposed Functions
    //PEPEPEPEPEPEPEPEPEPEPEPEPEPEPEPEPEPEPEPEPE//
    this.PutPix = _putPix;
    //PEPEPEPEPEPEPEPEPEPEPEPEPEPEPEPEPEPEPEPEPE//

    if(!canvas){
        throw("[NilCanvasGivenToPenConstruct]");
    }

    var _ctx = canvas.getContext("2d");

    //Pixel Setting Test:
    // only do this once per page
    //絵  =="image"
    //資  =="data"
    //絵資=="image data"
    //筆  =="pen"
    var _絵資 = _ctx.createImageData(1,1);
    // only do this once per page
    var _筆  = _絵資.data;

    function _putPix(x,y,  r,g,b,a){
        _筆[0]   = r;
        _筆[1]   = g;
        _筆[2]   = b;
        _筆[3]   = a;
        _ctx.putImageData( _絵資, x, y );
    }
}

//Back-buffer object, for fast pixel setting:
//尻 =="butt,rear" using to mean "back-buffer"
//T尻=="type: back-buffer"
function T尻(canvas){

    //Publicly Exposed Functions
    //PEPEPEPEPEPEPEPEPEPEPEPEPEPEPEPEPEPEPEPEPE//
    this.PutPix = _putPix;
    this.Apply  = _apply;
    //PEPEPEPEPEPEPEPEPEPEPEPEPEPEPEPEPEPEPEPEPE//

    if(!canvas){
        throw("[NilCanvasGivenToPenConstruct]");
    }

    var _can = canvas;
    var _ctx = canvas.getContext("2d");

    //Pixel Setting Test:
    // only do this once per page
    //絵  =="image"
    //資  =="data"
    //絵資=="image data"
    //筆  =="pen"
    var _w = _can.width;
    var _h = _can.height;
    var _絵資 = _ctx.createImageData(_w,_h);
    // only do this once per page
    var _筆  = _絵資.data;

    function _putPix(x,y,  r,g,b,a){

        //Convert XY to index:
        var dex = ( (y*4) *_w) + (x*4);

        _筆[dex+0]   = r;
        _筆[dex+1]   = g;
        _筆[dex+2]   = b;
        _筆[dex+3]   = a;

    }

    function _apply(){
        _ctx.putImageData( _絵資, 0,0 );
    }

}

function backBufferTest(canvas_input, test_type){
    var can = canvas_input; //shorthand var.

    if(test_type==SLOW_TEST){
        var t筆 = new T筆( can );

        //Iterate over entire canvas,
        //and set pixels:
        var x0 = 0;
        var x1 = can.width - 1;

        var y0 = 0;
        var y1 = can.height -1;

        for(var x = x0; x <= x1; x++){
        for(var y = y0; y <= y1; y++){
            t筆.PutPix(
                x,y,
                x%256, y%256,(x+y)%256, 255
            );
        }}//next X/Y

    }else
    if(test_type==FAST_TEST){
        var t尻 = new T尻( can );

        //Iterate over entire canvas,
        //and set pixels:
        var x0 = 0;
        var x1 = can.width - 1;

        var y0 = 0;
        var y1 = can.height -1;

        for(var x = x0; x <= x1; x++){
        for(var y = y0; y <= y1; y++){
            t尻.PutPix(
                x,y,
                x%256, y%256,(x+y)%256, 255
            );
        }}//next X/Y

        //When done setting arbitrary pixels,
        //use the apply method to show them
        //on screen:
        t尻.Apply();

    }
}

main();
</script>
</html>


问:
Attaching metadata to Bugsnag with Laravel
Reading the documentation I found that I can append data to a threw Exception this way:

```<code>Bugsnag::setMetaData([
    'account' => [
        'paying' => true,
        'name' => 'Acme Co'
    ]
]);
</code>```

I want to append the user email. Where should I place this code? I added it to Handler@render but the information is not being showed in the dashboard

答:
render() comes after report() in the exception flow, so if you're reporting to bugsnag in report() and setting metadata in render() it won't work:

https://github.com/laravel/framework/blob/cb48cf54fcd16a8cac246fcb98340cc2c9ed6b5a/src/Illuminate/Foundation/Bootstrap/HandleExceptions.php#L80-L86

Your bugsnag code should all be going into report() since you're reporting the error to an external service.

In any case, it's hard to provide any further information without seeing what you're actually doing in your exception handler.

Body:
Reading the documentation I found that I can append data to a threw Exception this way:

Bugsnag::setMetaData([
    'account' => [
        'paying' => true,
        'name' => 'Acme Co'
    ]
]);

I want to append the user email. Where should I place this code? I added it to Handler@render but the information is not being showed in the dashboard


问:
Java app does not start after successful gradle build in eclipse
Simple java libgdx hello world builds sucecssful with gradle(new to gradle) build tool from eclipse, but it does not start.
I.e. I get ton of green buttons in graddle executions tab, and BUILD SUCCESSFUL in console tab. I cant find any errors that something went wrong and application could not start or any runtime errors. Nothing.
All instructions Ive been able to find on internets only tells how to build, none tells how to start the newly built application.</p>

答: Thx, I finally got it work, it was exactly gradle run (gradlew run on windows) in the project folder.</p>


问:
Exception in thread "main" java.io.StreamCorruptedException: invalid stream header: 0BDAACED
I am trying to execute jenkins cli command from master.

ssh user@192.168.1.2 -C "/usr/bin/java -jar /home/user/slave.jar"

Getting following error:

```<code><===[JENKINS REMOTING CAPACITY]===>Exception in thread "main" java.io.StreamCorruptedException: invalid stream header: 0BDAACED
  at java.io.ObjectInputStream.readStreamHeader(ObjectInputStream.java:808)
  at java.io.ObjectInputStream.<init>(ObjectInputStream.java:301)
  at hudson.remoting.ObjectInputStreamEx.<init>(ObjectInputStreamEx.java:48)
  at hudson.remoting.ChannelBuilder.makeTransport(ChannelBuilder.java:430)
  at hudson.remoting.ChannelBuilder.negotiate(ChannelBuilder.java:389)
  at hudson.remoting.ChannelBuilder.build(ChannelBuilder.java:310)
  at hudson.remoting.Launcher.main(Launcher.java:528)
  at hudson.remoting.Launcher.runWithStdinStdout(Launcher.java:468)
  at hudson.remoting.Launcher.run(Launcher.java:242)
  at hudson.remoting.Launcher.main(Launcher.java:195)
ERROR: Unexpected error in launching an agent. This is probably a bug in Jenkins
hudson.remoting.RequestAbortedException: java.io.IOException: Unexpected EOF
  at hudson.remoting.Request.abort(Request.java:303)
  at hudson.remoting.Channel.terminate(Channel.java:847)
  at hudson.remoting.SynchronousCommandTransport$ReaderThread.run(SynchronousCommandTransport.java:92)
  at ......remote call to ubuntu-slave(Native Method)
  at hudson.remoting.Channel.attachCallSiteStackTrace(Channel.java:1416)
  at hudson.remoting.Request.call(Request.java:172)
  at hudson.remoting.Channel.call(Channel.java:780)
  at hudson.slaves.SlaveComputer.setChannel(SlaveComputer.java:508)
  at hudson.slaves.SlaveComputer.setChannel(SlaveComputer.java:381)
  at hudson.slaves.CommandLauncher.launch(CommandLauncher.java:131)
  at hudson.slaves.SlaveComputer$1.call(SlaveComputer.java:253)
  at jenkins.util.ContextResettingExecutorService$2.call(ContextResettingExecutorService.java:46)
  at java.util.concurrent.FutureTask.run(FutureTask.java:266)
  at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
  at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
  at java.lang.Thread.run(Thread.java:745)
Caused by: java.io.IOException: Unexpected EOF
  at hudson.remoting.ChunkedInputStream.readUntilBreak(ChunkedInputStream.java:99)
  at hudson.remoting.ChunkedCommandTransport.readBlock(ChunkedCommandTransport.java:39)
  at hudson.remoting.AbstractSynchronousByteArrayCommandTransport.read(AbstractSynchronousByteArrayCommandTransport.java:34)
  at hudson.remoting.SynchronousCommandTransport$ReaderThread.run(SynchronousCommandTransport.java:59)
ERROR: Connection terminated
java.io.IOException: Unexpected EOF
  at hudson.remoting.ChunkedInputStream.readUntilBreak(ChunkedInputStream.java:99)
  at hudson.remoting.ChunkedCommandTransport.readBlock(ChunkedCommandTransport.java:39)
  at hudson.remoting.AbstractSynchronousByteArrayCommandTransport.read(AbstractSynchronousByteArrayCommandTransport.java:34)
  at hudson.remoting.SynchronousCommandTransport$ReaderThread.run(SynchronousCommandTransport.java:59)
ERROR: Process terminated with exit code 1
</code>```

Please tell me what could be the problem?

答:
The short answer

Jenkins' slave.jar communicates with the Jenkins server through the slave's stdin/stdout. You rely on ssh to transfer stdin/stdout to/from the slave.

Something that you are not aware of tampers with the stdin before it reaches the slave, and the resulting communication protocol violation causes the exception that you see.

The longer explanation and a fix

I suppose that you have the ssh command from your question, which starts the slave, in a shell script on the jenkins server, and that this shell script also has other commands in it that precede this command. Because this is how it was in my case, inspired by the jenkins remoting documetation that suggests you could do things like copying the correct slave.jar to the slave.

So we are both using the "Launch agent via execution of command on the server" option to start the slave agent. In my case I do this to be able to use an ssh jump host to reach the slave, but this is not of relevance to this answer.

I will now give examples of non-working and working shell scripts to start  a slave.jar on a remote node, and then come up with reasoning of what might cause the observed behaviour. I use /bin/bash as the shell, feel free to use others.

1) These versions both work if you already have slave.jar on the slave

```<code>#!/bin/bash
ssh user@host "java -jar /home/user/slave.jar"
</code>```

.

```<code>#!/bin/bash
exec ssh user@host "java -jar /home/user/slave.jar"
</code>```

Both versions have only a single command in them. Nothing else is in here that tampers with stdin or stdout. In the first version, the shell lingers around and forwards stdin/stdout to/from the ssh command. In the second version, the shell is replaced by the ssh process and directly inherits its stdin/stdout. Both versions work ok, and the additional shell process in the first version should not matter on any system.

2) This version copies slave.jar from some location on the server to the slave before executing it on the slave

```<code>#!/bin/bash
scp -q /some/location/slave.jar user@host:.
exec ssh user@host "java -jar /home/user/slave.jar"
</code>```

Of course, this only works if you have /some/location/slave.jar on the server.

3) This version tries to do some additional cleanup on the slave before starting the slave agent.

```<code>#!/bin/bash
ssh user@host "rm -rf /home/user/tmp/jenkins"
exec ssh user@host "java -jar /home/user/slave.jar"
</code>```

The /home/user/tmp/jenkins location on the slave is just an example.
This version fails after a 4 minute timeout. With the exact error message from the question. The failure is not caused by anything important missing from /home/user/tmp/jenkins, as you will see in the next example:

4) Different ways to make example 3 work

```<code>#!/bin/bash
ssh user@host "rm -rf /home/user/tmp/jenkins" </dev/null
exec ssh user@host "java -jar /home/user/slave.jar"
</code>```

.

```<code>#!/bin/bash
exec ssh user@host "rm -rf /home/user/tmp/jenkins && java -jar /home/user/slave.jar"
</code>```

In the first fix, we make sure stdin to communicate with the slave is not forwarded to the remote rm command. rm does not read its stdin, but apparently ssh does not know that and buffers some bytes from its own stdin and forwards them to the remote command just in case it is needed? This is fixed by forwarding /dev/null as stdin to the rm command instead of the stdin destined for the slave communication.

In the second fix, only one ssh command is used, the rm command again does not read anything from stdin, and the slave.jar receives the untampered stream.

Body:
I am trying to execute jenkins cli command from master.

ssh user@192.168.1.2 -C "/usr/bin/java -jar /home/user/slave.jar"

Getting following error:

<===[JENKINS REMOTING CAPACITY]===>Exception in thread "main" java.io.StreamCorruptedException: invalid stream header: 0BDAACED
  at java.io.ObjectInputStream.readStreamHeader(ObjectInputStream.java:808)
  at java.io.ObjectInputStream.<init>(ObjectInputStream.java:301)
  at hudson.remoting.ObjectInputStreamEx.<init>(ObjectInputStreamEx.java:48)
  at hudson.remoting.ChannelBuilder.makeTransport(ChannelBuilder.java:430)
  at hudson.remoting.ChannelBuilder.negotiate(ChannelBuilder.java:389)
  at hudson.remoting.ChannelBuilder.build(ChannelBuilder.java:310)
  at hudson.remoting.Launcher.main(Launcher.java:528)
  at hudson.remoting.Launcher.runWithStdinStdout(Launcher.java:468)
  at hudson.remoting.Launcher.run(Launcher.java:242)
  at hudson.remoting.Launcher.main(Launcher.java:195)
ERROR: Unexpected error in launching an agent. This is probably a bug in Jenkins
hudson.remoting.RequestAbortedException: java.io.IOException: Unexpected EOF
  at hudson.remoting.Request.abort(Request.java:303)
  at hudson.remoting.Channel.terminate(Channel.java:847)
  at hudson.remoting.SynchronousCommandTransport$ReaderThread.run(SynchronousCommandTransport.java:92)
  at ......remote call to ubuntu-slave(Native Method)
  at hudson.remoting.Channel.attachCallSiteStackTrace(Channel.java:1416)
  at hudson.remoting.Request.call(Request.java:172)
  at hudson.remoting.Channel.call(Channel.java:780)
  at hudson.slaves.SlaveComputer.setChannel(SlaveComputer.java:508)
  at hudson.slaves.SlaveComputer.setChannel(SlaveComputer.java:381)
  at hudson.slaves.CommandLauncher.launch(CommandLauncher.java:131)
  at hudson.slaves.SlaveComputer$1.call(SlaveComputer.java:253)
  at jenkins.util.ContextResettingExecutorService$2.call(ContextResettingExecutorService.java:46)
  at java.util.concurrent.FutureTask.run(FutureTask.java:266)
  at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
  at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
  at java.lang.Thread.run(Thread.java:745)
Caused by: java.io.IOException: Unexpected EOF
  at hudson.remoting.ChunkedInputStream.readUntilBreak(ChunkedInputStream.java:99)
  at hudson.remoting.ChunkedCommandTransport.readBlock(ChunkedCommandTransport.java:39)
  at hudson.remoting.AbstractSynchronousByteArrayCommandTransport.read(AbstractSynchronousByteArrayCommandTransport.java:34)
  at hudson.remoting.SynchronousCommandTransport$ReaderThread.run(SynchronousCommandTransport.java:59)
ERROR: Connection terminated
java.io.IOException: Unexpected EOF
  at hudson.remoting.ChunkedInputStream.readUntilBreak(ChunkedInputStream.java:99)
  at hudson.remoting.ChunkedCommandTransport.readBlock(ChunkedCommandTransport.java:39)
  at hudson.remoting.AbstractSynchronousByteArrayCommandTransport.read(AbstractSynchronousByteArrayCommandTransport.java:34)
  at hudson.remoting.SynchronousCommandTransport$ReaderThread.run(SynchronousCommandTransport.java:59)
ERROR: Process terminated with exit code 1

Please tell me what could be the problem?

Body:
The short answer

Jenkins' slave.jar communicates with the Jenkins server through the slave's stdin/stdout. You rely on ssh to transfer stdin/stdout to/from the slave.

Something that you are not aware of tampers with the stdin before it reaches the slave, and the resulting communication protocol violation causes the exception that you see.

The longer explanation and a fix

I suppose that you have the ssh command from your question, which starts the slave, in a shell script on the jenkins server, and that this shell script also has other commands in it that precede this command. Because this is how it was in my case, inspired by the jenkins remoting documetation that suggests you could do things like copying the correct slave.jar to the slave.

So we are both using the "Launch agent via execution of command on the server" option to start the slave agent. In my case I do this to be able to use an ssh jump host to reach the slave, but this is not of relevance to this answer.

I will now give examples of non-working and working shell scripts to start  a slave.jar on a remote node, and then come up with reasoning of what might cause the observed behaviour. I use /bin/bash as the shell, feel free to use others.

1) These versions both work if you already have slave.jar on the slave

#!/bin/bash
ssh user@host "java -jar /home/user/slave.jar"

.

#!/bin/bash
exec ssh user@host "java -jar /home/user/slave.jar"

Both versions have only a single command in them. Nothing else is in here that tampers with stdin or stdout. In the first version, the shell lingers around and forwards stdin/stdout to/from the ssh command. In the second version, the shell is replaced by the ssh process and directly inherits its stdin/stdout. Both versions work ok, and the additional shell process in the first version should not matter on any system.

2) This version copies slave.jar from some location on the server to the slave before executing it on the slave

#!/bin/bash
scp -q /some/location/slave.jar user@host:.
exec ssh user@host "java -jar /home/user/slave.jar"

Of course, this only works if you have /some/location/slave.jar on the server.

3) This version tries to do some additional cleanup on the slave before starting the slave agent.

#!/bin/bash
ssh user@host "rm -rf /home/user/tmp/jenkins"
exec ssh user@host "java -jar /home/user/slave.jar"

The /home/user/tmp/jenkins location on the slave is just an example.
This version fails after a 4 minute timeout. With the exact error message from the question. The failure is not caused by anything important missing from /home/user/tmp/jenkins, as you will see in the next example:

4) Different ways to make example 3 work

#!/bin/bash
ssh user@host "rm -rf /home/user/tmp/jenkins" </dev/null
exec ssh user@host "java -jar /home/user/slave.jar"

.

#!/bin/bash
exec ssh user@host "rm -rf /home/user/tmp/jenkins && java -jar /home/user/slave.jar"

In the first fix, we make sure stdin to communicate with the slave is not forwarded to the remote rm command. rm does not read its stdin, but apparently ssh does not know that and buffers some bytes from its own stdin and forwards them to the remote command just in case it is needed? This is fixed by forwarding /dev/null as stdin to the rm command instead of the stdin destined for the slave communication.

In the second fix, only one ssh command is used, the rm command again does not read anything from stdin, and the slave.jar receives the untampered stream.


问:
Make simply HTTP request and receive the content
I have found a working code for makeing simply HTTP requests here, from How can I make a simple HTTP request in MainActivity.java? (Android Studio) and I am going to post it below (with some changes, if I am not wrong it is now necessery to use try{} catch{}). But I would like to ask how I can receive the content? I work with the code in the following way:

```<code>GetUrlContentTask req = new GetUrlContentTask();
req.execute("http://192.168.1.10/?pin=OFF1");
textView3.setText(req.doInBackground("http://192.168.1.10/?pin=OFF1"));
</code>```

GetUrlContentTask

```<code>private class GetUrlContentTask extends AsyncTask<String, Integer, String> {
    protected String doInBackground(String... urls) {
        // String content1 = "";
        try {
            URL url = new URL(urls[0]);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("GET");
            connection.setDoOutput(true);
            connection.connect();

            BufferedReader rd = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            String content = "", line;
            while ((line = rd.readLine()) != null) {
                content += line + "\n";
            }
            // content1 = content;
        }
        catch (Exception e) {
            e.printStackTrace();
        }

        // return content1; - returns "", wrong
        return "aaa";
        //does not work    return content;
    }

    protected void onProgressUpdate(Integer... progress) {
    }

    protected void onPostExecute(String result) {
        // this is executed on the main thread after the process is over
        // update your UI here
    }
}
</code>```

答:
Add this to your onPostExecute(String result) call

```<code>    protected void onPostExecute(String result) {
        // this is executed on the main thread after the process is over
        // update your UI here
        setMyData(result);
    }
</code>```

And then fill your textfield or whatever other data you need to update.

```<code>    private void setMyData(String result){
        textView3.setText(result);
    }
</code>```

Body:
I have found a working code for makeing simply HTTP requests here, from How can I make a simple HTTP request in MainActivity.java? (Android Studio) and I am going to post it below (with some changes, if I am not wrong it is now necessery to use try{} catch{}). But I would like to ask how I can receive the content? I work with the code in the following way:

GetUrlContentTask req = new GetUrlContentTask();
req.execute("http://192.168.1.10/?pin=OFF1");
textView3.setText(req.doInBackground("http://192.168.1.10/?pin=OFF1"));

GetUrlContentTask

private class GetUrlContentTask extends AsyncTask<String, Integer, String> {
    protected String doInBackground(String... urls) {
        // String content1 = "";
        try {
            URL url = new URL(urls[0]);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("GET");
            connection.setDoOutput(true);
            connection.connect();

            BufferedReader rd = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            String content = "", line;
            while ((line = rd.readLine()) != null) {
                content += line + "\n";
            }
            // content1 = content;
        }
        catch (Exception e) {
            e.printStackTrace();
        }

        // return content1; - returns "", wrong
        return "aaa";
        //does not work    return content;
    }

    protected void onProgressUpdate(Integer... progress) {
    }

    protected void onPostExecute(String result) {
        // this is executed on the main thread after the process is over
        // update your UI here
    }
}

Body:
Add this to your onPostExecute(String result) call

    protected void onPostExecute(String result) {
        // this is executed on the main thread after the process is over
        // update your UI here
        setMyData(result);
    }

And then fill your textfield or whatever other data you need to update.

    private void setMyData(String result){
        textView3.setText(result);
    }


问:
choose n largest elements in two vector
I have two vectors, each contains n unsorted elements, how can I get n largest elements in these two vectors?

my solution is merge two vector into one with 2n elements, and then use std::nth_element algorithm, but I found that's not quite efficient, so anyone has more efficient solution. Really appreciate.

答:
You can do the "n'th element" algorithm conceptually in parallel on the two vectors quite easiely (at least the simple variant that's only linear in the average case).

Pick a pivot.

Partition (std::partition) both vectors by that pivot. You'll have the first vector partitioned by some element with rank i and the second by some element with rank j. I'm assuming descending order here.

If i+j < n, recurse on the right side for the n-i-j greatest elements. If i+j > n, recurse on the left side for the n greatest elements. If you hit i+j==n, stop the recursion.

You basically just need to make sure to partition both vectors by the same pivot in every step. Given a decent pivot selection, this algorithm is linear in the average case (and works in-place).

See also: http://en.wikipedia.org/wiki/Selection_algorithm#Partition-based_general_selection_algorithm

Edit: (hopefully) clarified the algorithm a bit.

ContentLicense: CC BY-SA 2.5

Title: choose n largest elements in two vector


问:
TextInput Doesn't Get Focus Inside a Modal - React Native Android
I have 4 TextInputs in a Modal, the first TextInput get the focus without any problem, but the rest don't get focus. To be more accurate when you click it seems that they get the focus and loose as soon as they get it.

```<code> <Modal
   animationType={"fade"}
   transparent={false}
   visible={modalVisible}
   onRequestClose={() => {alert("Modal has been closed.")}}
   >
  <View style={{paddingTop: 22, height: Dimensions.get('window').height , backgroundColor: 'rgba(252,84,102,0.9)'}}>
   <View style={{flex: 1, alignItems: 'center', justifyContent: 'center'}}>
     <View style={{flex: 1, justifyContent: 'flex-start', alignItems: 'center'}}>
       <View style={{flex: 0.2, flexDirection: 'row', alignItems: 'flex-start', justifyContent: 'flex-start'}}>
         <TouchableHighlight underlayColor={'rgba(0,0,0,0)'} style={{flex: 0.2, left: 20, alignItems: 'flex-start', justifyContent: 'flex-start'}} onPress={() => {
           setModalVisible(!modalVisible)
         }}>
           <Text style={{textAlign: 'center', color: 'white', fontSize: 35}}>X</Text>
         </TouchableHighlight>
         <View style={{flex: 0.8}}></View>
       </View>
       <View style={{flex: 0.6, width: Dimensions.get('window').width, alignItems: 'center', justifyContent: 'center', bottom: 100}}>
         <View style={{height: 180, width: 280, backgroundColor: '#5CA4F9', elevation: 5, borderRadius: 5}}>
           <View style={{flex: 0.25}}>
             <Text style={{marginVertical: 5, marginHorizontal: 10, color: 'white', fontFamily: helpers.getFont(), fontSize: 18}}>
               Credit Card
             </Text>
           </View>
           <View style={{flex: 0.25, justifyContent: 'center', alignItems: 'center', marginVertical: 5}}>
             <TextInput style={{flex: 1, width: 260, backgroundColor: 'white', borderRadius: 5}} placeholder="Card Name Holder"/>
           </View>
           <View style={{flex: 0.25, justifyContent: 'center', alignItems: 'center', marginVertical: 5}}>
             <TextInput style={{flex: 1, width: 260, backgroundColor: 'white', borderRadius: 5}} placeholder="Card Number"/>
           </View>
           <View style={{flex: 0.25, flexDirection: 'row', justifyContent: 'center', alignItems: 'center', marginVertical: 10}}>
             <View style={{flex: 0.5, justifyContent: 'center', alignItems: 'center', marginHorizontal: 5}}>
               <TextInput style={{flex:1, width: 120, backgroundColor: 'white', borderRadius: 5}} placeholder="Expires (12/20)"/>
             </View>
             <View style={{flex: 0.5, justifyContent: 'center', alignItems: 'center', marginHorizontal: 5}}>
               <TextInput style={{flex:1, width: 120, backgroundColor: 'white', borderRadius: 5}} placeholder="CSV Number"/>
             </View>
           </View>
         </View>
         <View style={{height: Dimensions.get('window').height * 0.35, width: Dimensions.get('window').width * 0.9, backgroundColor: 'white', bottom: 100,  borderRadius: 5, justifyContent: 'center', alignItems: 'center'}}>
           <View style={{flex: 0.5}}>
           </View>
           <Text style={{flex: 0.1, fontFamily: helpers.getFont(), fontSize: 16, fontWeight: '500'}}>
             Enter your card information above.
           </Text>
           <View style={{flex: 0.1}}></View>
           <TouchableHighlight style={{flex: 0.2, height: 10, width: Dimensions.get('window').width * 0.70, backgroundColor: 'rgba(84,191,175,1)', justifyContent: 'center', alignItems: 'center', borderRadius: 3}}>
             <Text style={{fontFamily: helpers.getFont(), color: 'white', fontSize: 18, justifyContent: 'center', alignItems: 'center'}}>
               Add Card
             </Text>
           </TouchableHighlight>
           <View style={{flex: 0.1}}></View>
         </View>
       </View>
     </View>
   </View>
  </View>
 </Modal>
</code>```

I am also attaching a gif to further illustrate the problem I am facing

答:
I finally found the solution to this, the reason behind the problem I was facing it's because two views were overlapping siblings views were and they interfered with each other. What I had to do to solve this problem is swap the places of the two siblings. Here is my solution: </p>

```<code>   <View style={{height: Dimensions.get('window').height * 0.35, width: Dimensions.get('window').width * 0.9, backgroundColor: 'white', top: 100,  borderRadius: 5, justifyContent: 'center', alignItems: 'center'}}>
         <View style={{flex: 0.5}}>
         </View>
         <Text style={{flex: 0.1, fontFamily: helpers.getFont(), fontSize: 16, fontWeight: '500'}}>
           Enter your card information above.
         </Text>
         <View style={{flex: 0.1}}></View>
         <TouchableHighlight style={{flex: 0.2, height: 10, width: Dimensions.get('window').width * 0.70, backgroundColor: 'rgba(84,191,175,1)', justifyContent: 'center', alignItems: 'center', borderRadius: 3}}>
           <Text style={{fontFamily: helpers.getFont(), color: 'white', fontSize: 18, justifyContent: 'center', alignItems: 'center'}}>
             Add Card
           </Text>
         </TouchableHighlight>
         <View style={{flex: 0.1}}></View>
       </View>
       <View style={{flex: 0.6, width: Dimensions.get('window').width, alignItems: 'center', justifyContent: 'center', bottom: 260}}>
         <View style={{height: 180, width: 280, backgroundColor: '#5CA4F9', elevation: 5, borderRadius: 5}}>
           <View style={{flex: 0.25}}>
             <Text style={{marginVertical: 5, marginHorizontal: 10, color: 'white', fontFamily: helpers.getFont(), fontSize: 18}}>
               Credit Card
             </Text>
           </View>
           <View style={{flex: 0.25, justifyContent: 'center', alignItems: 'center', marginVertical: 5}}>
             <TextInput style={{flex: 1, width: 260, backgroundColor: 'white', borderRadius: 5}} placeholder="Card Name Holder"/>
           </View>
           <View style={{flex: 0.25, justifyContent: 'center', alignItems: 'center', marginVertical: 5}}>
             <TextInput style={{flex: 1, width: 260, backgroundColor: 'white', borderRadius: 5}} placeholder="Card Number"/>
           </View>
           <View style={{flex: 0.25, flexDirection: 'row', justifyContent: 'center', alignItems: 'center', marginVertical: 10}}>
             <View style={{flex: 0.5, justifyContent: 'center', alignItems: 'center', marginHorizontal: 5}}>
               <TextInput style={{flex:1, width: 120, backgroundColor: 'white', borderRadius: 5}} placeholder="Expires (12/20)"/>
             </View>
             <View style={{flex: 0.5, justifyContent: 'center', alignItems: 'center', marginHorizontal: 5}}>
               <TextInput style={{flex:1, width: 120, backgroundColor: 'white', borderRadius: 5}} placeholder="CSV Number"/>
             </View>
           </View>
         </View>
</code>```

Body:
I have 4 TextInputs in a Modal, the first TextInput get the focus without any problem, but the rest don't get focus. To be more accurate when you click it seems that they get the focus and loose as soon as they get it.

 <Modal
   animationType={"fade"}
   transparent={false}
   visible={modalVisible}
   onRequestClose={() => {alert("Modal has been closed.")}}
   >
  <View style={{paddingTop: 22, height: Dimensions.get('window').height , backgroundColor: 'rgba(252,84,102,0.9)'}}>
   <View style={{flex: 1, alignItems: 'center', justifyContent: 'center'}}>
     <View style={{flex: 1, justifyContent: 'flex-start', alignItems: 'center'}}>
       <View style={{flex: 0.2, flexDirection: 'row', alignItems: 'flex-start', justifyContent: 'flex-start'}}>
         <TouchableHighlight underlayColor={'rgba(0,0,0,0)'} style={{flex: 0.2, left: 20, alignItems: 'flex-start', justifyContent: 'flex-start'}} onPress={() => {
           setModalVisible(!modalVisible)
         }}>
           <Text style={{textAlign: 'center', color: 'white', fontSize: 35}}>X</Text>
         </TouchableHighlight>
         <View style={{flex: 0.8}}></View>
       </View>
       <View style={{flex: 0.6, width: Dimensions.get('window').width, alignItems: 'center', justifyContent: 'center', bottom: 100}}>
         <View style={{height: 180, width: 280, backgroundColor: '#5CA4F9', elevation: 5, borderRadius: 5}}>
           <View style={{flex: 0.25}}>
             <Text style={{marginVertical: 5, marginHorizontal: 10, color: 'white', fontFamily: helpers.getFont(), fontSize: 18}}>
               Credit Card
             </Text>
           </View>
           <View style={{flex: 0.25, justifyContent: 'center', alignItems: 'center', marginVertical: 5}}>
             <TextInput style={{flex: 1, width: 260, backgroundColor: 'white', borderRadius: 5}} placeholder="Card Name Holder"/>
           </View>
           <View style={{flex: 0.25, justifyContent: 'center', alignItems: 'center', marginVertical: 5}}>
             <TextInput style={{flex: 1, width: 260, backgroundColor: 'white', borderRadius: 5}} placeholder="Card Number"/>
           </View>
           <View style={{flex: 0.25, flexDirection: 'row', justifyContent: 'center', alignItems: 'center', marginVertical: 10}}>
             <View style={{flex: 0.5, justifyContent: 'center', alignItems: 'center', marginHorizontal: 5}}>
               <TextInput style={{flex:1, width: 120, backgroundColor: 'white', borderRadius: 5}} placeholder="Expires (12/20)"/>
             </View>
             <View style={{flex: 0.5, justifyContent: 'center', alignItems: 'center', marginHorizontal: 5}}>
               <TextInput style={{flex:1, width: 120, backgroundColor: 'white', borderRadius: 5}} placeholder="CSV Number"/>
             </View>
           </View>
         </View>
         <View style={{height: Dimensions.get('window').height * 0.35, width: Dimensions.get('window').width * 0.9, backgroundColor: 'white', bottom: 100,  borderRadius: 5, justifyContent: 'center', alignItems: 'center'}}>
           <View style={{flex: 0.5}}>
           </View>
           <Text style={{flex: 0.1, fontFamily: helpers.getFont(), fontSize: 16, fontWeight: '500'}}>
             Enter your card information above.
           </Text>
           <View style={{flex: 0.1}}></View>
           <TouchableHighlight style={{flex: 0.2, height: 10, width: Dimensions.get('window').width * 0.70, backgroundColor: 'rgba(84,191,175,1)', justifyContent: 'center', alignItems: 'center', borderRadius: 3}}>
             <Text style={{fontFamily: helpers.getFont(), color: 'white', fontSize: 18, justifyContent: 'center', alignItems: 'center'}}>
               Add Card
             </Text>
           </TouchableHighlight>
           <View style={{flex: 0.1}}></View>
         </View>
       </View>
     </View>
   </View>
  </View>
 </Modal>

I am also attaching a gif to further illustrate the problem I am facing

Body:
I finally found the solution to this, the reason behind the problem I was facing it's because two views were overlapping siblings views were and they interfered with each other. What I had to do to solve this problem is swap the places of the two siblings. Here is my solution:

   <View style={{height: Dimensions.get('window').height * 0.35, width: Dimensions.get('window').width * 0.9, backgroundColor: 'white', top: 100,  borderRadius: 5, justifyContent: 'center', alignItems: 'center'}}>
         <View style={{flex: 0.5}}>
         </View>
         <Text style={{flex: 0.1, fontFamily: helpers.getFont(), fontSize: 16, fontWeight: '500'}}>
           Enter your card information above.
         </Text>
         <View style={{flex: 0.1}}></View>
         <TouchableHighlight style={{flex: 0.2, height: 10, width: Dimensions.get('window').width * 0.70, backgroundColor: 'rgba(84,191,175,1)', justifyContent: 'center', alignItems: 'center', borderRadius: 3}}>
           <Text style={{fontFamily: helpers.getFont(), color: 'white', fontSize: 18, justifyContent: 'center', alignItems: 'center'}}>
             Add Card
           </Text>
         </TouchableHighlight>
         <View style={{flex: 0.1}}></View>
       </View>
       <View style={{flex: 0.6, width: Dimensions.get('window').width, alignItems: 'center', justifyContent: 'center', bottom: 260}}>
         <View style={{height: 180, width: 280, backgroundColor: '#5CA4F9', elevation: 5, borderRadius: 5}}>
           <View style={{flex: 0.25}}>
             <Text style={{marginVertical: 5, marginHorizontal: 10, color: 'white', fontFamily: helpers.getFont(), fontSize: 18}}>
               Credit Card
             </Text>
           </View>
           <View style={{flex: 0.25, justifyContent: 'center', alignItems: 'center', marginVertical: 5}}>
             <TextInput style={{flex: 1, width: 260, backgroundColor: 'white', borderRadius: 5}} placeholder="Card Name Holder"/>
           </View>
           <View style={{flex: 0.25, justifyContent: 'center', alignItems: 'center', marginVertical: 5}}>
             <TextInput style={{flex: 1, width: 260, backgroundColor: 'white', borderRadius: 5}} placeholder="Card Number"/>
           </View>
           <View style={{flex: 0.25, flexDirection: 'row', justifyContent: 'center', alignItems: 'center', marginVertical: 10}}>
             <View style={{flex: 0.5, justifyContent: 'center', alignItems: 'center', marginHorizontal: 5}}>
               <TextInput style={{flex:1, width: 120, backgroundColor: 'white', borderRadius: 5}} placeholder="Expires (12/20)"/>
             </View>
             <View style={{flex: 0.5, justifyContent: 'center', alignItems: 'center', marginHorizontal: 5}}>
               <TextInput style={{flex:1, width: 120, backgroundColor: 'white', borderRadius: 5}} placeholder="CSV Number"/>
             </View>
           </View>
         </View>


问:
Optimizing LINQ combining multiple lists into new generic list
Given the following three lists:

```<code>    var FirstNames = new List<string>(){ "Bob", "Sondra", "Avery", "Von", "Randle", "Gwen", "Paisley" };
    var LastNames = new List<string>(){ "Anderson", "Carlson", "Vickers", "Black", "Schultz", "Marigold", "Johnson" };
    var Birthdates = new List<DateTime>()
                    {
                        Convert.ToDateTime("11/12/1980"),
                        Convert.ToDateTime("09/16/1978"),
                        Convert.ToDateTime("05/18/1985"),
                        Convert.ToDateTime("10/29/1980"),
                        Convert.ToDateTime("01/19/1989"),
                        Convert.ToDateTime("01/14/1972"),
                        Convert.ToDateTime("02/20/1981")
                    };
</code>```

I'd like to combine them into a new generic type where the relationship the lists share is their position in the collection. i.e. FirstNames[0], LastNames[0], Birthdates[0] are related.

So I have come up with this LINQ, matching the indices, which seems to work fine for now:

```<code>    var students = from fn in FirstNames
                   from ln in LastNames
                   from bd in Birthdates
                   where FirstNames.IndexOf(fn) == LastNames.IndexOf(ln)
                   where FirstNames.IndexOf(fn) == Birthdates.IndexOf(bd)
                   select new { First = fn, Last = ln, Birthdate = bd.Date };
</code>```

However, I have stressed tested this code (Each List<string> and List<DateTime> loaded with a few million records) and I run into SystemOutOfMemory Exception.

Is there any other way of writing out this query to achieve the same results more effectively using Linq?

答:
That is what Zip is for.

```<code>var result = FirstNames
  .Zip(LastNames, (f,l) => new {f,l})
  .Zip(BirthDates, (fl, b) => new {First=fl.f, Last = fl.l, BirthDate = b});
</code>```

Regarding scaling:

```<code>int count = 50000000;
var FirstNames = Enumerable.Range(0, count).Select(x=>x.ToString());
var LastNames = Enumerable.Range(0, count).Select(x=>x.ToString());
var BirthDates = Enumerable.Range(0, count).Select(x=> DateTime.Now.AddSeconds(x));

var sw = new Stopwatch();
sw.Start();

var result = FirstNames
  .Zip(LastNames, (f,l) => new {f,l})
  .Zip(BirthDates, (fl, b) => new {First=fl.f, Last = fl.l, BirthDate = b});

foreach(var r in result)
{
    var x = r;
}
sw.Stop();
Console.WriteLine(sw.ElapsedMilliseconds); // Returns 69191 on my machine.
</code>```

While these blow up with out of memory:

```<code>int count = 50000000;
var FirstNames = Enumerable.Range(0, count).Select(x=>x.ToString());
var LastNames = Enumerable.Range(0, count).Select(x=>x.ToString());
var BirthDates = Enumerable.Range(0, count).Select(x=> DateTime.Now.AddSeconds(x));

var sw = new Stopwatch();
sw.Start();

var FirstNamesList = FirstNames.ToList(); // Blows up in 32-bit .NET with out of Memory
var LastNamesList = LastNames.ToList();
var BirthDatesList = BirthDates.ToList();

var result = Enumerable.Range(0, FirstNamesList.Count())
    .Select(i => new
                 {
                     First = FirstNamesList[i],
                     Last = LastNamesList[i],
                     Birthdate = BirthDatesList[i]
                 });

result = BirthDatesList.Select((bd, i) => new
{
    First = FirstNamesList[i],
    Last = LastNamesList[i],
    BirthDate = bd
});

foreach(var r in result)
{
    var x = r;
}
sw.Stop();
Console.WriteLine(sw.ElapsedMilliseconds);
</code>```

At lower values, the cost of converting the Enumerables to a List is much more expensive than the additional object creation as well.  Zip was approximately 30% faster than the indexed versions.  As you add more columns, Zips advantage would likely shrink.

The performance characteristics are also very different.  The Zip routine will start outputting answers almost immediately, while the others will start outputting answers only after the entire Enumerables have been read and converted to Lists, so if you take the results and do pagination on it with .Skip(x).Take(y), or check if something exists .Any(...) it will be magnitudes faster as it doesn't have to convert the entire enumerable.

Lastly, if it becomes performance critical, and you need to implement many results, you could consider extending zip to handle an arbitrary number of Enumerables like (shamelessly stolen from Jon Skeet - https://codeblog.jonskeet.uk/2011/01/14/reimplementing-linq-to-objects-part-35-zip/):

```<code>private static IEnumerable<TResult> Zip<TFirst, TSecond, TThird, TResult>(
    IEnumerable<TFirst> first,
    IEnumerable<TSecond> second,
    IEnumerable<TThird> third,
    Func<TFirst, TSecond, TThird, TResult> resultSelector)
{
    using (IEnumerator<TFirst> iterator1 = first.GetEnumerator())
    using (IEnumerator<TSecond> iterator2 = second.GetEnumerator())
    using (IEnumerator<TThird> iterator3 = third.GetEnumerator())
    {
        while (iterator1.MoveNext() && iterator2.MoveNext() && iterator3.MoveNext())
        {
            yield return resultSelector(iterator1.Current, iterator2.Current, iterator3.Current);
        }
    }
}
</code>```

Then you can do this:

```<code>var result = FirstNames
  .Zip(LastNames, BirthDates, (f,l,b) => new {First=f,Last=l,BirthDate=b});
</code>```

And now you don't even have the issue of the middle object being created, so you get the best of all worlds.

Or use the implementation here to handle any number generically: Zip multiple/abitrary number of enumerables in C#

Body:
Given the following three lists:

    var FirstNames = new List<string>(){ "Bob", "Sondra", "Avery", "Von", "Randle", "Gwen", "Paisley" };
    var LastNames = new List<string>(){ "Anderson", "Carlson", "Vickers", "Black", "Schultz", "Marigold", "Johnson" };
    var Birthdates = new List<DateTime>()
                    {
                        Convert.ToDateTime("11/12/1980"),
                        Convert.ToDateTime("09/16/1978"),
                        Convert.ToDateTime("05/18/1985"),
                        Convert.ToDateTime("10/29/1980"),
                        Convert.ToDateTime("01/19/1989"),
                        Convert.ToDateTime("01/14/1972"),
                        Convert.ToDateTime("02/20/1981")
                    };

I'd like to combine them into a new generic type where the relationship the lists share is their position in the collection. i.e. FirstNames[0], LastNames[0], Birthdates[0] are related.

So I have come up with this LINQ, matching the indices, which seems to work fine for now:

    var students = from fn in FirstNames
                   from ln in LastNames
                   from bd in Birthdates
                   where FirstNames.IndexOf(fn) == LastNames.IndexOf(ln)
                   where FirstNames.IndexOf(fn) == Birthdates.IndexOf(bd)
                   select new { First = fn, Last = ln, Birthdate = bd.Date };

However, I have stressed tested this code (Each List<string> and List<DateTime> loaded with a few million records) and I run into SystemOutOfMemory Exception.

Is there any other way of writing out this query to achieve the same results more effectively using Linq?

Body:
That is what Zip is for.

var result = FirstNames
  .Zip(LastNames, (f,l) => new {f,l})
  .Zip(BirthDates, (fl, b) => new {First=fl.f, Last = fl.l, BirthDate = b});

Regarding scaling:

int count = 50000000;
var FirstNames = Enumerable.Range(0, count).Select(x=>x.ToString());
var LastNames = Enumerable.Range(0, count).Select(x=>x.ToString());
var BirthDates = Enumerable.Range(0, count).Select(x=> DateTime.Now.AddSeconds(x));

var sw = new Stopwatch();
sw.Start();

var result = FirstNames
  .Zip(LastNames, (f,l) => new {f,l})
  .Zip(BirthDates, (fl, b) => new {First=fl.f, Last = fl.l, BirthDate = b});

foreach(var r in result)
{
    var x = r;
}
sw.Stop();
Console.WriteLine(sw.ElapsedMilliseconds); // Returns 69191 on my machine.

While these blow up with out of memory:

int count = 50000000;
var FirstNames = Enumerable.Range(0, count).Select(x=>x.ToString());
var LastNames = Enumerable.Range(0, count).Select(x=>x.ToString());
var BirthDates = Enumerable.Range(0, count).Select(x=> DateTime.Now.AddSeconds(x));

var sw = new Stopwatch();
sw.Start();

var FirstNamesList = FirstNames.ToList(); // Blows up in 32-bit .NET with out of Memory
var LastNamesList = LastNames.ToList();
var BirthDatesList = BirthDates.ToList();

var result = Enumerable.Range(0, FirstNamesList.Count())
    .Select(i => new
                 {
                     First = FirstNamesList[i],
                     Last = LastNamesList[i],
                     Birthdate = BirthDatesList[i]
                 });

result = BirthDatesList.Select((bd, i) => new
{
    First = FirstNamesList[i],
    Last = LastNamesList[i],
    BirthDate = bd
});

foreach(var r in result)
{
    var x = r;
}
sw.Stop();
Console.WriteLine(sw.ElapsedMilliseconds);

At lower values, the cost of converting the Enumerables to a List is much more expensive than the additional object creation as well.  Zip was approximately 30% faster than the indexed versions.  As you add more columns, Zips advantage would likely shrink.

The performance characteristics are also very different.  The Zip routine will start outputting answers almost immediately, while the others will start outputting answers only after the entire Enumerables have been read and converted to Lists, so if you take the results and do pagination on it with .Skip(x).Take(y), or check if something exists .Any(...) it will be magnitudes faster as it doesn't have to convert the entire enumerable.

Lastly, if it becomes performance critical, and you need to implement many results, you could consider extending zip to handle an arbitrary number of Enumerables like (shamelessly stolen from Jon Skeet - https://codeblog.jonskeet.uk/2011/01/14/reimplementing-linq-to-objects-part-35-zip/):

private static IEnumerable<TResult> Zip<TFirst, TSecond, TThird, TResult>(
    IEnumerable<TFirst> first,
    IEnumerable<TSecond> second,
    IEnumerable<TThird> third,
    Func<TFirst, TSecond, TThird, TResult> resultSelector)
{
    using (IEnumerator<TFirst> iterator1 = first.GetEnumerator())
    using (IEnumerator<TSecond> iterator2 = second.GetEnumerator())
    using (IEnumerator<TThird> iterator3 = third.GetEnumerator())
    {
        while (iterator1.MoveNext() && iterator2.MoveNext() && iterator3.MoveNext())
        {
            yield return resultSelector(iterator1.Current, iterator2.Current, iterator3.Current);
        }
    }
}

Then you can do this:

var result = FirstNames
  .Zip(LastNames, BirthDates, (f,l,b) => new {First=f,Last=l,BirthDate=b});

And now you don't even have the issue of the middle object being created, so you get the best of all worlds.

Or use the implementation here to handle any number generically: Zip multiple/abitrary number of enumerables in C#


问:
Sub query returns more than one row
I'm building a point of sale software in php

So I've saved the items in the cart in a temporary table called tempsales, then update all the quantity of items with the new quantities. Just one query,  using the code below which gives me subquery, returns:

More than one row error

```<code>UPDATE items SET quantity = quantity -
    (SELECT quantity FROM tempsales ORDER BY id ASC)
WHERE id  IN
    (SELECT id FROM ORDER BY I'd ASC)
</code>```

答:
It looks like you want to update a whole mess of rows in your items table based on the rows in your tempsales table. I think you want to match the id values. That requires using JOIN syntax in your UPDATE query, like this.

```<code>   UPDATE items
     JOIN tempsales ON items.id = tempsales.id
      SET items.quantity = items.quantity - tempsales.quantity
</code>```

Title: Sub query returns more than one row

Body:
I'm building a point of sale software in php

So I've saved the items in the cart in a temporary table called tempsales, then update all the quantity of items with the new quantities. Just one query,  using the code below which gives me subquery, returns:

More than one row error

UPDATE items SET quantity = quantity -
    (SELECT quantity FROM tempsales ORDER BY id ASC)
WHERE id  IN
    (SELECT id FROM ORDER BY I'd ASC)

Body:
It looks like you want to update a whole mess of rows in your items table based on the rows in your tempsales table. I think you want to match the id values. That requires using JOIN syntax in your UPDATE query, like this.

   UPDATE items
     JOIN tempsales ON items.id = tempsales.id
      SET items.quantity = items.quantity - tempsales.quantity


问:
How to consider few parameters in method
I have my own implementation of SimpleFileVisitor with a visitFile method.
I wonder how can i perform more precise search, if there are more than only one parameter. Here what i mean

```<code>public class SearchFileVisitor extends SimpleFileVisitor<Path>
{
    private String partOfName;
    private String partOfContent;
    private int minSize;
    private int maxSize;
    private List<Path> foundFiles = new ArrayList<>();

    public void setPartOfName(String partOfName)
    {
        this.partOfName = partOfName;
    }

    public void setPartOfContent(String partOfContent)
    {
        this.partOfContent = partOfContent;
    }

    public void setMinSize(int minSize)
    {
        this.minSize = minSize;
    }

    public void setMaxSize(int maxSize)
    {
        this.maxSize = maxSize;
    }

    public List<Path> getFoundFiles()
    {
        return foundFiles;
    }

    @Override
    public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException
    {
        if(partOfName != null && file.toString().contains(partOfName))
        {
           foundFiles.add(file);
        }
        else if(partOfContent != null)
            {
                try(Scanner scanner = new Scanner(file))
                {
                    while(scanner.hasNextLine())
                    {
                        String line = scanner.nextLine();
                        if(line.contains(partOfContent))
                        {
                            foundFiles.add(file);
                            break;
                        }
                    }
                }
            }
         else if(file.toFile().length() < maxSize)
         {
             foundFiles.add(file);
         }
         else if(file.toFile().length() > minSize)
         {
             foundFiles.add(file);
         }
        return super.visitFile(file, attrs);
    }
}
</code>```

The main method:

```<code>public static void main(String[] args) throws IOException
    {
        SearchFileVisitor searchFileVisitor = new SearchFileVisitor();

        searchFileVisitor.setPartOfName("John");
        searchFileVisitor.setPartOfContent("be or not to be?");
        searchFileVisitor.setMinSize(500);
        searchFileVisitor.setMaxSize(10000);

        Files.walkFileTree(Paths.get("D:/SecretFolder"), searchFileVisitor);

        List<Path> foundFiles = searchFileVisitor.getFoundFiles();
        for (Path file : foundFiles)
        {
            System.out.println(file);
        }
    }
</code>```

So, if i set only partOfName it should relay only on it. But if beside it i also set partOfContent and say maxSize, it simultaneously should relay on 3 parameters so far. And consequently if there are 4 par it should relay on four and add to the List, if the object satisfies all the criteria. How can i do that?(Without damn boolean flags)

答:
You should structure the logic as "parameter is disabled OR file passes parameter check" for each parameter.

First, use default values to indicate a parameter is disabled:

```<code>private String partOfName = null;
private String partOfContent = null;
private int minSize = -1;
private int maxSize = -1;
</code>```

Then you can use a single if statement, with the partOfContent check in a separate method to keep things simple:

```<code>@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
    if ((partOfName == null || file.toString().contains(partOfName))
            && (partOfContent == null || fileContains(file, partOfContent))
            && (maxSize < 0 || file.toFile().length() < maxSize)
            && (minSize < 0 || file.toFile().length() > minSize)) {
        foundFiles.add(file);
    }
    return super.visitFile(file, attrs);
}

private static boolean fileContains(Path file, String partOfContent) throws IOException {
    try (Scanner scanner = new Scanner(file)) {
        while (scanner.hasNextLine()) {
            String line = scanner.nextLine();
            if (line.contains(partOfContent)) {
                return true;
            }
        }
    }
    return false;
}
</code>```

Body:
I have my own implementation of SimpleFileVisitor with a visitFile method.
I wonder how can i perform more precise search, if there are more than only one parameter. Here what i mean

public class SearchFileVisitor extends SimpleFileVisitor<Path>
{
    private String partOfName;
    private String partOfContent;
    private int minSize;
    private int maxSize;
    private List<Path> foundFiles = new ArrayList<>();

    public void setPartOfName(String partOfName)
    {
        this.partOfName = partOfName;
    }

    public void setPartOfContent(String partOfContent)
    {
        this.partOfContent = partOfContent;
    }

    public void setMinSize(int minSize)
    {
        this.minSize = minSize;
    }

    public void setMaxSize(int maxSize)
    {
        this.maxSize = maxSize;
    }

    public List<Path> getFoundFiles()
    {
        return foundFiles;
    }

    @Override
    public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException
    {
        if(partOfName != null && file.toString().contains(partOfName))
        {
           foundFiles.add(file);
        }
        else if(partOfContent != null)
            {
                try(Scanner scanner = new Scanner(file))
                {
                    while(scanner.hasNextLine())
                    {
                        String line = scanner.nextLine();
                        if(line.contains(partOfContent))
                        {
                            foundFiles.add(file);
                            break;
                        }
                    }
                }
            }
         else if(file.toFile().length() < maxSize)
         {
             foundFiles.add(file);
         }
         else if(file.toFile().length() > minSize)
         {
             foundFiles.add(file);
         }
        return super.visitFile(file, attrs);
    }
}

The main method:

public static void main(String[] args) throws IOException
    {
        SearchFileVisitor searchFileVisitor = new SearchFileVisitor();

        searchFileVisitor.setPartOfName("John");
        searchFileVisitor.setPartOfContent("be or not to be?");
        searchFileVisitor.setMinSize(500);
        searchFileVisitor.setMaxSize(10000);

        Files.walkFileTree(Paths.get("D:/SecretFolder"), searchFileVisitor);

        List<Path> foundFiles = searchFileVisitor.getFoundFiles();
        for (Path file : foundFiles)
        {
            System.out.println(file);
        }
    }

So, if i set only partOfName it should relay only on it. But if beside it i also set partOfContent and say maxSize, it simultaneously should relay on 3 parameters so far. And consequently if there are 4 par it should relay on four and add to the List, if the object satisfies all the criteria. How can i do that?(Without damn boolean flags)

Body:
You should structure the logic as "parameter is disabled OR file passes parameter check" for each parameter.

First, use default values to indicate a parameter is disabled:

private String partOfName = null;
private String partOfContent = null;
private int minSize = -1;
private int maxSize = -1;

Then you can use a single if statement, with the partOfContent check in a separate method to keep things simple:

@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
    if ((partOfName == null || file.toString().contains(partOfName))
            && (partOfContent == null || fileContains(file, partOfContent))
            && (maxSize < 0 || file.toFile().length() < maxSize)
            && (minSize < 0 || file.toFile().length() > minSize)) {
        foundFiles.add(file);
    }
    return super.visitFile(file, attrs);
}

private static boolean fileContains(Path file, String partOfContent) throws IOException {
    try (Scanner scanner = new Scanner(file)) {
        while (scanner.hasNextLine()) {
            String line = scanner.nextLine();
            if (line.contains(partOfContent)) {
                return true;
            }
        }
    }
    return false;
}


问:
IE 11 "sometimes" preventing the display of "font-awesome" webfonts
Some of our IE11 clients are not seeing the "font-awesome" webfonts in our web application. I have done extensive testing with our own IE11 instances, and also via cross browser testing tools. All performed correctly. So I am struggling to understand why some setups of IE11 might not see "Font-Awesome" webfonts? I did try altering the security settings to replicate the issue, but with no success.

So I am seeking some advice on what might cause this issue? Only other thing I can think of is if IE is being served across a shared server such as Citrix.

Thanks in advance.

EDIT1

More evidence:

```<code>Desktop1   S/W Firewall(on/off)     Windows 7     IE V11.0.9600.17959    Office  Errors
Laptop1    No S/W Firewall          Windows 7     IE V11.0.9600.17959    Office  OK
Laptop1    No S/W Firewall          Windows 7     IE V11.0.9600.17959    Home    OK
Azure VM   ?? S/W Firewall          Windows 10    IE V11 via Edge        Azure   OK
Azure VM   ?? S/W Firewall          Windows 10    Edge                   Azure   OK
Laptop2    ?? S/W Firewall          Windows 10    Edge                   Home    Errors
</code>```

More Evidence 2

When I first enter the page the icons show. When the user re-enters the page from say a hyperlink the icons do not show. However a ctrl-F5 sorts it.

More Evidence 3

I am also seeing Ajax linked requests linked to clickable fonts being made inactive.

More Evidence 4

When I add my site to "Restricted", I cannot then even log in, so I do not believe this is the reason.

Cause of my problem found.

My issue was caused and fixed by an IE Browser History setting via

```<code>Cog
  - Internet Options
     - General
       - Browsing History
          - Settings
            - Temporary Internet Files
              - Automatic (will cause issue)
              - Every time I visit the webpage (will fix issue)
</code>```

The answer below will still cause issues, but was not the cause in my case

Cause of my problem found, but NOT for HTTPS

Just found that if I try to implement HTTPS via Cloudflare, the issue represents itself....

答:
In my case, I could see this issue only when using Win 10 + IE 11. Even after ensuring correct IE settings (security zone and font download enabled), the font won't render. It seems that cache headers should not be set for fonts.

We are using Spring MVC and Tomcat. Adding following code in CORS filter solved problem for me.

```<code>        if (!request.getServletPath().endsWith(".woff")
                && !request.getServletPath().endsWith(".ttf")) {
            response.setHeader("Cache-Control", "no-cache");
            response.setHeader("Pragma", "no-cache");
            response.setDateHeader("Expires", -1);
        }
</code>```

https://stackoverflow.com/a/33508291/828062

Body:
Some of our IE11 clients are not seeing the "font-awesome" webfonts in our web application. I have done extensive testing with our own IE11 instances, and also via cross browser testing tools. All performed correctly. So I am struggling to understand why some setups of IE11 might not see "Font-Awesome" webfonts? I did try altering the security settings to replicate the issue, but with no success.

So I am seeking some advice on what might cause this issue? Only other thing I can think of is if IE is being served across a shared server such as Citrix.

Thanks in advance.

EDIT1

More evidence:

Desktop1   S/W Firewall(on/off)     Windows 7     IE V11.0.9600.17959    Office  Errors
Laptop1    No S/W Firewall          Windows 7     IE V11.0.9600.17959    Office  OK
Laptop1    No S/W Firewall          Windows 7     IE V11.0.9600.17959    Home    OK
Azure VM   ?? S/W Firewall          Windows 10    IE V11 via Edge        Azure   OK
Azure VM   ?? S/W Firewall          Windows 10    Edge                   Azure   OK
Laptop2    ?? S/W Firewall          Windows 10    Edge                   Home    Errors

More Evidence 2

When I first enter the page the icons show. When the user re-enters the page from say a hyperlink the icons do not show. However a ctrl-F5 sorts it.

More Evidence 3

I am also seeing Ajax linked requests linked to clickable fonts being made inactive.

More Evidence 4

When I add my site to "Restricted", I cannot then even log in, so I do not believe this is the reason.

Cause of my problem found.

My issue was caused and fixed by an IE Browser History setting via

Cog
  - Internet Options
     - General
       - Browsing History
          - Settings
            - Temporary Internet Files
              - Automatic (will cause issue)
              - Every time I visit the webpage (will fix issue)

The answer below will still cause issues, but was not the cause in my case

Cause of my problem found, but NOT for HTTPS

Just found that if I try to implement HTTPS via Cloudflare, the issue represents itself....

Body:
In my case, I could see this issue only when using Win 10 + IE 11. Even after ensuring correct IE settings (security zone and font download enabled), the font won't render. It seems that cache headers should not be set for fonts.

We are using Spring MVC and Tomcat. Adding following code in CORS filter solved problem for me.

        if (!request.getServletPath().endsWith(".woff")
                && !request.getServletPath().endsWith(".ttf")) {
            response.setHeader("Cache-Control", "no-cache");
            response.setHeader("Pragma", "no-cache");
            response.setDateHeader("Expires", -1);
        }

https://stackoverflow.com/a/33508291/828062


问:
Checking if string exists in array - what is the mistake here?
I am trying remove duplicates from an array and build a reduced array. I receive an object required error. Here is what I am doing -

```<code>Dim LUT as object, baseArray() as string, sval as variant
'Dim sval as string ... ignore this
For I = 1 to n
    Set LUT = CreateObject("Scripting.Dictionary")
    ... other stuff
    u = 1
    for each sval in baseArray
        if not LUT.exists(sval) then
            do something...
            LUT.Add u, sval
        end if
    u = u + 1
    next sval
    Set LUT = nothing
Next I
</code>```

Please forgive if the code is unrefined. I need it to work more than being the most memory efficient, although unnecessary clutter is always to be avoided. Thanks for your help.

答:
This method exists takes as argument a dictionary key not a dictionary value.

```<code>LUT.exists(sval)
</code>```

You probably may want to check another data structure like collections and this method Collection.contains

https://msdn.microsoft.com/en-us/library/microsoft.visualbasic.collection.contains(v=vs.110).aspx

Body:
I am trying remove duplicates from an array and build a reduced array. I receive an object required error. Here is what I am doing -

Dim LUT as object, baseArray() as string, sval as variant
'Dim sval as string ... ignore this
For I = 1 to n
    Set LUT = CreateObject("Scripting.Dictionary")
    ... other stuff
    u = 1
    for each sval in baseArray
        if not LUT.exists(sval) then
            do something...
            LUT.Add u, sval
        end if
    u = u + 1
    next sval
    Set LUT = nothing
Next I

Please forgive if the code is unrefined. I need it to work more than being the most memory efficient, although unnecessary clutter is always to be avoided. Thanks for your help.

Body:
This method exists takes as argument a dictionary key not a dictionary value.

LUT.exists(sval)

You probably may want to check another data structure like collections and this method Collection.contains

https://msdn.microsoft.com/en-us/library/microsoft.visualbasic.collection.contains(v=vs.110).aspx


答:
Another option is to use Select overload with the indexer supplied:</p>

```<code>var result = Birthdates.Select((bd, i) => new
{
    First = FirstNames[i],
    Last = LastNames[i],
    Birthdate = bd
});
</code>```

Title: Optimizing LINQ combining multiple lists into new generic list

Body:
Another option is to use Select overload with the indexer supplied:

var result = Birthdates.Select((bd, i) => new
{
    First = FirstNames[i],
    Last = LastNames[i],
    Birthdate = bd
});


问:
Using SpringBoot CrudRepository to find one known entry
I am currently working with a project that uses SpringBoot.

I have created a tabled called configuration_documents using Hibernate.  This table can store different types of document objects that I have created.

One of the document objects I have created is Index, and I want to retrieve Index data, so I created a repository like this:

```<code>public interface IndexRepository extends CrudRepository<Index, Long> {
}
</code>```

I know for a fact that the configuration_document table should only have one entry of Index, or else just return the 1st Index in the table.  What is best way of implementing this?

Without modifying IndexRepository, I am currently thinking of something like this (The IndexRepository is autowired in):

```<code>StreamSupport.stream(this.configurationRepository.findAll().spliterator(), false).
                map(
                    return Index;
                ).//A Collector here perhaps?
</code>```

Thanks.

答:
You can use Top and First keywords while constructing your queries, here is the documentation.

You have to declare method like this:

```<code>Index findFirstIndex();
</code>```

in the IndexRepository and that will solve your problem.

Alternatively if you're not allowed to modify IndexRepository you can fetch the first result using streams API somehow like this

```<code>indexRepository.findAll().stream()
        .findFirst()
        .orElseThrow(
                () -> new IndexNotFoundException("Index cannot be found")
        );
</code>```

But the first option would be much more optimal.

Body:
I am currently working with a project that uses SpringBoot.

I have created a tabled called configuration_documents using Hibernate.  This table can store different types of document objects that I have created.

One of the document objects I have created is Index, and I want to retrieve Index data, so I created a repository like this:

public interface IndexRepository extends CrudRepository<Index, Long> {
}

I know for a fact that the configuration_document table should only have one entry of Index, or else just return the 1st Index in the table.  What is best way of implementing this?

Without modifying IndexRepository, I am currently thinking of something like this (The IndexRepository is autowired in):

StreamSupport.stream(this.configurationRepository.findAll().spliterator(), false).
                map(
                    return Index;
                ).//A Collector here perhaps?

Thanks.

Body:
You can use Top and First keywords while constructing your queries, here is the documentation.

You have to declare method like this:

Index findFirstIndex();

in the IndexRepository and that will solve your problem.

Alternatively if you're not allowed to modify IndexRepository you can fetch the first result using streams API somehow like this

indexRepository.findAll().stream()
        .findFirst()
        .orElseThrow(
                () -> new IndexNotFoundException("Index cannot be found")
        );

But the first option would be much more optimal.


问:
Boost Hana iterating over tuple of pairs
I have a template class which accepts a tuple of pairs of a type and an integral constant (some of the types can be repeated so it can't be a hana::map). I'm looking to iterate over the tuple and call a static toString() type method defined for each type. The error I am receiving is:

"error: type 'decltype(hana::first(c))' (aka 'boost::hana::type_impl::_ &') cannot be used prior to '::' because it has no members"

```<code>struct A
{
    static std::string toString() {return std::string("A");}
};
struct B
{
    static std::string toString() {return std::string("B");}
};

using namespace hana::literals;
std::array<std::string,3> ret;
constexpr auto tupleOfPairs = hana::make_tuple(
    hana::make_pair(hana::type_c<A>, 0_c),
    hana::make_pair(hana::type_c<B>, 0_c),
    hana::make_pair(hana::type_c<B>, 5_c));

size_t idx = 0;
hana::for_each(tupleOfPairs, [&](auto c)
{
    ret[idx++] = decltype(hana::first(c))::type::toString();
});
</code>```

I had something very similar working when it was just a tuple (using decltype(c)::type::toString()) but as soon as I made the tuple elements pairs with an integral constant I can't seem to extract the type of the first element of the pair and do the same.

Thanks

答:
TL;DNR: That decltype yields a type "reference to ...", which (it's a reference) obviously has no members. Simple fix: remove the reference with std::remove_reference:

```<code>ret[idx++] =
  std::remove_reference_t<decltype(hana::first(c))>::type::toString();
</code>```

This is not about hana. Taking it "out of the loop" we can reduce your case further to

```<code>#include <string>
struct A {
  static std::string toString() {
    return std::string("A");
  }
};
template<typename T> T & get_it() {
  static T thing;
  return thing;
}
int main() {
  std::string str = decltype(get_it<A>())::toString();
}
</code>```

This gives (basically) the same error message as yours:

error: 'decltype(get_it())' (aka 'A &') is not a class, namespace, or enumeration

This is telling us that A & (a reference to A) is not a class (etc.) and can thus not have a (static) member. The same is true when your compiler tells you that:

error: type 'decltype(hana::first(c))' (aka 'boost::hana::type_impl::_ &') cannot be used prior to '::' because it has no members

boost::hana::type_impl::_ & is a reference. Of course it has no members. The referenced class has, so just remove the reference with std::remove_reference.

The fact that the return type of first is reference type is also noted in the documentation, btw (emphasis mine):

Returns the first element of a pair.Note that if the Product actually stores the elements it contains, hana::first is required to return a lvalue reference, a lvalue reference to const or a rvalue reference to the first element, where the type of reference must match that of the pair passed to first. If [.., not applicable here].

Body:
I have a template class which accepts a tuple of pairs of a type and an integral constant (some of the types can be repeated so it can't be a hana::map). I'm looking to iterate over the tuple and call a static toString() type method defined for each type. The error I am receiving is:

"error: type 'decltype(hana::first(c))' (aka 'boost::hana::type_impl::_ &') cannot be used prior to '::' because it has no members"

struct A
{
    static std::string toString() {return std::string("A");}
};
struct B
{
    static std::string toString() {return std::string("B");}
};

using namespace hana::literals;
std::array<std::string,3> ret;
constexpr auto tupleOfPairs = hana::make_tuple(
    hana::make_pair(hana::type_c, 0_c),
    hana::make_pair(hana::type_c, 0_c),
    hana::make_pair(hana::type_c, 5_c));

size_t idx = 0;
hana::for_each(tupleOfPairs, [&](auto c)
{
    ret[idx++] = decltype(hana::first(c))::type::toString();
});

I had something very similar working when it was just a tuple (using decltype(c)::type::toString()) but as soon as I made the tuple elements pairs with an integral constant I can't seem to extract the type of the first element of the pair and do the same.

Thanks

Body:
TL;DNR: That decltype yields a type "reference to ...", which (it's a reference) obviously has no members. Simple fix: remove the reference with std::remove_reference:

ret[idx++] =
  std::remove_reference_t<decltype(hana::first(c))>::type::toString();

This is not about hana. Taking it "out of the loop" we can reduce your case further to

#include <string>
struct A {
  static std::string toString() {
    return std::string("A");
  }
};
template<typename T> T & get_it() {
  static T thing;
  return thing;
}
int main() {
  std::string str = decltype(get_it<A>())::toString();
}

This gives (basically) the same error message as yours:

error: 'decltype(get_it())' (aka 'A &') is not a class, namespace, or enumeration

This is telling us that A & (a reference to A) is not a class (etc.) and can thus not have a (static) member. The same is true when your compiler tells you that:

error: type 'decltype(hana::first(c))' (aka 'boost::hana::type_impl::_ &') cannot be used prior to '::' because it has no members

boost::hana::type_impl::_ & is a reference. Of course it has no members. The referenced class has, so just remove the reference with std::remove_reference.

The fact that the return type of first is reference type is also noted in the documentation, btw (emphasis mine):

Returns the first element of a pair.Note that if the Product actually stores the elements it contains, hana::first is required to return a lvalue reference, a lvalue reference to const or a rvalue reference to the first element, where the type of reference must match that of the pair passed to first. If [.., not applicable here].


问:
How to reuse superclass method's variables in Python 3?
I want to subclass by extending a method that always has the same first stage, say:

```<code>class Data:
    def show(self):
    #  this part is common for all subclasses
        total=10

class PrintA(Data):
    def show(self):
        Data.show(self)
        print(total)

class PrintAPlus(Data):
    def show(self):
        Data.show(self)
        print(total+10)
</code>```

However, I get NameError: name a is not defined.

How to reuse total variable from the superclass's method?
(The obvious one is to save it as instance's attribute, but I don't need there, actually.)

答:
the problem here is that total is only assigned inside the superclass method show, there is just a local variable. its value can't be see outside it.

to fix it you need to make it a instance attribute or return that value from there

option 1

```<code>class Data:
    def show(self):
    #  this part is common for all subclasses
        self.total = 10

class PrintA(Data):
    def show(self):
        Data.show(self)
        print(self.total)

class PrintAPlus(Data):
    def show(self):
        Data.show(self)
        print(self.total+10)
</code>```

option 2

```<code>class Data:
    def show(self):
    #  this part is common for all subclasses
        return 10

class PrintA(Data):
    def show(self):
        total = Data.show(self)
        print(total)

class PrintAPlus(Data):
    def show(self):
        total = Data.show(self)
        print(total+10)
</code>```

Body:
I want to subclass by extending a method that always has the same first stage, say:

class Data:
    def show(self):
    #  this part is common for all subclasses
        total=10

class PrintA(Data):
    def show(self):
        Data.show(self)
        print(total)

class PrintAPlus(Data):
    def show(self):
        Data.show(self)
        print(total+10)

However, I get NameError: name a is not defined.

How to reuse total variable from the superclass's method?
(The obvious one is to save it as instance's attribute, but I don't need there, actually.)

Body:
the problem here is that total is only assigned inside the superclass method show, there is just a local variable. its value can't be see outside it.

to fix it you need to make it a instance attribute or return that value from there

option 1

class Data:
    def show(self):
    #  this part is common for all subclasses
        self.total = 10

class PrintA(Data):
    def show(self):
        Data.show(self)
        print(self.total)

class PrintAPlus(Data):
    def show(self):
        Data.show(self)
        print(self.total+10)

option 2

class Data:
    def show(self):
    #  this part is common for all subclasses
        return 10

class PrintA(Data):
    def show(self):
        total = Data.show(self)
        print(total)

class PrintAPlus(Data):
    def show(self):
        total = Data.show(self)
        print(total+10)