text:
Q: How can I load python wikipedia image in pygame display? Alright, I am making as title, and here is this is part of codes.
black = (0,0,0)
display = pygame.display.set_mode((1000, 600))
def main():
   search_word = "apple inc"
   result = ""
   main = True

   while main:
       for event in pygame.event.get():
           if event.type == pygame.QUIT:
               pygame.quit()
               quit()
       display.blit(black)
       result = wikipedia.page(search_word)
       display.blit(result.images[0], (100, 100)

       pygame.display.update()

And, I got error:

Traceback (most recent call last):
      display.blit(result.images[0], (100, 100)) AttributeError: 'str' object has no attribute 'images'

How can I fix it?

A:
How can I fix it?

You can fix it by passing a Surface object to the blit function, not a string.
Pygame does not automatically download images from the internet for you. You have to download the images yourself; then you can use the functions in pygame.image to create Surface instances.


text:
Q: How To Edit After Effects Template with Python or Javascript? I planning to build an online music visualizer but I cannot figure out how to generate high graphic visualization using this After Effects template - Visualization After Effects Template and similar others. How can I Edit this Template with my own text and audio.
I want to make something like this - Website Example
I Found Some Visualization Example using Web Audio & p5js But They Were Not as Graphically Pleasing and I want to Streamline The Process By Using Existing AE Templates.
I Was Not Able to Find Any Helpful Tutorial or Tool for this, So I am Here Looking for a Solution.
The Process -

*

*User Makes API Request with Link of Audio (web address), Title and Subtitle.

*The Video is Processed with the Data in the request and stored in a public access dir.

*Link to The File is Sent Back to The User.

The Tech I Am Open to Use :
ReactJS, Javascript, Python, Django, Nodejs.
Thanks for your time.

A: Use NexRender
This Will Help To Edit and Render After Effects File.
Read the Docs and Implement According to Your Need.

A: Just wanted to add this in addition to Shivam's answer:  you can achieve this using Dataclay's tool Templater Bot for Adobe After Effects.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Should i use hybrid app which has user authentication and store sessions? Hi I'm new to hybrid app development, i'm trying to develop an hybrid app using Sencha, which has features like user login, store user details in local(client), and consume rest apis. AFAIK its not possible  to make a POST request(CORS) and cookie storage don't work in mobile.
 So whats the workaround to it OR should i really be using the hybrid at all

A: Simple ajax request will work, you don't need CORS nor JSONP if you package the app with cordova or phonegap. Once app is packaged you don't have cross domain restrictions.
Yeah go for it with Sencha Touch.


text:
Q: Update driver for one of the same model network adapters There are multiple network adapters of the same model in the target computer. As below, they are all Intel I211.
PCI\VEN_8086&DEV_1539&SUBSYS_00008086&REV_03\0060E0FFFF6336A000
    Name: Intel(R) I211 Gigabit Network Connection
    Hardware IDs:
        PCI\VEN_8086&DEV_1539&SUBSYS_00008086&REV_03
        PCI\VEN_8086&DEV_1539&SUBSYS_00008086
        PCI\VEN_8086&DEV_1539&CC_020000
        PCI\VEN_8086&DEV_1539&CC_0200
    Compatible IDs:
        PCI\VEN_8086&DEV_1539&REV_03
        PCI\VEN_8086&DEV_1539
        PCI\VEN_8086&CC_020000
        PCI\VEN_8086&CC_0200
        PCI\VEN_8086
        PCI\CC_020000&DT_0
        PCI\CC_020000
        PCI\CC_0200&DT_0
        PCI\CC_0200
PCI\VEN_8086&DEV_1539&SUBSYS_00008086&REV_03\0060E0FFFF6336A100
    Name: Intel(R) I211 Gigabit Network Connection #2
    Hardware IDs:
        PCI\VEN_8086&DEV_1539&SUBSYS_00008086&REV_03
        PCI\VEN_8086&DEV_1539&SUBSYS_00008086
        PCI\VEN_8086&DEV_1539&CC_020000
        PCI\VEN_8086&DEV_1539&CC_0200
    Compatible IDs:
        PCI\VEN_8086&DEV_1539&REV_03
        PCI\VEN_8086&DEV_1539
        PCI\VEN_8086&CC_020000
        PCI\VEN_8086&CC_0200
        PCI\VEN_8086
        PCI\CC_020000&DT_0
        PCI\CC_020000
        PCI\CC_0200&DT_0
        PCI\CC_0200

How do I update driver for a specific one of these same model adapters by devcon, C++ or C#? For example, update by the unique device instance ID (ex: PCI\VEN_8086&DEV_1539&SUBSYS_00008086&REV_03\0060E0FFFF6336A100)
Thanks
EDIT:
I've searched APIs for this but they all use hardware ID to update the driver, which will update all of the same model adapters' drivers.
Ex: C++'s UpdateDriverForPlugAndPlayDevicesA and devcon's update command.
EDIT2:
The motivation of this issue is that we are using an RTOS (real-time OS, RTX64) and we want to establish a real-time network communication (EtherCAT connection) with other devices by the RTOS. We need to update one of the adapters' driver to the driver provided by RTX64, so that this adapter can be used by it.
The only workable solution for us to just update one of them is using Windows' "Device Manager". (There's no same model adapters in the below picture, it's just shows how to update by device manager manually)

We are asking our users to do this manual update after installing our software. It's not convenient for them. So we are trying to find an automatic way to do this.
Since Device Manager in Windows can do this, we suppose that there's an API can do this too.

A: This is not really a average Programmer Problem.
Driver Programming - as a subset of Realtime Programming - is a highly specialized field. The average C# or C++ .NET Programmer will rarely have to deal with stuff like pointers and neer with assembler level code. But for those two, it is their daily bread and butter. I can not give you little more then general advice:
My first advice for you is to get somebody elses code to make that decision and installation. Usually drivers of one Manufacturer are distributed in packages. Wich do understand how to deal with idenitifcation of the hardware. Usually those installers also have a silent mode. So it comes down to calling them and intercepting the console output/looking for the return value.
My second advice, is to use their name as listed in the Device Manager. Optionally get them renamed manually. It is not that reliable as strings are quite patient and easily changed/missmatched, but it would get you somewhere to start  from.
But as I understand it your problem is worse then just general driver updates. You have two instances of the same Hardware, and want to use different drivers for each. Wich is a order worse:

*

*I am not even sure this is possible. Since the driver folder still uses the good old "only one file of each name" approach, it is propable that you can not use different drivers for different instances of the same hardware. Unless you define your own driver storage location.

*I have no idea why you would do that. The average enduser programm does not need to worry about even selecting wich interface it will use. It just hands it's request off the to network stack and does not deal with layer 3 or below. Servers may have to pick a specific adapter to listen on, or just listen on both in paralell. But even those do not care for the driver version in use. They do not even care if it is a real, physical interface - after all missclassification like with early Bluetooth and Virtual Devices like for Virtual Machine Monitors/PDF printers are a thing.
So it honestly sounds like you got a XY Problem, with this idea being the (propably wrong) Y, to your real X.

A: Two workarounds. One minimizes manual customer interaction when updating the device driver, the other fully automates the process, but requires coding in a BASIC like language.
The first one consists on automatically showing the Hardware Update Wizard for that particular device instance, using the API function DiShowUpdateDevice as described in the previous link.
The second one is to use the free AutoIt automation software. With it you can automate basically everything in a Windows system, it's very powerful and I've used it in conjunction with web bots and automatic web testing (non-headless). I've also used it in double-click roll-outs of Windows systems and many sysadmin tasks.
As a remark, you could also mix both approaches. First, use DiShowUpdateDevice to show the wizard and then an AutoIt script can automatically perform UI interaction, the client won't have to do anything at all.


text:
Q: using a switch statement - but case where counter equals one never gets used array switch
    Sample Use the array switch button to toggle through a number of combinations
$(document).ready(function() {
   var clcks = 0;
    $('#cyclStylsArrayCntr').click(function(event){
    var curFnt = ['Trebuchet MS', 'Verdana', 'Tahoma', 'Palatino',  'Georgia', 'Times New Roman', 'Arial', 'Courier New'];
   var txtClr =['Black', 'Red','Green','Blue','Brown','Aqua','Gold','white','black'];
    var curBkC = ['white', 'aqua','brown','yellow','lightGreen','orange','blue','lightBlue','LightSeaGreen']
   var msg = '';                   // Message

      // Arrays are zero based (so 0 is round 1)
     // Add 1 to the current round
      clcks = (clcks + 1);
      if(clcks>=8)clcks=1;

                            switch (true) {
        case clcks == 1:
            $(".sample2").css('background-color', curBkC[clcks]);
            $(".sample2").css("font-family", curFnt[clcks]);
            $("#currFont").css("font-family", curFnt[clcks]);
            $(".sample2").css("color", txtClr[clcks]);
            $(".sample2").animate({fontSize: '38px'}, "fast");
            $(".sample2").animate({fontSize: '36px'}, "fast");
            $("#currFont").html(curFnt[clcks]);
            break;
        case clcks == 2:
            $(".sample2").css('background-color', curBkC[clcks]);
            $(".sample2").css("font-family", curFnt[clcks]);
            $("#currFont").css("font-family", curFnt[clcks]);
            $(".sample2").css("color", txtClr[clcks]);
            $(".sample2").animate({fontSize: '34px'}, "fast");
            $(".sample2").animate({fontSize: '36px'}, "fast");
            $("#currFont").html(curFnt[clcks]);
            break;
        case clcks == 3:
            $(".sample2").css('background-color', curBkC[clcks]);
            $(".sample2").css("font-family", curFnt[clcks]);
            $("#currFont").css("font-family", curFnt[clcks]);
            $(".sample2").css("color", txtClr[clcks]);
            $(".sample2").animate({fontSize: '38px'}, "fast");
            $(".sample2").animate({fontSize: '36px'}, "fast");
            $("#currFont").html(curFnt[clcks]);
            break;
        case clcks == 4:
            $(".sample2").css('background-color', curBkC[clcks]);
            $(".sample2").css("font-family", curFnt[clcks]);
            $("#currFont").css("font-family", curFnt[clcks]);
            $(".sample2").css("color", txtClr[clcks]);
            $(".sample2").animate({fontSize: '34px'}, "fast");
            $(".sample2").animate({fontSize: '36px'}, "fast");
            $("#currFont").html(curFnt[clcks]);
            break;
          case clcks == 5:
            $(".sample2").css('background-color', curBkC[clcks]);
            $(".sample2").css("font-family", curFnt[clcks]);
            $("#currFont").css("font-family", curFnt[clcks]);
            $(".sample2").css("color", txtClr[clcks]);
            $(".sample2").animate({fontSize: '38px'}, "fast");
            $(".sample2").animate({fontSize: '36px'}, "slow");
            $("#currFont").html(curFnt[clcks]);
            break;
        case clcks == 6:
            $(".sample2").css('background-color', curBkC[clcks]);
            $(".sample2").css("font-family", curFnt[clcks]);
            $("#currFont").css("font-family", curFnt[clcks]);
            $(".sample2").css("color", txtClr[clcks]);
            $(".sample2").animate({fontSize: '34px'}, "fast");
            $(".sample2").animate({fontSize: '36px'}, "fast");
            $("#currFont").html(curFnt[clcks]);
            break;
        case clcks == 7:
            $(".sample2").css('background-color', curBkC[clcks]);
            $(".sample2").css("font-family", curFnt[clcks]);
            $("#currFont").css("font-family", curFnt[clcks]);
            $(".sample2").css("color", txtClr[clcks]);
            $(".sample2").animate({fontSize: '38px'}, "fast");
            $(".sample2").animate({fontSize: '36px'}, "fast");
            $("#currFont").html(curFnt[clcks]);
            break;
        case clcks == 8:
            $(".sample2").css('background-color', curBkC[clcks]);
            $(".sample2").css("font-family", curFnt[clcks]);
            $("#currFont").css("font-family", curFnt[clcks]);
            $(".sample2").css("color", txtClr[clcks]);
            $(".sample2").animate({fontSize: '34px'}, "fast");
            $(".sample2").animate({fontSize: '36px'}, "fast");
            $("#currFont").html(curFnt[clcks]);

            break;
                            }

  } );

      });

Here is a sample of my file online -  the first font selected by the 'array switch' button should be 'Trebuchet MS' but instead it skips to Verdana       http://etherealdoorways.com/switchColorFont.html

A: You've initialized the clcks variable to 0, but it is incremented by 1 upon the first click.
The clcks should begin at 0 so that it can be used to access the first element in the arrays.
Initialize the clcks to 7 instead of 0 on document ready.
Also, if clcks is equal or larger than 8, it should be reset to 0.
$(document).ready(function() {
   // Initialize to 7, so that the first click will return to 0
   var clcks = 7;
    $('#cyclStylsArrayCntr').click(function(event){
    var curFnt = ['Trebuchet MS', 'Verdana', 'Tahoma', 'Palatino',  'Georgia', 'Times New Roman', 'Arial', 'Courier New'];
   var txtClr =['Black', 'Red','Green','Blue','Brown','Aqua','Gold','white','black'];
    var curBkC = ['white', 'aqua','brown','yellow','lightGreen','orange','blue','lightBlue','LightSeaGreen']
   var msg = '';                   // Message

      // Arrays are zero based (so 0 is round 1)
     // Add 1 to the current round
      clcks = (clcks + 1);

      // This should be reset to 0, not 1
      // Also, change index numbers in switch-case so that clcks is also 0-based
      if(clcks>=8)clcks=0;

                            switch (true) {
        case clcks == 0:
            $(".sample2").css('background-color', curBkC[clcks]);
            $(".sample2").css("font-family", curFnt[clcks]);
            $("#currFont").css("font-family", curFnt[clcks]);
            $(".sample2").css("color", txtClr[clcks]);
            $(".sample2").animate({fontSize: '38px'}, "fast");
            $(".sample2").animate({fontSize: '36px'}, "fast");
            $("#currFont").html(curFnt[clcks]);
            break;
        case clcks == 1:
            $(".sample2").css('background-color', curBkC[clcks]);
            $(".sample2").css("font-family", curFnt[clcks]);
            $("#currFont").css("font-family", curFnt[clcks]);
            $(".sample2").css("color", txtClr[clcks]);
            $(".sample2").animate({fontSize: '34px'}, "fast");
            $(".sample2").animate({fontSize: '36px'}, "fast");
            $("#currFont").html(curFnt[clcks]);
            break;
        case clcks == 2:
            $(".sample2").css('background-color', curBkC[clcks]);
            $(".sample2").css("font-family", curFnt[clcks]);
            $("#currFont").css("font-family", curFnt[clcks]);
            $(".sample2").css("color", txtClr[clcks]);
            $(".sample2").animate({fontSize: '38px'}, "fast");
            $(".sample2").animate({fontSize: '36px'}, "fast");
            $("#currFont").html(curFnt[clcks]);
            break;
        case clcks == 3:
            $(".sample2").css('background-color', curBkC[clcks]);
            $(".sample2").css("font-family", curFnt[clcks]);
            $("#currFont").css("font-family", curFnt[clcks]);
            $(".sample2").css("color", txtClr[clcks]);
            $(".sample2").animate({fontSize: '34px'}, "fast");
            $(".sample2").animate({fontSize: '36px'}, "fast");
            $("#currFont").html(curFnt[clcks]);
            break;
          case clcks == 4:
            $(".sample2").css('background-color', curBkC[clcks]);
            $(".sample2").css("font-family", curFnt[clcks]);
            $("#currFont").css("font-family", curFnt[clcks]);
            $(".sample2").css("color", txtClr[clcks]);
            $(".sample2").animate({fontSize: '38px'}, "fast");
            $(".sample2").animate({fontSize: '36px'}, "slow");
            $("#currFont").html(curFnt[clcks]);
            break;
        case clcks == 5:
            $(".sample2").css('background-color', curBkC[clcks]);
            $(".sample2").css("font-family", curFnt[clcks]);
            $("#currFont").css("font-family", curFnt[clcks]);
            $(".sample2").css("color", txtClr[clcks]);
            $(".sample2").animate({fontSize: '34px'}, "fast");
            $(".sample2").animate({fontSize: '36px'}, "fast");
            $("#currFont").html(curFnt[clcks]);
            break;
        case clcks == 6:
            $(".sample2").css('background-color', curBkC[clcks]);
            $(".sample2").css("font-family", curFnt[clcks]);
            $("#currFont").css("font-family", curFnt[clcks]);
            $(".sample2").css("color", txtClr[clcks]);
            $(".sample2").animate({fontSize: '38px'}, "fast");
            $(".sample2").animate({fontSize: '36px'}, "fast");
            $("#currFont").html(curFnt[clcks]);
            break;
        case clcks == 7:
            $(".sample2").css('background-color', curBkC[clcks]);
            $(".sample2").css("font-family", curFnt[clcks]);
            $("#currFont").css("font-family", curFnt[clcks]);
            $(".sample2").css("color", txtClr[clcks]);
            $(".sample2").animate({fontSize: '34px'}, "fast");
            $(".sample2").animate({fontSize: '36px'}, "fast");
            $("#currFont").html(curFnt[clcks]);

            break;
                            }

  } );

      });

A: The switch statement is formatted incorrectly. You need to put your expression on the switch and the values on the case like so:
switch(clcks) {
  case 1:
     :
    break;
  case 2:
     :
    break;
  :
}

A: Switch case needs an expression to compare against the cases. But you dont really need it either.
It goes straight to Verdana cos you're adding 1 to clcks before executing the code (in JS, array index starts from 0).
Here's what I think you need (untested code):
$(document).ready(function() {
   // Declare all variables outside of the on click
   var clcks = 0;
   var curFnt = ['Trebuchet MS', 'Verdana', 'Tahoma', 'Palatino',  'Georgia', 'Times New Roman', 'Arial', 'Courier New'];
   var txtClr =['Black', 'Red','Green','Blue','Brown','Aqua','Gold','white','black'];
   var curBkC = ['white', 'aqua','brown','yellow','lightGreen','orange','blue','lightBlue','LightSeaGreen']
   var msg = '';
   $('#cyclStylsArrayCntr').click(function(event){

      if( clcks >= 8 ) clcks = 1;

        $(".sample2").css({
          'background-color'     : curBkC[clcks],
          'font-family'          : curFnt[clcks],
          'color'                : txtClr[clcks]
        });
        $("#currFont").css("font-family", curFnt[clcks]);
        $(".sample2").animate({fontSize: '38px'}, "fast");
        $(".sample2").animate({fontSize: '36px'}, "fast"); // Not sure why you have 2 of these
        $("#currFont").html(curFnt[clcks]);

        clcks = (clcks + 1); // Put after executing your on click code

     });
});

Also, try to make your variable names readable so if you're collaborating with others they can understand what each one represents straight away.

A: You don't need a switch statement at all (apart from that it is is written the wrong way)
The first time the function is called, clcks in incremented to 1, which means that the array elements at index 1 are read instead of the elements at index 0.
Here's a better, working solution:
$(document).ready(function() {
    var curFnt = ['Trebuchet MS', 'Verdana', 'Tahoma', 'Palatino',  'Georgia', 'Times New Roman', 'Arial', 'Courier New'];
    var fontSizes = ["38px", "34px", "38px", "34px", "38px", "34px", "38px", "34px"];
    var txtClr = ['Black', 'Red', 'Green', 'Blue', 'Brown', 'Aqua', 'Gold', 'white', 'black'];
    var curBkC = ['white', 'aqua', 'brown', 'yellow', 'lightGreen', 'orange', 'blue', 'lightBlue', 'LightSeaGreen'];

    var clcks = 0;

    $('#cyclStylsArrayCntr').click(function(event){
        var msg = '';

        // clcks is incremented at the end of the function
        // -> clcks is 0 at the first time

        $(".sample2").css('background-color', curBkC[clcks]);
        $(".sample2").css("font-family", curFnt[clcks]);
        $("#currFont").css("font-family", curFnt[clcks]);
        $(".sample2").css("color", txtClr[clcks]);
        $(".sample2").animate({fontSize: fontSizes[clcks]}, "fast");
        $(".sample2").animate({fontSize: '36px'}, "fast");
        $("#currFont").html(curFnt[clcks]);

        clcks = clcks + 1;
        if (clcks >= 8) clcks = 1;
    });
});

A: This is the solution I will use:
    $(document).ready(function() {
    var curFnt = ['Trebuchet MS', 'Verdana', 'Tahoma', 'Palatino',  'Georgia', 'Times New Roman', 'Arial', 'Courier New'];
    var fontSizes = ["38px", "34px", "38px", "34px", "38px", "34px", "38px", "34px"];
    var txtClr = ['Black', 'Red', 'Green', 'Blue', 'Brown', 'Aqua', 'Gold', 'white', 'black'];
    var curBkC = ['white', 'aqua', 'brown', 'yellow', 'lightGreen', 'orange', 'blue', 'lightBlue', 'LightSeaGreen'];

    var clcks = 0;

    $('#cyclStylsArrayCntr').click(function(event){
        var msg = '';

        // clcks is incremented at the end of the function
        // -> clcks is 0 at the first time

        $(".sample2").css('background-color', curBkC[clcks]);
        $(".sample2").css("font-family", curFnt[clcks]);
        $("#currFont").css("font-family", curFnt[clcks]);
        $(".sample2").css("color", txtClr[clcks]);
        $(".sample2").animate({fontSize: fontSizes[clcks]}, "fast");
        $(".sample2").animate({fontSize: '36px'}, "fast");
        $("#currFont").html(curFnt[clcks]);

        clcks = clcks + 1;
        if (clcks >= 8) clcks = 0;
            });
        });


text:
Q: How can I remove all the users and groups associated with removed (purged) programs? How can I remove all the users and groups associated with removed (purged) programs?
For example, I install exim. It created a group and a user named Debian-exim.
I then use it for a while, and remove it using apt-get purge exim*. And then, it removes all the files associated with it. But, it does not remove the users and groups created by the program 'exim'. I have installed and removed several programs, so, I am not sure how many users are left behind in my system. I want to remove all the unwanted users automatically when I uninstall a program, and I also want to remove all  the unwanted users that exist currently in my system. How can I achieve that?


text:
Q: font for charset GB2312.1980-0 is lacking when launching xorg in freebsd I am a newbie of freebsd (FreeBSD 12.0). I got a warning when launching xorg:
twm: warning: font for charset GB2312.1980-0 is lacking
How can I install the font? I googled it but can't find a solution.
Thanks.


text:
Q: Conditionally replacing NaNs Python Pandas sorry for the n00b question.
I'm new to Kaggle and have begun looking at some of their competitions, and one of their beginner ones is on the famous Titanic data. My question regards filling NaNs in for the Age column. What I would like to do is for each NaN in the Age column I'd like to replace it with the average age for that Class and Sex.
For example, passengerID 6 is a Man from 3rd class, and he has a NaN age. What I'd like is to replace that NaN with the average age of 3rd class males. Which is 26.5.
What I've tried so far is the following:
man_1 = train[(train['male'] == 1) & (train['Pclass'] == 1)]['Age'].mean()
train[(train['male'] == 1) & (train['Pclass'] == 1)]['Age'].fillna(man_1, inplace=True)

man_2 = train[(train['male'] == 1) & (train['Pclass'] == 2)]['Age'].mean()
train[(train['male'] == 1) & (train['Pclass'] == 2)]['Age'].fillna(man_2, inplace=True)

man_3 = train[(train['male'] == 1) & (train['Pclass'] == 3)]['Age'].mean()
train[(train['male'] == 1) & (train['Pclass'] == 3)]['Age'].fillna(man_3, inplace=True)

wom_1 = train[(train['male'] == 0) & (train['Pclass'] == 1)]['Age'].mean()
train[(train['male'] == 0) & (train['Pclass'] == 1)]['Age'].fillna(wom_1, inplace=True)

wom_2 = train[(train['male'] == 0) & (train['Pclass'] == 2)]['Age'].mean()
train[(train['male'] == 0) & (train['Pclass'] == 2)]['Age'].fillna(wom_2, inplace=True)

wom_3 = train[(train['male'] == 0) & (train['Pclass'] == 3)]['Age'].mean()
train[(train['male'] == 0) & (train['Pclass'] == 3)]['Age'].fillna(wom_3, inplace=True)

And quelle suprise it doens't work. I'm not sure why though? Firstly if anyone could suggest why it doesn't work that would be great. Secondly, I feel like there should be a more 'Pythonistic' way of doing this, but I'm not sure how exactly. I'm aware there is another possibly duplicate topic on Stack but it doesn't quite explain why my code isn't working, so sorry if this post annoys people. Cheers

A: You can do this in one pass with groupby().transform()
s = train.groupby(['male', 'Pclass'])['Age'].transform('mean')

df['Age'] = df['Age'].fillna(s)


text:
Q: Use of indexedDB returns 'undefined' I'm trying to use indexedDB.
Some parts of my code works.
In the following example, the first function adds server in my DB, however in Chrome debug console there is an undefined message not related to any line. The server is already added though.
The second function puts records in an array, there is also an undefined message not related to any line.
If I do a console.log(servers); just before return servers; I can see the array content, however if I call the function somewhere else in my code, the returned object is undefined.
var dbName = 'myDBname',
dbServersStoreName = 'servers',
dbVersion = 1,
openDBforCreation = indexedDB.open(dbName, dbVersion);

openDBforCreation.onupgradeneeded = function(e) {
 var db = e.target.result;
 var objStore = db.createObjectStore(dbServersStoreName, { keyPath: "alias"
});
var index = objStore.createIndex("serversAlias", ["alias"]);
};

function addServerInDB(serverAlias,serverAddress,user,pwd){
 var myDB = indexedDB.open(dbName, dbVersion);

 myDB.onerror = function() {
  var notification = document.querySelector('.mdl-js-snackbar');
   notification.MaterialSnackbar.showSnackbar(
    {message: 'Error while trying to access internal database'});
}
myDB.onsuccess = function(e) {
 var db = e.target.result,
     request = db.transaction([dbServersStoreName],
               "readwrite").objectStore("servers")
                .put({alias:''+serverAlias+'',
                address:''+serverAddress+'', login:''+user+'',
                passwd:''+pwd+''});

     request.onsuccess = function(){
      var notification = document.querySelector('.mdl-js-snackbar');
       notification.MaterialSnackbar.showSnackbar(
        {message: 'Server added'});
     }
 }
};

function listServersInDB(){
 var myDB= indexedDB.open(dbName, dbVersion);

myDB.onerror = function() {
    var notification = document.querySelector('.mdl-js-snackbar');
    notification.MaterialSnackbar.showSnackbar(
        {message: 'Error while trying to access internal database'});

}
myDB.onsuccess = function(e) {
    var servers = new Array(),
        db = e.target.result,
        request = db.transaction(["servers"], "readwrite")
                    .objectStore("servers")
                    .openCursor();

    request.onsuccess = function(e){
        var cursor = e.target.result;
        if(cursor){
            servers.push(cursor.value);
            cursor.continue();
        }
        return servers;
    }
}
};

I do not understand where this undefined comes from and if that is why the listServersInDB() function doesn't work.

A: You need to learn more about how to write asynchronous Javascript. There are too many errors in your code to even begin reasoning about the problem.
Briefly, don't do this:
function open() {
  var openDatabaseRequest = ...;
}

openDatabaseRequest.foo = ...;

Instead, do this:
function open() {
  var openDatabaseRequest = ...;
  openDatabaseRequest.foo = ...;
}

Next, you don't need to try and open the same database multiple times. Why are you calling indexedDB.open twice? You can open a database to both install it and to start using it immediately. All using the same connection.
Next, I'd advise you don't name the database open request as 'myDB'. This is misleading. This is an IDBRequest object, and more specifically, an IDBOpenRequest object. A request isn't a database.
Next, you cannot return the servers array from the request.onsuccess at the end. For one this returns to nowhere and might be source of undefined. Two this returns every single time the cursor is advanced, so it makes no sense at all to return return servers multiple times. Three is that this returns too early, because it cannot return until all servers enumerated. To properly return you need to wait until all servers listed. This means using an asynchronous code pattern. For example, here is how you would do it with a callback:
function listServers(db, callbackFunction) {
  var servers = [];
  var tx = db.transaction(...);
  var store = tx.objectStore(...);
  var request = store.openCursor();

  request.onsuccess = function() {
    var cursor = request.result;
    if(cursor) {
      servers.push(cursor.value);
      cursor.continue();
    }
  };

  tx.oncomplete = function() {
    callbackFunction(servers);
  };

  return 'Requested servers to be loaded ... eventually callback will happen';
}

function connectAndList() {
  var request = indexedDB.open(...);
  request.onsuccess = function() {
    var db = request.result;
    listServers(db, onServersListed);
  };
}

function onServersListed(servers) {
  console.log('Loaded servers array from db:', servers);
}

When you call a function that does not return a value, it returns undefined. All functions in JavaScript return undefined unless you explicitly return something else.
When you call a function from the devtools console, and that function returns undefined, then the console prints out '-> undefined'. This is an ordinary aspect of using the console.
If you want to get a function that returns the list of servers as an array, well, you cannot. The only way to do that in a pretend sort of way, is to use an 'async' function, together with promises.
async function getServers() {
  var db = await new Promise(resolve => {
    var request = indexedDB.open(...);
    request.onsuccess = () => resolve(request.result);
  });

  var servers = await new Promise(resolve => {
    var tx = db.transaction(...);
    var request = tx.objectStore(...).getAll();
    request.onsuccess = () => resolve(request.result);
  });
  return servers;
}

One more edit, if you want to call this from the console, use await getServers();. If you do not use the top-level await in console, then you will get the typical return value of async function which is a Promise object. To turn a promise into its return value you must await it.

A: Clear and helpfull explanations, Thank you.
I open database multiple times beacause the first time is for checking if DB needs an upgrade and doing something if needed. I'll add 'db.close()' in each functions.
Then, I tried your exemple and the result is the same:
console.log('Loaded servers array from db:', servers); works
but return servers; Don't work.
And in console there is already an undefined without related line :
Screenshot


text:
Q: Qt : Find object in list by property i'm a beginner in Qt, I'm more used to programming in C#. So my question is how to implement in Qt the C# code bellow:
public class MyObject
{
    private string myproperty;

    public string Myproperty
    {
                get { return myproperty; }
                set { myproperty = value; }
    }
}

private void button1_Click(object sender, EventArgs e)
{
    List<MyObject> myobjectlist = new List<MyObject>();

    MyObject selectedobject = myobjectlist.Find(p => p.Myproperty == "Some name");
}

is it possible in Qt retrieve a object from list like the code above?

A: This has little to do with Qt itself. If you can use C++11, use a lambda, just like in C#:
auto itObj = std::find_if(
  myobjectlist.begin(), myobjectlist.end(),
  [](MyObject o) { return o.myproperty() == "Some name"; }
);
if (itObj != myobjectlist.end())
{
  // object was found, use *itObj (or itObj->) to access it/its members
}
else
{
  // object was not found
}

Without C++11, you'd have to hand-create a class with operator() to use as the predicate, or write a for loop by hand.

A: Maybe this way?
void MyClass::button1_Click()
{
    QList<MyObject> myobjectlist;
    MyObject selectedobject;
    foreach (const MyObject &o, myobjectlist) {
        if (o.property("Some name").isValid()) {
            selectedobject = o;
            break;
        }
    }
}

Assuming that the MyObject is a QObject.

A: Add to .pro file
CONFIG +=c++11
#include <QString>
#include <QList>
#include <algorithm>
//...
//...
class MyObject
{
private:
    QString myproperty;
public:

   void MypropertySet(QString s)
   {
       myproperty=s;
   }
   QString MypropertyGet() const
   {
       return myproperty;
   }
};

void MainWindow::on_pushButton_clicked()
{
    QList<MyObject> myobjectlist;
    MyObject selectedobject=*std::find_if(myobjectlist.begin(), myobjectlist.end(),[] (const MyObject& s) { return s.MypropertyGet()=="Some name"; });

}

Main window has a button and when you click it a privete slot from main window is called
on_pushButton_clicked(). If you have more questions i can post whole files. If you are not sure that the object you are looking for is in the list then you have to check if you found it.

A: How about
MyObject selectedobject = myobjectlist.Where(p => p.Myproperty == "Some name")
                                      .FirstOrDefault();


text:
Q: Rails, Embert: view as a single page web app I have Rails app and I need to add client-rich view. The best way to do it is to use Javascript MVC framework, right? So, I choose Ember.js. But there is one problem: it seems like Embert usage suggests that I have only one view. How to organise code right?
UPD:
If I use ember-rails gem, it loads Ember for all views. How to load Ember for only one view?


text:
Q: Main Thread Checker: UI API called on a background thread: -[UIApplication applicationState] I am using google maps in Xcode 9 beta, iOS 11.
I am getting an error outputted to the log as follows:

Main Thread Checker: UI API called on a background thread: -[UIApplication applicationState]
  PID: 4442, TID: 837820, Thread name: com.google.Maps.LabelingBehavior, Queue name: com.apple.root.default-qos.overcommit, QoS: 21

Why would this be occurring as I am almost certain I'm not altering any interface elements from the main thread in my code.
 override func viewDidLoad() {

    let locationManager = CLLocationManager()

    locationManager.requestAlwaysAuthorization()

    locationManager.requestWhenInUseAuthorization()

        if CLLocationManager.locationServicesEnabled() {

            locationManager.desiredAccuracy = kCLLocationAccuracyNearestTenMeters
            locationManager.startUpdatingLocation()
        }

      viewMap.delegate = self

     let camera = GMSCameraPosition.camera(withLatitude: 53.7931183329367, longitude: -1.53649874031544, zoom: 17.0)

        viewMap.animate(to: camera)

    }

    func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
        let locValue:CLLocationCoordinate2D = manager.location!.coordinate
        print("locations = \(locValue.latitude) \(locValue.longitude)")
    }

    func mapView(_ mapView: GMSMapView, willMove gesture: Bool) {

    }

    func mapView(_ mapView: GMSMapView, idleAt position: GMSCameraPosition) {

        if(moving > 1){
            moving = 1
        UIView.animate(withDuration: 0.5, delay: 0, animations: {

            self.topBarConstraint.constant = self.topBarConstraint.constant + (self.topBar.bounds.height / 2)

            self.bottomHalfConstraint.constant = self.bottomHalfConstraint.constant + (self.topBar.bounds.height / 2)

            self.view.layoutIfNeeded()
        }, completion: nil)
    }
         moving = 1
    }

    // Camera change Position this methods will call every time
    func mapView(_ mapView: GMSMapView, didChange position: GMSCameraPosition) {
        moving = moving + 1
        if(moving == 2){

            UIView.animate(withDuration: 0.5, delay: 0, animations: {

                self.topBarConstraint.constant = self.topBarConstraint.constant - (self.topBar.bounds.height / 2)

                self.bottomHalfConstraint.constant = self.bottomHalfConstraint.constant - (self.topBar.bounds.height / 2)

                self.view.layoutIfNeeded()
            }, completion: nil)
        }
        DispatchQueue.main.async {

            print("Moving: \(moving) Latitude: \(self.viewMap.camera.target.latitude)")
            print("Moving: \(moving)  Longitude: \(self.viewMap.camera.target.longitude)")
        }
    }

A: First, make sure your invocations of google maps and ui changes are called from the main thread.
You can enable Thread Sanitizer option in Xcode using below steps:

You can put offending lines on the main thread with the following:
DispatchQueue.main.async {
    //Do UI Code here.
    //Call Google maps methods.
}

Also, update your current version of google maps. Google maps had to make a couple of updates for the thread checker.
For the question: "Why would this be occurring?"  I think Apple added an assertion for an edge case which Google then had to update their pod for.

A: Wrap the lines of code that modify the UI in DispatchQueue.main.async {} in order to make sure they execute on the main thread. Otherwise, you may be calling them from a background thread, where UI modifications are not allowed. All such lines of code must be executed from the main thread.

A: Refer this link
https://developer.apple.com/documentation/code_diagnostics/main_thread_checker
For me this worked when I called from block.

A: It's hard to find the UI code which is not executed in main thread sometimes. You can use the trick below to locate it and fix it.

*

*Choose Edit Scheme -> Diagnostics, tick Main Thread Checker.
Xcode 11.4.1
Click the small arrow next to the Main Thread Checker to create a Main Thread Checker breakpoint.

Previous Xcode
Tick on Pause on issues.

*Run your iOS application to reproduce this issue. (Xcode should pause on the first issue.)

*Wrap the code that modify the UI in DispatchQueue.main.async {}

A: I think the solution is already given,
For my issue is Keyboard on the way.
UIKeyboardTaskQueue may only be called from the main thread

A: Choose scheme -> Diagnotics, remove main thread checker, then the warning will disappear.
scheme editor


text:
Q: dataframe condition on multiple columns in python dataframe:
i_id    sg_yes_or_no
i-123   yes
i-123   yes
i-456   no
i-678   yes
i-1y6   yes
i-1y6   yes

Expected output should be:
i_id    sg_yes_or_no    sg_only_one sg_morethan_one
i-123   yes                         yes
i-123   yes                         yes
i-456   no
i-678   yes             yes
i-1y6   yes                         yes
i-1y6   yes                         yes

or
i_id    sg_yes_or_no
i-123   more_sg
i-123   more_sg
i-456   no
i-678   one_sg
i-1y6   more_sg
i-1y6   more_sg

Tried to use the below syntax but its not working:
for df['sg_yes_or_no'] in 'yes':
    if df['i_id'].nunique() == 1:
        df['sg_only_one'] = 'yes'
    elif df['i_id'].nunique() >= 1:
        df['sg_morethan_one'] = 'yes'

If the 2nd column is "yes" take the new_dataframe in to consideration and check (count) the 1st column value in the new_dataframe. if the count is 1 then write yes in 3rd column (or update the 2nd column with "one_sg"), if the count is more than 1 then write yes in 4th column (or update the 2nd column with "more_sg").
please assist

A: an elegant solution with DataFrame.pivot_table:
new_df = df.join(df.pivot_table(columns = (df.groupby('i_id')['i_id']
                   .transform('size')
                   .gt(1)),
                                values='sg_yes_or_no',
                                index=df.index,
                                aggfunc='first')
                  .rename(columns={False : 'sg_only_one',
                                   True : 'sg_morethan_one'})
                  .mask(lambda x: x.eq('no'))
                  .sort_index(axis=1, ascending=False))

print(new_df)
    i_id sg_yes_or_no sg_only_one sg_morethan_one
0  i-123          yes         NaN             yes
1  i-123          yes         NaN             yes
2  i-456           no         NaN             NaN
3  i-678          yes         yes             NaN
4  i-1y6          yes         NaN             yes
5  i-1y6          yes         NaN             yes

We can also use:
m1 = df.groupby('i_id')['i_id'].transform('size').gt(1)
m2 = df['sg_yes_or_no'].ne('no')
df['sg_morethan_one'] = df['sg_yes_or_no'].where(m & m2)
df['sg_only_one'] = df['sg_yes_or_no'].where(~m & m2)

This is possibly much more efficient when there are only two categories, but for n categories the pivot_table option is better, in addition pivot_table avoids applying n times Series.where
EDIT
new_df = df.join(df.pivot_table(columns = (df.groupby('i_id')['i_id']
                                             .transform('size')
                                             .gt(1)
                                             .astype(int)
                                             .mask(df['sg_yes_or_no'].eq('no'), 2)),
                                values='sg_yes_or_no',
                                index=df.index,
                                aggfunc='first')
                  .rename(columns={0 : "one_sg",
                                   1 : "more_sg",
                                   2 : "no_sg"})
                  .sort_index(axis=1, ascending=False))
print(new_df)
    i_id sg_yes_or_no one_sg no_sg more_sg
0  i-123          yes    NaN   NaN     yes
1  i-123          yes    NaN   NaN     yes
2  i-456           no    NaN    no     NaN
3  i-678          yes    yes   NaN     NaN
4  i-1y6          yes    NaN   NaN     yes
5  i-1y6          yes    NaN   NaN     yes


text:
Q: .htaccess Environments not working I've recently started to work with .htaccess and I can't get the environments (I think that's how are they called) to work. I basically have this:
RewriteEngine on
RewriteCond %{TIME_HOUR}%{TIME_MIN} >0600
RewriteCond %{TIME_HOUR}%{TIME_MIN} <1800
RewriteRule ^page\.html$ default.html [L]
RewriteRule ^page\.html$ defaultNight.html [L]

I'm not sure what's the problem. This is the only code I have in my .htaccess file. Do I have to make a separate directory of default.html and defaultNight.html? I have no idea.

A: Your rewrite conditions don't look right. You can have rules like this:
RewriteEngine on

# serve default.html between 8AM to 6PM
RewriteCond %{TIME_HOUR} >07
RewriteCond %{TIME_HOUR} <19
RewriteRule ^page\.html$ default.html [L]

RewriteRule ^page\.html$ defaultNight.html [L]


text:
Q: Spring + JSF - Retrieve Image from Database and Show in Brower I am developing a web site with Spring 4 + JSF 2.0 framework + MySQL Database.
I'm trying to retrieve a image from database and display it on browser.
So basically I have a table called product_t with a LongBlob column called image, which is responsible to store png files.
I need to retrieve each image from each product in a page, so:
<ui:repeat value="#{productControllerImpl.list3NotNewRandomProducts()} var="product" varStatus="status">

#{product.name}

#{product.subDescription}

 #{product.description}
</ui:repeat>

So far so good.
I search on google the following solution:
For each product in UI I need to call a Servlet in order to retrieve the image.
As I'm using JSF + Spring, I wrote the following block code in UI:
<h:graphicImage   value="/images/#{productControllerImpl.findProductImageById(product.id)}"/>

And in my productControllerImpl I have this:
@Override
public byte[] findProductImageById(Long productId) {
    byte[] productImage = null;
    HttpServletResponse response = (HttpServletResponse) FacesContext.getCurrentInstance().getExternalContext().getResponse();
    ServletOutputStream outputStream = null;
    try {
        productImage = productService.findProductImageById(productId);
        response.reset();
        outputStream = response.getOutputStream();
        response.setContentType("image/png");
        outputStream.write(productImage);
        outputStream.flush();
        outputStream.close();
    } catch(Throwable e){
        throw new RuntimeException("Error processing product image: " + e.getMessage(), e);
    }

    return null;
}

So basically I am receiving the producIt from iteration, and search on database for the respective product image (I don't know if this is the best choice).
The problem here is, when this page is accessed I receive the full image in browser:

And I'm pretty lost in this part.
Does anybody knows what I am missing here?
Thanks in advance.

A: I assume you're referring to Show image as byte[] from database as graphic image in JSF page
I believe your main issue is you're ending your response stream:
outputStream.flush();
outputStream.close();
remove them, and try it again on your doGet for the image servlet.
Personally I prefer StreamedContent with PrimeFaces as mentioned here Display dynamic image from database with p:graphicImage and StreamedContent
or OmniFaces graphicImage http://showcase.omnifaces.org/components/graphicImage rather than creating servlet to output the content.
This post by BalusC will solve all your issues: Servlet for serving static content


text:
Q: How do you trivially change a Python script to capture everything written to stdout by itself and its subprocesses? Suppose you have a big script that writes to stdout in many places, both directly (using Python features like print() or logging that goes to stdout) and indirectly by launching subprocesses which write to stdout.
Is there a trivial way to capture all this stdout?
For example, if you want the script to send an email with all its output when it completes.
By "trivial" I mean a constant rather than linear code change. Otherwise, I believe you will have to introduce redirection parameters (and some accumulation logic) into every single subrprocess call. You can capture all the output of the script itself by redirecting sys.stdout, however I don't see a similar "catch-all" trivial solution for all the subprocess calls, or indeed whatever other types of code you may be using to launch these subprocesses.
Is there any such solution, or must one use a runner script that will call this Python script as a subprocess and capture all stdout from that subprocess?

A: Probably the shortest way to do so, not python specific would be to use os.dup2() e.g.:
f = open('/tmp/OUT', 'w')
os.dup2(f.fileno(), 1)
f.close()

What it does is to replaces file descriptor 1 which would normally be your stdout. With file descriptor of f (which you can then close). After that all writes to stdout and in /tmp/OUT. This duplication is inheritable, subprocesses have fd 1 writing to the same file.


text:
Q: Scroll Counter - _.debouce fix My problem
I created a counter meant to raise or lower by one each time that the user scrolls up or down. The problem is that my counter
$('html').on('mousewheel', function (e) {
    var delta = e.originalEvent.wheelDelta;

    if (delta < 0) {
        --count;
        transitionScreen(count);
        //$('h1').text ('You scrolled down');

    } else if (delta > 0 && count < 0) {
        ++count;
        transitionScreen(count);
        //$('h1').text ('You scrolled up');
    }
});

is incrementing multiple times by the scroll.
the solution
So someone suggested underscore.js's debounce function to keep my counter function from being executed more than once per a given amount of time.
The problem is me not knowing exactly how to implement the solution:
Can someone help me use _.debounce with this function? I'm looking at the examples but don't exactly understand how to use it here. I'm new to javascript and picking it up very quickly, so any help will be much appreciated.
Documentation clipping
Debounce is used like this in documentation:
debounce_.debounce(function, wait, [immediate])

And here's an example of the useage:
var lazyLayout = _.debounce(calculateLayout, 300);
$(window).resize(lazyLayout);

Thanks!

A: $('html').on('mousewheel', _.debounce(function(e){
    var delta = e.originalEvent.wheelDelta;

    if (delta < 0) {
        --count;
        transitionScreen(count);
        //$('h1').text ('You scrolled down');

    } else if (delta > 0 && count < 0) {
        ++count;
        transitionScreen(count);
        //$('h1').text ('You scrolled up');
    }
}, 250));

That's  it.  Just like it's shown, instead of passing your function in, you pass in the result of the _.debounce function.


text:
Q: What is in a new terminal window's command history? If I open a terminal window (Gnome terminal 3.6.2) and type a command, say echo "hello", then open a new terminal window and type <Ctrl>Rhello, I might expect to be able to dig this command out of the history.
But my newly-typed command does not appear at the (reverse-i-search)`': prompt.
But some commands from some terminal do appear in the search.
So how does my Linux (Mint 17) decide which terminals' commands should appear in which other terminals' search histories?

A: Terminal application itself has no relation to the feature you describe. It's important and very useful to understand that all terminal does is the text input and output rest is done in shell. Terminal only redirects your keypresses to program running in terminal, displays output generated by that program and able to inform that program about terminal resizes. It is important to understand that because you need to know what should you configure to change behavior.
In absolute majority of cases, default shell in Linux is bash, and that is bash who does react on your ctrl-R, and all other things you do in terminal window.
Feature you talking about is bash history. There are lot of options how and when bash reads and writes history. By default, bash appends history to history file on exit from the shell, so while you typing in one shell this commands would never appear in history of other shells.
You can save after each command you typed if you add:
export PROMPT_COMMAND="history -a"

to your ~/.bashrc file.
You can also reload after each command:
export PROMPT_COMMAND="history -a; history -r"

but I don't recommend that because it makes more sense to dedicate each console for particular task and have history for that particular task till exit.

A: Since you're on Mint, we'll assume that you're running bash as your shell.
The reason you don't see recently typed commands from other windows is because bash maintains a history list in memory for the currently running process, and a different history list on disk for saving history between sessions.
When your interactive bash shell starts up, it reads your history file (~/.bash_history by default) into the runtime history list for the running shell process.  As you type new commands, they are appended only into the history list of that process, not the history file on disk.
Likewise, the bash process writes it history list to the history file on disk before exiting.
If you have commands in one terminal window (T1) that you would like to access in another window, (T2) you can do this:
T1> history -a  # append history lines from this session to the history file

T2> history -r  # read the history file and append contents to the history list

After running the above commands in different bash consoles, you should be able to find the commands from T1 in the history list of T2.
There are many environment variables and options in bash to affect the history list behavior. Find more details from the bash built-in help command: help history.  There's even more on the bash man page (man bash) and in the Bash Reference Manual.


text:
Q: How to run your .net console application to add bingmapapi key to sharepoint 365? I saw a post on how to register Bing Maps API key on Sharepoint Online using this simple .NET console application:
static void Main(string[] args)
{
    var webUrl = new Uri("<Office 365 site URL>");
    using (ClientContext ctx = new ClientContext(webUrl))
    {
        var login = "<Office 365 login email>";
        var password = "<Office 365 password>";
        var secureStrPwd = new SecureString();
        foreach (char c in password)
        {
            secureStrPwd.AppendChar(c);
        }

        var creds = new SharePointOnlineCredentials(login, secureStrPwd);
        ctx.Credentials = creds;

        var web = ctx.Web;
        web.AllProperties["BING_MAPS_KEY"] = "<Bing maps API key>";
        web.Update();

        ctx.ExecuteQuery();
    }
}

I don't know anything on .NET and I have Visual Studio 2010. What are the steps required to run this code in Visual Studio 2010?

A: To run that code in VS 2010, follow steps in Creating a Basic SharePoint Foundation Client Application:
(0. Open Visual Studio, close all dialogs opened automatically)

*

*On the File menu, point to New and click Project.

*In the New Project dialog box, select [...] Visual C# in the
  Installed Templates panel. Select Windows and then Console
  Application. Choose .NET Framework 3.5 from the drop-down at the top
  of the center panel. Type a name and location for the project in the
  Name and Location boxes. Then click OK.

*In Windows Explorer, copy the two DLLs from the server's
  %ProgramFiles%\Common Files\Microsoft Shared\web server
  extensions\14\ISAPI folder into the top-level folder of your console
  application.

*Right-click the project in Solution Explorer, click Add Reference, and
  in the Add Reference dialog box, click the Browse tab and navigate to
  the folder where you copied Microsoft.SharePoint.Client.dll and
  Microsoft.SharePoint.Client.Runtime.dll. Select the two DLLs, and
  click OK.

*Then replace empty main with a code you cited.

*Press F5 to run the application...


text:
Q: Problema al insertar setTitle("title"); No puedo creer que no pueda poner una simple Toolbar, mi código es el siguente:
MainActivity:
package com.example.a60393.calculadorakuspit;

    import android.support.v7.app.AppCompatActivity;
    import android.os.Bundle;
    import android.support.v7.widget.Toolbar;
   public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

  Toolbar toolbar = findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);
    toolbar.setTitle("Calcula el Total");  }}

toolbar
    <?xml version="1.0" encoding="utf-8"?><android.support.v7.widget.Toolbar
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/toolbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:elevation="4dp"
android:background="@color/colorPrimary"
android:popupTheme="@style/ThemeOverlay.AppCompat.Light"
android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar">
</android.support.v7.widget.Toolbar>

activity_main
<?xml version="1.0" encoding="utf-8"?>

<include
    android:id="@+id/toolBar"
    layout="@layout/toolbar"/>

<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_centerInParent="true"
    android:text="Hello World!"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintLeft_toLeftOf="parent"
    app:layout_constraintRight_toRightOf="parent"
    app:layout_constraintTop_toTopOf="parent" />

  </RelativeLayout>

A: Tengo una app donde lo hago de la misma forma:
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    Toolbar toolbar = findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);
    toolbar.setTitle("Calcula el Total");
};

Le he puesto un ; que creo que faltaba. Aunque dudo que sea eso.
Aquí una documentación que te podría ayudar:Toolbar


text:
Q: batch insert millions of records to hive using hive sql? I want to prepare sample data for test on hive table stored as parquet format. Table look like this:
hive> CREATE TABLE exps (sn STRING, buildNum STRING, shortProdName
STRING, userIV STRING, cfs STRUCT<version : STRING, name : STRING,
objArray : ARRAY<STRUCT<id : STRING, properties : INT>> >) STORED AS PARQUET;

Then I write a sql file say "sample.sql" which contains millions of lines of sql insert command.

$ /opt/hive-0.13.1/bin/hive -f sample.sql

It will result in hive start lots of map-reduce jobs and execute one by one, which is quite slow.
So my question is: is there a better way to do this?

A: There is no dummy table in Hive, so sample.sql won't work.
Since you need to try parquet format in hive using SQL, my suggestion is

*

*Load the data in a relational database like mysql.

*Import data from relational database to HDFS using Apache Sqoop.

*Create a Hive table as parquet format

*Load the data from HDFS to Hive table.

A: i am not so professional in SQL but i think this is only way to insert data to database
INSERT INTO TABLE(c1,c2,...) VALUES(v1,v2,...);


text:
Q: Python Flask app deployed on pythonanywhere error on submit I have deployed the successfully running python flask app on pythonanywhere.
Only the home page is showing but when I submit the form its throwing Internal Server Error.
What might be the case.Checking the console network ,the requests link I have used is not being visited and error comes ahead.
I have successfully installed requests and BeautifulSoup dependencies for the project in virtualenv.
Here is the code
from flask import Flask,render_template
from flask import request
#lets do the scraping here
import requests
from bs4 import BeautifulSoup

app=Flask(__name__)

@app.route('/',methods=['GET','POST'])
def index():
    if request.method== "GET" :
        return render_template('home.html',result="")
    else:
        result=requests.post("jobkhulyo.com/")
        soup1=BeautifulSoup(result.content)
        return render_template('home.html',result=soup1);

if __name__=="__main__":
    app.run(debug=True)

The GET methods is working well but for the POST methods its throwing an internal server Error. Home.html is the template file inside template directory. Same template is loaded in POST method but with some values when Form is submitted.

A: URLs passed to requests must start with a scheme, such as http:// or https://. Your URL does not, so it raises a MissingScheme exception which explains exactly what the problem is.
MissingSchema: Invalid URL 'jobkhulyo.com': No schema supplied. Perhaps you meant http://jobkhulyo.com?

As it suggests, make the request to http://jobkhulyo.com.
When running the server locally in debug mode, Flask will show tracebacks for errors that occur. In production, it will show a 500 error but still log the traceback. Enable logging to see these errors, as described in Flask application traceback doesn't show up in server log.

A: Actually the problem was pythonanywhere doesnot allow you to refer any external sites in your web app. I had few external links so the error came. You can add the external link that they have listed as whitelists which can be checked in their site.
Most importantly if its a free account you cant but It must be available on paid service


text:
Q: Java : How to override a method and throw exception? I'm trying to override a method, with throwing an exception:
class A {

    public doSomething(){
        // some of logic
    }

}

class B extends A {

    public doSomething() throws MyCustomizedException {
        try {
             // some of logic
        } catch(ExceptionX ex ) {
             throw new MyCustomizedException(" Some info ", ex);
        }
    }
}

But I get this compile time error :
Exception MyCustomizedException is not compatible with throws clause in A

The two constraints are :

*

*Using the same name of the function and the same arguments if they exist: doSomething()

*Throwing my customized exception

How can I get rid of the exception?
Thank you a lot.

A: Cannot be done.
When you override a method, you can't break the original contract and decide to throw a checked exception.
You can make MyCustomizedException unchecked.  You can throw it, but you can't require that users handle it the way you can with a checked exception.  The best you can do is add it to the javadocs and explain.

A: There is actually a way to do this - using composition rather than inheritance:
class B {
   A a = new A();
   void doSomething() throws MyException {
      a.doSomething();
      throw MyException();
   }
}

Of course by doing this your B no longer counts as an A so cannot be passed to anything expecting an A. You could use a B throughout your code though and just wrap As on demand.

A: This is not a overloading case. To overload you need methods with same signature but different argument list. This is Overriding, Use public doSomething() throws MyCustomizedException {} in class A if Class A can modify.
Now you can override with your current implementation for class B.

A: The only way you can do this is to make the exception that you are throwing extend RuntimeException instead of Exception.
This way you will be able to throw it as you don't change the compact of the method, unfortunately the compiler will not automatically detect that you need to catch that exception but depending on how you are using it that may not be a problem.


text:
Q: Live server error: InvalidArgumentException in FileViewFinder.php line 137: View [welcome] not found I have developed a Laravel application which works well on a local machine.
Local is windows and live server is linux.
On live it gives error like

InvalidArgumentException in FileViewFinder.php line 137:
  View [welcome] not found.

in FileViewFinder it still takes path of Xampp/htdocc/xxx

FileViewFinder->findInPaths('welcome', array('C:\xampp\htdocs\CRM\resources\views', '/mnt/data/vhosts/casite-673772.cloudaccess.net/httpdocs/CRM/app\Modules\User\Views')) in FileViewFinder.php line 79

A: @thanks i have done it through route like
Route::get('/cmd', function () {
    chdir('../');
    $dir =  getcwd();
    print_r($dir);
    $cmd = shell_exec ('php artisan cache:clear');
    return $cmd;
});


text: Q: Device access through Rails on LAN The device I am attempting to access is a PLC with a built in web server. I am trying to pull data through the PLC's unique IP address. I have a computer running the Rails application sitting inside the same Local Area Network as the PLC. With the computer still INSIDE the network, can I access a device IP through my Rails app? I'm not sure how the request works. Will Rails move directly to the ISP and search that way or will it scan the local network first?


text:
Q: How do I convert a base64 string to a png image in PHP? I am trying to create a PHP form that outputs a PDF (using mPDF) of all the values in the form after hitting submit. I have included jSignature which takes in an e-signature drawn by the user. The signature is then converted to an image and outputs the data URI string in a text area.

            <input type='button' id='click' value='click'>
            <textarea id='output' name="signature"></textarea>

            <button type="submit" class="btn btn-success btn-lg">Submit</button>

I have another file that uses the name attribute from the input areas to display the values from each input field to show on the PDF. Since the signature comes in as a data URI string I have to convert it back into a png image before creating the PDF. What I am sure of at the moment is that I am able to retrieve the data URI string and I am able to replace the "image/png;base64" string that comes with it so all I am left with is the data itself. But I am struggling to decode the URI back to an image and I am not sure about how I should display it back as an image.
<?php

require_once __DIR__ . '/vendor/autoload.php';

//grab variables
$inspection = $_POST['inspection'];
$ccOfficer = $_POST['cco-name'];
$inspector = $_POST['inspector'];
$tower = $_POST['tower'];
$strata = $_POST['strata'];
$suite = $_POST['suite'];
$phone = $_POST['phone'];
$email = $_POST['email'];
$signature = $_POST['signature'];

//Create new PDf instance
$mpdf = new \Mpdf\Mpdf();

$mpdf->debug = true;

$signature = str_replace('image/png;base64,','', $signature);

$signatureDecode = base64_decode($signature);

$im = imagecreatefromstring($signatureDecode);

if(!$im) {
    die('Base64 value is not a valid image');
};

// $img_file = '/wti-report-form/images/signature.png';
// imagepng($im, $img_file, 0);

//$file = fopen($output_file, "wb");

//fwrite($file, $signatureDecode);
//fclose($file);

//Create our PDF
$data = '';

$data .= '
ARC - NEW HOME WALK-THROUGH CHECKLIST
';

//add data
$data .= 'Inspection Date ' . $inspection . '
';
$data .= 'Customer Care Officer ' . $ccOfficer . '
';
$data .= 'This Suite was inspected by ' . $inspector . '
';
$data .= 'Tower # ' . $tower . '
';
$data .= 'Strata Lot # ' . $strata . '
';
$data .= 'Suite # ' . $suite . '
';
$data .= 'Email ' . $phone . '
';
$data .= 'Phone ' . $email . '
';
//$data .= "";
//$data .= '
' . $signature . '
';

//Write PDF
$mpdf->WriteHTML($data);

//output to the browser

$mpdf->Output('myfile.pdf', 'I');
?>

Any help will be appreciated. Thanks! :)

A: As far as I know You can use base64 data string in img tag and mpdf will render PDF correctly, did You try this solution ?
$data.='';


text:
Q: Sort an array by object field I have an array of objects

const myarray = [   {
name: 'Alex',
job: 'Doctor'   },   {
name: 'John',
job: 'Taxi Driver'   },   {
name: 'Marc',
job: 'Taxi Driver'   }, ]

How can i, for each job, print the name of the job, then all the corresponding objects ?
For example I want to be able to display:
Doctor:
Alex
Taxi driver:
John,
Marc

A: first of all create object which will store job like obj = {"Taxi driver": [],"Doctor": [] } and after you can pass array myarray.forEach(e => obj[e.job].append(e.name)) after just manipulate with object. Best regards

A: It returns an object with the result you want

const myarray = [ { name: 'Alex', job: 'Doctor' }, { name: 'John', job: 'Taxi Driver' }, { name: 'Marc', job: 'Taxi Driver' }, ]

function getJobs() {
  let result = {};
  myarray.forEach(function t(e) {
    if (!result.hasOwnProperty(e.job))  result[e.job] = [];
    result[e.job].push(e.name);
  });
  return result;
}

console.log(getJobs());

A: You can try something like this:

const myarray = [ { name: 'Alex', job: 'Doctor' }, { name: 'John', job: 'Taxi Driver' }, { name: 'Marc', job: 'Taxi Driver' } ]
const sorted = {}
myarray.forEach((e)=>{
  if(e.job in sorted){
    sorted[e.job].push(e.name);
  }else{
    sorted[e.job] = [e.name]
  }
})
console.log(sorted);

To print them in the format you want:

const myarray = [ { name: 'Alex', job: 'Doctor' }, { name: 'John', job: 'Taxi Driver' }, { name: 'Marc', job: 'Taxi Driver' } ]
const sorted = {}
myarray.forEach((e)=>{
  if(e.job in sorted){
    sorted[e.job].push(e.name);
  }else{
    sorted[e.job] = [e.name]
  }
})
for(const key in sorted){
  var str = key+': ';
  sorted[key].forEach(e=>str+=e+', ');
  console.log(str.slice(0, -2));
}


text:
Q: SQL Number Serially for common row values always starting with 1 for new value For example I have a table with values as:
A
A
A
C
C
D
E
E

And I want to result as:
1 A
2 A
3 A
1 C
2 C
1 D
1 E
2 E

Please reply with any SQL query to get above output.

A: Try this
declare @t table (name nvarchar(1))

insert into @t
select 'a' union all
select 'a' union all
select 'a' union all
select 'b' union all
select 'c' union all
select 'c' union all
select 'd'

select row_number() over(partition by name order by name) as [order], name
from @t


text:
Q: Is XmlTextWriter The Best Way To Write Out Xml Data I have a list of products I want to generate xml for currently all the products are held in a List<> object....
 List<Product> products= DataAccess.GetProducts();
            XmlTextWriter writer = new XmlTextWriter(@"C:\ProductsToXml.xml", null);

            writer.WriteComment("Nick's Test Products To Xml.");

            writer.WriteStartElement("xml");

            writer.WriteStartElement("Product");
            writer.WriteStartElement("Name");
            writer.WriteString("Almonds");
            writer.WriteEndElement();

            //end for product
            writer.WriteEndElement();

            //end for xml
            writer.WriteEndElement();
            writer.Close();

Now I was gonna use this skeleton and loop through all the products and add xml like the skeleton shows above. The thing is there is gonna be alot of writer.WriteStartElement instructions because my products have alot of data in them. I am not sure if this is the best way to create an xml file or does it even matter? Is this approach ok for what I am doing? Basically taking a product object that has a bunch of properties in it and creating xml out of it thats all the purpose of this code is for.
Would you guys do it different?

A: What about using XmlSerializer?
See also: Introducing XML serialization @ MSDN and Changing the XML structure generated by XmlSerializer in C#.

A: I think there are two options, one use a custom XmlSerializer for List<Product> or, more straightforward use Linq to XML to serialize your products:
List<Product> products = new List<Product>();
products.Add(new Product() { Id =1, Name="Foo"});
products.Add(new Product() { Id =2, Name="Bar"});

XElement xDoc = new XElement("Products", products.Select(p => new XElement("Product",
                                                         new XAttribute("id", p.Id),
                                                         new XAttribute("name", p.Name))));
xDoc.Save(@"testOut.xml");

Output:
<?xml version="1.0" encoding="utf-8"?>
<Products>
  <Product id="1" name="Foo" />
  <Product id="2" name="Bar" />
</Products>

Edit:
Composition is pretty easy in Linq to XML - so if I wanted an outer node of "Stuff" I can just prepend that node (and add a bracket at the end of course):
XElement xDoc = new XElement("Stuff",
                             new XElement("Products", products.Select(p => new XElement("Product",
                                                                           new XAttribute("id", p.Id),
                                                                           new XAttribute("name", p.Name)))));

you can just duplicate this approach for your "Categories" list, just have new XElement("Categories") ... and so on.

A: I have this in my code:
XmlSerializer serializer = new XmlSerializer(typeof(ObservableCollection<Item>));
TextWriter textWriter = new StreamWriter(@"items.xml");
serializer.Serialize(textWriter, items);
textWriter.Close();

which creates an .xml files with the root of 'arrayofitems'.

A: How about making use of LINQ for serializing data? There are several articles on the net. Here is one. http://kiranpatils.wordpress.com/2008/09/23/generic-list-to-xml-using-linq/


text:
Q: Creating a single URL with htaccess Is it possible to create a single URL with htaccess? Below are examples of SELF URLs I need.
example:
localhost/blog (category)
localhost/frequently-asked-questions (content)
localhost/book (tag)
  RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-l

    RewriteRule ^(en|de|tr)/?$ ?lang=$1 [QSA,NC,L]

    RewriteCond $1 !^(css|js|images|inc|lang)

    RewriteRule ^([0-9a-zA-Z-_]+)-([0-9]+)$ article.php?url=$1&id=$2 [L,QSA]

    RewriteRule ^([0-9a-zA-Z-_]+)$  article.php?caturl=$1&catid=$2 [L,QSA]

    RewriteRule ^([0-9a-zA-Z-_]+)$  tag.php?tagurl=$1&id=$2 [L,QSA]

A: Since there is no "main" differences that can tell you that the requested URL point to specific type of content, I will suggest 2 approaches :
1.
Define prefixes for category and tag and article routes
RewriteRule ^/category/([0-9a-zA-Z-_]+)$  article.php?caturl=$1&catid=$2 [L,QSA]

RewriteRule ^/tag/([0-9a-zA-Z-_]+)$  tag.php?tagurl=$1&id=$2 [L,QSA]

RewriteRule ^/article/([0-9a-zA-Z-_]+)-([0-9]+)$ article.php?url=$1&id=$2 [L,QSA]

*

Redirect all url's to php script that will query DB and search the type of the content by the url
RewriteRule ^([0-9a-zA-Z-_]+)-([0-9]+)$ content.php?url=$1 [L,QSA]

and then inside this content.php run queries against categories table,
if no matches so search in tags table... and so on...
until no matches redirect to 404 page.
After you find the relevant content type you can include the relevant php file to continue handle this request.


text:
Q: UVM phase singletons After browsing a bit through the UVM source code, I noticed that singletons for each phase exist. For the run phase this can be accessed by calling uvm_run_phase::get().
I tried calling uvm_run_phase::get() from both the run_phase and the end_of_elaboration phase and as expected both calls returned a handle to the same object. I am a bit puzzled as the object returned by this method is not the same object that is passed to the run_phase(...) task as it's phase argument.
I've created an example on EDA Playground: http://www.edaplayground.com/x/2PL
Does anyone know exactly what the phase argument getting passed to phase methods is and why it's not the singleton?

A: After asking the question on the UVM forum, I've found out that there are multiple instances of uvm_phase for each phase that get created, one being used for scheduling and the other being used as the actual implementation.
Calling uvm_run_phase::get() will return the implementation node for the run phase, whereas the argument being past to run_phase(...) is the scheduling node. To get the scheduling node from any other phase, one can use phase.find_by_name("run",0).
Here is the link to the original thread in the UVM forum: http://forums.accellera.org/topic/1769-uvm-phase-singletons/


text:
Q: Operator showing true for all keys in for loop I'm loading some data into the page and then iterating through it.  I only want certain keys visibly appended to the page.  (The others should be appended in hidden input.)  It seems like the if statement is checking to see if any key is true for any value in the object instead of just the particular key and value in the loop.  Anyway here is what is not working.
//example data
var yaml = {"title": "blog", "author": "John Doe", "layout": "blog.hbt", "url": "my-blog", "date": "10-2-2015"};

function addYaml(data) {
    for (var key in data) {
        if (key == 'title'||'author'||'layout') {
            var type = 'text';
            var label = ""+key+"";
            $('#input').append(label+'
');
            }
            else{var type = 'hidden';}

            var input = "<input type='"+type+"' name='"+key+"' value='"+data[key]+"' />";
            $('#input').append(input+'
');
        }
    }

addYaml(yaml);

It appends everything (the hidden property is never applied).  No matter if the key is not 'title, author, or layout'.

A: (key == 'title'||'author'||'layout') is not valid for your case, it will always return title Logical OR is short-circuited and any non-empty string is truthy. So essentially what you are doing is (key == 'title' || true). Change it to check individually.
if (key == 'title' || key == 'author' || key == 'layout') {

A: You can also use syntax like this:
// Near the top of the function
var targets = ["title", "author", "layout"];

// Later on:
if (targets.indexOf(key) !== -1) {
  // A valid target
}


text:
Q: How to find the center point and radius of a circle given two sides and a single point
I have a wooden shelf (blue) with a support (red). The support is 17 cm long and 5 cm from the right edge of the shelf. I want to cut a part of the board that is in the lower right corner so that the support does not stick out underneath the board but the board is "as round as possible" on that corner. The green circle is there just to cut that one corner and is not a real physical object. How can i find the center point (as x y coordinates) and radius of the green circle?
I am sawing an actual shelf and it also needs to be done on the left side of the shelf.
EDIT: for clarity, the only relevant part of the circle is the bottom right. The circle is "fixed" to the bottom and the right side of the shelf. Also the top of the red line seems to be on the circle, but this is irrelevant, only the bottom of the red line should be on the circle.

A:
The question can be restated as:

find the circle,  inscribed in the
lower right corner,  which passes through the point $F$ (the lower end
of the support.

Using similarity, the center of the sought circle can be found by construction as follows.

*

*Draw the line $BG$ that bisects the lower right corner
(the center of the circle must be located on it).

*Choose any point $O_1$ on that line and draw circle $\mathcal{C_1}$ with the radius $r_1$
such that it touches the bottom and the right side.

*Find the point $F_1$ at the intersection of the line $FB$ and the circle $\mathcal{C_1}$

*find the scaling factor
\begin{align}
k&=\frac{|FB|}{|F_1B|}
.
\end{align}

*The radius of the sought circle is $r=k\cdot r_1$.

For the given dimensions, the value of the sought radius can be found as
\begin{align}
r&=18+\sqrt{130}
\approx 29.40 \mathrm{cm}
.
\end{align}
Also, the center $O$ of the sought circle can be found
at the intersection of the line $BG$
and the line through the point $F$
parallel to the line $F_1O_1$.

Edit

In general, for given shelf length $|AB|=|CD|=l$,
width $|AD|=|BC|=w$,
length of the support $|EF|=v\le w$
and offset  $|CE|=u$, the radius of the circle can be found as
\begin{align}
r&=u+w-v+\sqrt{2u(w-v)}
.
\end{align}


text:
Q: Indexing multidimensional numpy-array with list I have a problem accessing the data in a multidimensional numpy-array with python 2.7. The goal is to read multiple values whose positions are stored in a list.
import numpy as np
matrix=np.ones((10,30,5))

positions=[]
positions.append([1,2,3])
positions.append([4,5,6])

for i in positions:
    print matrix[i]

What I want is:
print matrix[1,2,3]

But I get:
print [matrix[1], matrix[2], matrix[3]]

Could you please give me a hint for the correct indexing? Thanks!

A: From indexing docs:

In Python, x[(exp1, exp2, ..., expN)] is equivalent to x[exp1, exp2,..., expN]; the
  latter is just syntactic sugar for the former.

So, instead of passing it a list, pass a tuple to matrix:
for i in positions:
    print matrix[tuple(i)]

Lists are used for picking item at particular indices, i.e index arrays:
>>> arr = np.random.rand(10)
>>> arr
array([ 0.56854322,  0.21189256,  0.72516831,  0.85751778,  0.29589961,
        0.90989207,  0.26840669,  0.02999548,  0.65572606,  0.49436744])
>>> arr[[0, 0, 5, 1, 5]]
array([ 0.56854322,  0.56854322,  0.90989207,  0.21189256,  0.90989207])


text:
Q: Why can't I select the code signing identity in XCode to validate the app really simple problem became a disaster =).
 I can't select the needed code signing identity in Xcode. Why is it so?? The certificates and the keys are ok. Here is picture:

Any ideas???

A: Please check your bundle Identifier . This is guess , but this may be the case. Your bundle identifier must match with your app Id. You can change bundle ID from the .plist file .

A: Have you checked your certificate? Today I had same problem where I was unable to select Code Signing Identity after selecting Provisioning Profile and it turns out my certificate has expired.


text:
Q: Arrays in Textboxes I am making a user password database to be written onto a file. I have tried experimenting with the string array username, but it still renders like the same with a regular string; the output prints whatever you entered last in the second line of the file (the first being Username, Email...)
btnNewButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
    openFile();
    addRecords();
    closeFile();
}

public void addRecords(){
    int records = Integer.parseInt(textField_4.getText());
    x.format("%-25s %-25s %-25s %-25s \n", "Username", "Email", "Mojang Password", "Email Password");
    String username[] = new String[records];
    for(int counter = 0; counter<records; counter++){
        username[counter] = textField.getText();
        textField.setText("");
        String email = textField_1.getText();
        String userpass = textField_2.getText();
        String emailpass = textField_3.getText();
        x.format("%-25s %-25s %-25s %-25s \n", username[counter], email, userpass, emailpass);
    }

A: The way you are storing the data needs to be changed. Each record should be like this
record[0] - {username,email,userpass,emailpass} -  for user 1
record[1] - {username,email,userpass,emailpass} -  for user 2

save it as
for user1 -
record[0][0] = username
record[0][1] = email
record[0][2] = userpass
record[0][3] = emailpass

for user2 -

record[1][0] = username
record[1][1] = email
record[1][2] = userpass
record[1][3] = emailpass

and when you access it
for(int counter = 0; counter<records; counter++){
        username = record[counter][0];
        String email = record[counter][1];
        String userpass = record[counter][2];
        String emailpass = record[counter][3];
        x.format("%-25s %-25s %-25s %-25s \n", username, email, userpass, emailpass);
    }


text:
Q: Baire and Measure Please,I would like help with this problem.
We say that a subset $E$ of a topological space $X$ has the property of Baire if $E=G\Delta P$, where $G\subseteq X$ is open and $P \subseteq X$ is meager. Prove the following statements.

*

*A set $E\subset X$ has the property of Baire if and only if $E = F \Delta Q$, where $F \subset X$ is closed and $Q \subset X$ is meager.

*If $ E \subset X $ has the property of Baire, then $ E^c $ also has.

*The class ${\cal{B}}_a(X)=\left\{E \subseteq  X \ ; \ E \ \mbox {has the property of Baire} \right\}$ is a  $\sigma$-algebra.

*The $\sigma$-algebra ${\cal {B}}_a(X)$ is generated by the open subsets of $X$ with the meager subsets of $X$.

A: Remark: notice that for any sets $A,B,C$, we have $A=B\Delta C$ iff $B=A\Delta C$ iff $C=A\Delta B$.

*

*Let's prove both implications simultaneously: Suppose $E=G\Delta P$ for $G$ open (closed) and $P$ meager. Let
$G'=\begin{cases}\overline{G}&\text{, if }G\text{ is open}\\\operatorname{int}G&\text{, if }G\text{ is closed}\end{cases}$.
Notice that, in both cases,
$$E\Delta G'\subseteq (E\Delta G)\cup (G\Delta G')=\underbrace{P}_{\text{meager}}\cup\underbrace{\partial G}_{\text{meager}}$$
(you can show that the frontier of open and closed sets is always nowhere dense), so $Q:=E\Delta G'$ is meager. By the remark above, $E=G'\Delta Q$, with $G'$ closed (open) and $Q$ meager.

*If $E$ has the Baire Property, then $E=G\Delta P$, $G$ open and $P$ meager. Since $E^c=\underbrace{G^c}_{\text{closed}}\Delta \underbrace{P}_{\text{meager}}$, then $E^c$ has the Baire Property, by item 1.

*By item 2, $\mathcal{B}_a(X)$ is closed by complements, so it remains only to show that $\mathcal{B}_a(X)$ is closed by countable unions: Suppose $\left\{E_n\right\}_{n\in\mathbb{N}}\subseteq \mathcal{B}_a(X)$. Then each $E_n$ can be written as $E_n=G_n\Delta P_n$, $G_n$ closed and $P_n$ meager. Notice that
$$\left(\bigcup_{n\in\mathbb{N}}E_n\right)\Delta\left(\bigcup_{n\in\mathbb{N}}G_n\right)\subseteq\bigcup_{n\in\mathbb{N}}(E_n\Delta G_n)=\underbrace{\bigcup_{n\in\mathbb{N}}\underbrace{P_n}_{\text{meager}}}_{\text{meager}}$$
so $Q=\left(\bigcup_{n\in\mathbb{N}}E_n\right)\Delta\left(\bigcup_{n\in\mathbb{N}}G_n\right)$ is meager. By the remark, $\bigcup_{n\in\mathbb{N}}E_n=\underbrace{\left(\bigcup_{n\in\mathbb{N}}G_n\right)}_{\text{open}}\Delta \underbrace{Q}_{\text{meager}}$ has the Baire Property.
Therefore, $\mathcal{B}_a(X)$ is a $\sigma$-algebra.

*Every element of $\mathcal{B}_a(X)$ is the symmetric difference of open and meager sets, so $\mathcal{B}_a(X)$ is contained in the $\sigma$-algebra generated by open and meager subsets of $X$. Conversely, every open/meager subset $A$ of $X$ can be written as $A=A\Delta\varnothing$, so $A$ has the Baire Property, that is, $A\in\mathcal{B}_a(X)$. This shows that $\mathcal{B}_a(X)$ is generated by the meager and open subsets of $X$.


text: Q: После залива сайта на хостинг с WordPressa, перестало все работать в панели администратора Залил все на хостинг и домен, добавил базу данных (раз 30 уже повторил это и заново на хостинг заливал), но сейчас если я захочу удалить или добавить плагин, у меня ничего не происходит. Просто нажимается и как будто кнопка статическая. Так же и со всем остальным, нельзя добавить страницу, изменить ссылку страницы и все остальное. Но при этом сам сайт работает.


text:
Q: Issues with initializing service class that has dependency on running application on startup (play 2.4 / scala) I am currently digging into using Quartz in our play 2.4 application.
Initially, I tried initializing everything through Global object, and everything worked perfectly.
Now, I an trying to move away from Global utilize modules infrastructure.
Here is what I have until now.
JobSchedulingService
@Singleton
class JobSchedulingService @Inject()(lifecycle: ApplicationLifecycle) extends ClassLogger{

  lazy val schedulerFactory = current.injector.instanceOf[StdSchedulerFactory]

  lazy val scheduler = schedulerFactory.getScheduler

  /**
    * Let's make sure that scheduler shuts down properly
    */
  lifecycle.addStopHook{ () =>
    Future.successful{
      if (scheduler.isStarted) {
        scheduler.shutdown(true)
      }
    }
  }

  protected def init() : Unit = {
    logger.info("Initializing scheduler...")
    scheduler.start()
  }

  init()
}

SchedulerModule -  here for initialization of the service above.
class SchedulerModule extends AbstractModule{
  override def configure(): Unit = {
    bind(classOf[JobSchedulingService]).asEagerSingleton
  }
}

And in my application.conf I added:
play.modules.enabled += "scheduling.modules.SchedulerModule"

It looks pretty strait forward. However, when the app starts I am getting an exception:

2016-03-23 00:07:42,173 INFO  s.JobSchedulingService - Initializing
  scheduler... 2016-03-23 00:07:42,213 ERROR application -
! @6pfp72mh6 - Internal server error, for (GET) [/] ->
play.api.UnexpectedException: Unexpected exception[CreationException:
  Unable to create injector, see the following errors:
1) Error injecting constructor, java.lang.RuntimeException: There is
  no started application   at
  scheduling.JobSchedulingService.(JobSchedulingService.scala:15)
  at
  scheduling.modules.SchedulerModule.configure(SchedulerModule.scala:11)
  (via modules: com.google.inject.util.Modules$OverrideModule ->
  scheduling.modules.SchedulerModule)   while locating
  scheduling.JobSchedulingService
...

The thing is, in our app, the scheduler is based of off persistence job storage and should restart when the application restarts. Again, when I did it through Global, it worked perfectly.
How do I get around this problem? What is the correct way to initialize an instance on startup?
Thanks,

A: You should probably be using the dependency injection for everything. Inject the scheduler like..
class JobSchedulingService @Inject()(lifecycle: ApplicationLifecycle, schedulerFactory: StdSchedulerFactory) extends ClassLogger{
  lazy val scheduler = schedulerFactory.getScheduler

A: Hmmm...
I think I just resolved it.
It seems like the problem was not the actual initialization of a class, but this line:
lazy val schedulerFactory = current.injector.instanceOf[StdSchedulerFactory]

once I changed it to:
lazy val schedulerFactory = new StdSchedulerFactory

it started working.
May that will help somebody


text:
Q: $V$ is Banach space, invertible operators $T_n \to -I$ in $B(V) \implies T^{-1}_n → -I$. Im stuck at this problem. I know that $f_n(f^{-1}_n+I)=(I+f_n)$. But I can't seem to use this fact. Any hints?
P.s. I tried to use some epsilon proof but I got stuck.

A: Note that $$\|T_n^{-1}+I\|\le \|T_n^{-1}\|\|T_n+I\|,$$ so it suffices to show $\|T_n^{-1}\|$ is bounded as $n\to\infty$. We find that for every $n$ with $\|T_n+I\|<1$,
$$
T_n^{-1}=-\sum_{k=0}^\infty (T_n+I)^k
$$ and this easily implies that
$$
\|T_n^{-1}\|\le \sum_{k=0}^\infty \|T_n+I\|^k \le \sum_{k=0}^\infty 2^{-k}=2
$$ for every $n$ such that $\|T_n+I\|\le \frac12$.


text:
Q: Clickhouse RBAC implementation I have been looking at the RBAC documentation but I cannot find something specific, like default roles or a set of privileges that will apply to a common role. I work a lot with SQL Server which comes with out of the box roles and I would like to create the equivalent on Clickhouse, is there any general implementation already out there?
My goal is to have sysadmin, securityadmin, ddladmin, processadmin roles.
Thanks


text:
Q: How to use Scandit plugin in ionic 2 I am trying to scan barcode with Scandit sdk or plugin. How to import scandit plugin in .ts file in ionic2.
My code is
import { Component } from '@angular/core';

import { NavController } from 'ionic-angular';

import { BarcodeScanner } from 'ionic-native';

import { Platform } from 'ionic-angular'

declare var Scandit;
declare var picker;

@Component({
selector: 'page-home',
templateUrl: 'home.html'
})
export class HomePage {

constructor(public navCtrl: NavController) {

}
success(session) {
alert(session.newlyRecognizedCodes[0].data);
}

failure(error) {
alert("Failed: " + error);
}

scan()
{
Scandit.License.setAppKey("My key");
var settings = new Scandit.ScanSettings();
settings.setSymbologyEnabled(Scandit.Barcode.Symbology.EAN13, true);
settings.setSymbologyEnabled(Scandit.Barcode.Symbology.UPC12, true);
settings.setSymbologyEnabled(Scandit.Barcode.Symbology.EAN8, true);
settings.setSymbologyEnabled(Scandit.Barcode.Symbology.CODE39, true);
settings.codeDuplicateFilter = -1;
picker = new Scandit.BarcodePicker(settings);
picker.continuousMode = true;
picker.getOverlayView().setViewfinderDimension(0.9, 0.2, 0.6, 0.2);
picker.setMargins(new Scandit.Margins(0, 0, 0, 200), null, 0);
picker.show(success, null, failure);
picker.startScanning();
}
stop()
{
picker.cancel();
}

start()
{
picker.startScanning();
picker.setMargins(new Scandit.Margins(0, 0, 0, 200), null, 0.5);
picker.getOverlayView().setViewfinderDimension(0.9, 0.2, 0.6, 0.2);
}

}

I write this code based upon this link -   http://krishjan.com/2016/10/27/multiple-barcode-scanning-in-ioniccordova-using-scandit-api/
But it doesn't working. How can I Scan barcode using scandit plugin.
Thanks for the answer.

A: I solve my problem with importing the plugin into .ts file like this
import { Scanditsdk } from plugins/com.mirasense.scanditsdk.plugin/plugin.xml

Then it perfectly works.


text:
Q: Deleting an existing file in java and renaming the temp file I want to read an existing file and write the file contents to another temp file without a particular line...
  i could not able to delete the existing file and renaming the temp file...
File tf = new File("F:\\nb\\project_inventory\\temp.tmp");

       FileReader fr = new     FileReader("F:\\nb\\project_inventory\\Employee_info.txt");
       BufferedReader br =new BufferedReader(fr);

       FileWriter fw = new FileWriter(tf);
       PrintWriter bw =new PrintWriter(fw);
       String line;
        while((line=br.readLine())!=null)
        {
            if(line.contains(del_id)) continue;

            bw.println(line);

        }

        bw.close();
        fw.close();
        br.close();
        fr.close();
        File real =new File("F:\\nb\\project_inventory\\Employee_info.txt");
        real.delete();
        tf.renameTo(real);


text:
Q: Jhipster error An unexpected error occurred: https://registry.yarnpkg.com/bower Because of the Chinese GFW, when I finished the Hipster configuration and generate the code, run via mvn spring-boot:run I got an issue with the message as follow:

error An unexpected error occurred:
  "https://registry.yarnpkg.com/bower: tunneling socket could not be
  established, cause=connect ECONNREFUSED 127.0.0.1:3128".

I did something as Hipster office site to set the proxy, but it doesn't work.
I set the ~/.npmrc as follow: proxy=127.0.0.1:3128 http-proxy=127.0.0.1:3128 http_proxy=127.0.0.1:3128 registry=registry.npm.taobao.org
Could someone tell me how to fix it? Thanks a lot!


text:
Q: Handling click event of switch widget on action bar This is how I added a switch widget to the action bar. I'm already playing with it. But I'm not knowing how to respond to the click events.
@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.map, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    System.out.println("actionbar clicked");
    // Handle item selection
    if (item.getItemId()==R.id.myswitch) {
        Switch actionView = (Switch)item.getActionView();
        actionView.setOnCheckedChangeListener(new OnCheckedChangeListener(){
            @Override
            public void onCheckedChanged(CompoundButton buttonView, final boolean isChecked) {
                status = isChecked;
                System.out.println(status);
            }
        });

        return true;
    }
    return super.onOptionsItemSelected(item);
}

This is my switch layout and map resource file
switch_status.xml
<?xml version="1.0" encoding="utf-8"?>
<Switch
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/switch1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:showText="true"
    android:textOff="Free"
    android:textOn="Booked" />

map.xml
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" >

<item
    android:id="@+id/myswitch"
    android:showAsAction="always"
    android:title=""
    android:actionLayout="@layout/switch_status" />
</menu>

While clicking the switch, It is changing its state, but I cannot see even one msg on the console like "actionbar clicked" & "true" / "false". And there is no error either.
I'm not sure weather this is the correct way of handling clicks on actionbar. If any one can help me with this code, it will be really nice.
Thankyou

A: Best way for do this using Toolbar .
In Toolbar you can add any view and control this.

A: You don't need to set a OnCheckedChangeListener, onOptionsItemSelected is a "onClickListener"
use switch for this:
@Override
public boolean onOptionsItemSelected(MenuItem item) {
    System.out.println("actionbar clicked");
    // Handle item selection
    switch (item.getItemId()) {
        case R.id.myswitch:
           System.out.println(((Switch)item.getActionView()).isChecked());
        break;
    }
    return super.onOptionsItemSelected(item);
}

A: I had the same issue and achieved by following below technique

*Added onClick method for switch like below
<Switch
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/switch1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:showText="true"
    android:textOff="Free"
    android:textOn="Booked"
    android:onClick="onSwitch"
/>

*Implement onSwitch method in Activity as below:
public void onSwitch(View view) {
    Switch androidSwitch = findViewById(R.id.switch1);
    if(androidSwitch.isChecked()){
        Log.i("Test","enabled");
    }else{
        Log.i("Test","disabled");
    }
}


text:
Q: How to crop and save segmented objects from an image? I have a hyperspectral image. In each image, there are many objects. I have to segment, crop, and save them as separate images. The segmented image after applying the thresholding is as below:

The problem is that I have to crop the segmented objects and save them. How it can be done?

A: Here's a simple approach:

*

*Obtain binary image. Load the image, convert to grayscale, and Otsu's threshold to obtain a binary image.

*Remove noise. We morphological operations to remove any particles of noise in the image.

*Extract objects. From here we find contours, obtain each bounding rectangle then extract and save each ROI using Numpy slicing.

Detected objects

Saved ROIs

import cv2
import numpy as np

# Load image, grayscale, Otsu's threshold
image = cv2.imread('1.jpg')
original = image.copy()
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
thresh = cv2.threshold(gray, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)[1]

# Morph open to remove noise
kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (5,5))
opening = cv2.morphologyEx(thresh, cv2.MORPH_OPEN, kernel, iterations=1)

# Find contours, obtain bounding box, extract and save ROI
ROI_number = 0
cnts = cv2.findContours(opening, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
cnts = cnts[0] if len(cnts) == 2 else cnts[1]
for c in cnts:
    x,y,w,h = cv2.boundingRect(c)
    cv2.rectangle(image, (x, y), (x + w, y + h), (36,255,12), 2)
    ROI = original[y:y+h, x:x+w]
    cv2.imwrite('ROI_{}.png'.format(ROI_number), ROI)
    ROI_number += 1

cv2.imshow('image', image)
cv2.imshow('thresh', thresh)
cv2.imshow('opening', opening)
cv2.waitKey()


text:
Q: Deploy a nodejs project in Microsoft Azure containing backend only I am developing a angular project with node js as backend. In the backend microservices are used. Frontend and backend are seperate projects. I am trying to deploy both in azure. I was able to deploy the front end properly. I tried to deploy the backend too. But it was not successful. Does anyone know how to deploy a node js project with backend only in azure ?
UPDATE:
The thing is that I don't have a dist folder to build the node project. It just contains a server with microservices. What we do is we will use npm start to run it. When I try to hit the backend from the frontend, I get an saying that "You don't have the permission to view the directory or page".