text:
Q: With the Ajax Control Toolkit, how would I go about programmatically creating an accordion control that is resizeable and drag/droppable at runtime? I was trying to generate a resizable and drag/droppable ajax control toolkit accordion control programmatically, but am running into some problems.
First, can it be done?
Second, my approach is not exactly working.
I have a button that, OnClick, is supposed to create the accordion. So I create the accordion.  Add an accordion pane to it.  Add a combo button to the accordion pane.  Then add the entire accordion to the Ajax Panel.  My event handler follows.
    protected void btnTest_Clicked(object sender, EventArgs e)
    {
        //Generate the accordion
        AjaxControlToolkit.Accordion acc = new AjaxControlToolkit.Accordion();

        //Generate a single accordion pane
        AjaxControlToolkit.AccordionPane itm = new AccordionPane();

        //Create and add a control to the pane
        AjaxControlToolkit.ComboBoxButton cbbtn = new ComboBoxButton();
        itm.Controls.Add(cbbtn);
        acc.Panes.Add(itm);

        //Add resizable extender to the accordion.  Only did resizable for now.
        //One step at a time.
        AjaxControlToolkit.ResizableControlExtender extResizeLocation = new AjaxControlToolkit.ResizableControlExtender();
        extResizeLocation.TargetControlID = acc.ID;
        extResizeLocation.Enabled = true;

        //Add accordion to update panel and update.
        UpdatePanel1.Controls.Add(acc);
        UpdatePanel1.Update();
    }

What I get when I press the test button is what appears to be a minimized button without text generated under the test button.  I have no clue what to do.
Appreciate the help

A: Dynamically added controls are typically supposed to be added during init or preinit event of the page.  That may be a complication, since you are doing it after load.
The key is to make sure the $register method on the client for the accordion is occurring.  This is what initializes the client-side features of the AJAX component, and starts the lifecycle.  I don't know if it happens for dynamically added controls...

A: You may want to look at the JQuery UI Accordian widget and use the draggable/droppable interactions.
You could use server side code to create an  block and apply the jQuery interaction.


text:
Q: How can I create or delete a file in springboot jar using java program after its deployment I have folder in class path which contains only resources file's that are to be accessed.  I cannot give that files from file system. What I need is after deploying spring  boot jar with command
Java -jar somename.jar

I want to create or delete files inside my resource  folder in the jar

redpajama_set_name: RedPajamaStackExchange


text:
Q: Shellcode doesn't work when pulled out of binary I'm learning to write shellcode and am trying to read a file (in this case, /flag/level1.flag). This file contains a single string.
Through looking at tutorials online, I've come up with the following shellcode. It opens the file, reads it byte by byte (pushing each byte onto the stack), then writes to stdout giving the pointer to the top of the stack.
section .text

global _start

_start:
    jmp ender

starter:
    pop ebx                     ; ebx -> ["/flag/level1.flag"]
    xor eax, eax
    mov al, 0x5                 ; open()
    int 0x80
    mov esi, eax                ; [file handle to flag]
    jmp read

exit:
    xor eax, eax
    mov al, 0x1               ; exit()
    xor ebx, ebx                ; return code: 0
    int 0x80

read:
    xor eax, eax
    mov al, 0x3                 ; read()
    mov ebx, esi                ; file handle to flag
    mov ecx, esp                ; read into stack
    mov dl, 0x1                ; read 1 byte
    int 0x80

    xor ebx, ebx
    cmp eax, ebx
    je exit                     ; if read() returns 0x0, exit

    xor eax, eax
    mov al, 0x4                 ; write()
    mov bl, 0x1                 ; stdout
    int 0x80
    inc esp
    jmp read                  ; loop

ender:
    call starter
    string: db "/flag/level1.flag"

Here's what I do to compile and test it:
nasm -f elf -o test.o test.asm
ld -m elf_i386 -o test test.o

When I run ./test, I get the expected result. Now if I pull the shellcode out of the binary and test it in a stripped down C runner:
char code[] = \
"\xeb\x30\x5b\x31\xc0\xb0\x05\xcd\x80\x89\xc6\xeb\x08\x31\xc0\xb0\x01\x31\xdb\xcd\x80\x31\xc0\xb0\x03\x89\xf3\x89\xe1\xb2\x01\xcd\x80\x31\xdb\x39\xd8\x74\xe6\x31\xc0\xb0\x04\xb3\x01\xcd\x80\x44\xeb\xe3\xe8\xcb\xff\xff\xff\x2f\x66\x6c\x61\x67\x2f\x6c\x65\x76\x65\x6c\x31\x2e\x66\x6c\x61\x67";

int main(int argc, char **argv){
    int (*exeshell)();
    exeshell = (int (*)()) code;
    (int)(*exeshell)();
}

Compiled the following way:
gcc -m32 -fno-stack-protector -z execstack -o shellcode shellcode.c

And then run it, I see that I read the file properly, but then continue to print garbage to the terminal (I have to Ctrl+C).
I'm guessing it has to do with read() not encountering a \x00 and, thus continuing to print data from the stack until it finds the null marker. Is that correct? If so, why does the compiled binary work?

A: TL;DR: Never assume the state of the registers when running as an exploit in a target executable. If you need an entire register zeroed out you must do so yourself. Running standalone and in a running program may behave differently depending on what is in the registers when the exploit begins to execute.

If you properly build your C code making sure the stack is executable and you build a 32-bit exploit and run it in a 32-bit executable (as you have done), the primary reason things may fail when not standalone is if you haven't properly zeroed out registers properly. As a standalone program many of the registers may be 0 or have 0 in the upper 24-bits where as inside a running program that may not be the case. This can cause your system calls to behave differently.
One of the best tools to debug shell code is a debugger like GDB. You can step through your exploit and review the register state prior to your system calls (int 0x80). An easier approach in this case is the STRACE tool (system trace). It will show you all the system calls and the parameters that are being issued by a program.
If you run strace ./test >output on your standalone program where /flag/level1.flag contains:
test

You'd probably see STRACE output something similar to:

execve("./test", ["./test"], [/* 26 vars */]) = 0
strace: [ Process PID=25264 runs in 32 bit mode. ]
open("/flag/level1.flag", O_RDONLY)     = 3
read(3, "t", 1)                         = 1
write(1, "t", 1)                        = 1
read(3, "e", 1)                         = 1
write(1, "e", 1)                        = 1
read(3, "s", 1)                         = 1
write(1, "s", 1)                        = 1
read(3, "t", 1)                         = 1
write(1, "t", 1)                        = 1
read(3, "\n", 1)                        = 1
write(1, "\n", 1
)                       = 1
read(3, "", 1)                          = 0
exit(0)                                 = ?
+++ exited with 0 +++

I redirected standard output to the file output so it didn't clutter the STRACE output. You can see the file /flag/level1.flag was opened as O_RDONLY and file descriptor 3 was returned. You then read 1 byte at a time and wrote it to standard output (file descriptor 1). The output file contains the data that is in /flag/level1.flag.
Now run STRACE on your shellcode program and examine the difference. Ignore all the system calls prior to reading the flag file as those are the system calls the shellcode program made directly and indirectly before it got to your exploit. The output may not look exactly like this but it is probably similar.

open("/flag/level1.flag", O_RDONLY|O_NOCTTY|O_TRUNC|O_DIRECT|O_LARGEFILE|O_NOFOLLOW|O_CLOEXEC|O_PATH|O_TMPFILE|0xff800000, 0141444) = -1 EINVAL (Invalid argument)
read(-22, 0xffeac2cc, 4293575425)       = -1 EBADF (Bad file descriptor)
write(1, "\211\345_V\1\0\0\0\224\303\352\377\234\303\352\377@\0`V\334Sl\367\0\303\352\377\0\0\0\0"..., 4293575425) = 4096
read(-22, 0xffeac2cd, 4293575425)       = -1 EBADF (Bad file descriptor)
write(1, "\345_V\1\0\0\0\224\303\352\377\234\303\352\377@\0`V\334Sl\367\0\303\352\377\0\0\0\0\206"..., 4293575425) = 4096
[snip]

You should notice that the open failed with -1 EINVAL (Invalid argument) and if you observe the flags passed to open there are many more than O_RDONLY. This suggests that the second parameter in ECX likely hasn't been properly zeroed. If you look at your code you have this:
pop ebx                     ; ebx -> ["/flag/level1.flag"]
xor eax, eax
mov al, 0x5                 ; open()
int 0x80

You don't set ECX to anything. When running in a real program ECX is non zero. Modify the code to be:
pop ebx                     ; ebx -> ["/flag/level1.flag"]
xor eax, eax
xor ecx, ecx
mov al, 0x5                 ; open()
int 0x80

Now generate the shellcode string with this fix and it probably looks something like:

\xeb\x32\x5b\x31\xc0\x31\xc9\xb0\x05\xcd\x80\x89\xc6\xeb\x08\x31\xc0\xb0\x01\x31\xdb\xcd\x80\x31\xc0\xb0\x03\x89\xf3\x89\xe1\xb2\x01\xcd\x80\x31\xdb\x39\xd8\x74\xe6\x31\xc0\xb0\x04\xb3\x01\xcd\x80\x44\xeb\xe3\xe8\xc9\xff\xff\xff\x2f\x66\x6c\x61\x67\x2f\x6c\x65\x76\x65\x6c\x31\x2e\x66\x6c\x61\x67

Run this shell string in your shellcode program using STRACE again and the output may appear something like:

open("/flag/level1.flag", O_RDONLY|O_EXCL|O_APPEND|O_DSYNC|0xff800000) = 3
read(3, "test\n", 4286583809)           = 5
write(1, "test\n\0\0\0\24\25\200\377\34\25\200\377@\0bV\334\363r\367\200\24\200\
377\0\0\0\0"..., 4286583809) = 4096

This is better, but there is still a problem. The number of bytes to read (third parameter) is 4286583809 (your value may be different). Your standalone code is suppose to be reading 1 byte at a time. This indicates that likely the upper 24 bits of EDX were not properly zeroed out. If you review the code you do:
read:
    xor eax, eax
    mov al, 0x3                 ; read()
    mov ebx, esi                ; file handle to flag
    mov ecx, esp                ; read into stack
    mov dl, 0x1                 ; read 1 byte
    int 0x80

At no point in this section of code (or before it) do you zero out EDX before placing 1 in DL. You can do so with:
read:
    xor eax, eax
    mov al, 0x3                 ; read()
    mov ebx, esi                ; file handle to flag
    mov ecx, esp                ; read into stack
    xor edx, edx                ; Zero all of EDX
    mov dl, 0x1                 ; read 1 byte
    int 0x80

Now generate the shellcode string with this fix and it probably looks something like:

\xeb\x34\x5b\x31\xc0\x31\xc9\xb0\x05\xcd\x80\x89\xc6\xeb\x08\x31\xc0\xb0\x01\x31\xdb\xcd\x80\x31\xc0\xb0\x03\x89\xf3\x89\xe1\x31\xd2\xb2\x01\xcd\x80\x31\xdb\x39\xd8\x74\xe4\x31\xc0\xb0\x04\xb3\x01\xcd\x80\x44\xeb\xe1\xe8\xc7\xff\xff\xff\x2f\x66\x6c\x61\x67\x2f\x6c\x65\x76\x65\x6c\x31\x2e\x66\x6c\x61\x67

Run this shell string in your shellcode program using STRACE again and the output may appear something like:

open("/flag/level1.flag", O_RDONLY)     = 3
read(3, "t", 1)                         = 1
write(1, "t", 1)                        = 1
read(3, "e", 1)                         = 1
write(1, "e", 1)                        = 1
read(3, "s", 1)                         = 1
write(1, "s", 1)                        = 1
read(3, "t", 1)                         = 1
write(1, "t", 1)                        = 1
read(3, "\n", 1)                        = 1
write(1, "\n", 1)                       = 1
read(3, "", 1)                          = 0

This produces the desired behaviour. Reviewing the rest of the assembly code it doesn't appear this mistake has been made on any of the other registers and system calls. Using GDB would have shown you similar information about the state of the registers before each system call. You would have discovered the registers didn't always have the expected values.


text:
Q: How can a float64 store more than 64 bits? I'm confused from https://tour.go-zh.org/basics/16
f := 1 << 100 * 0.1
fmt.Printf(" f : type = %8T  value = %v\n", f, f)

output: f : type =  float64  value = 1.2676506002282295e+29

The above means variable f has 101 bits, but how it can store in float64 with 64bits?
And I test it in java
double f = (1 << 100) * 0.1;
System.out.println(f);

output: 1.6

A: In Java, 1 << 100 is 16, because 1 is a 32-bit int value, so only the lower 5 bit of 100 is used.
100 = 0x64 => 0x04, and 1 << 4 = 16.
If you want full 101 bit precision, use BigInteger and BigDecimal for the calculations:
BigInteger bigInt = BigInteger.ONE.shiftLeft(100);
BigDecimal bigDec = new BigDecimal(bigInt).multiply(BigDecimal.valueOf(0.1));
double d = bigDec.doubleValue();
System.out.println("bigInt = " + bigInt);
System.out.println("bigDec = " + bigDec);
System.out.println("d = " + d);

Output
bigInt = 1267650600228229401496703205376
bigDec = 126765060022822940149670320537.6
d = 1.2676506002282295E29

Or maybe you don't use BigDecimal:
BigInteger bigInt = BigInteger.ONE.shiftLeft(100);
double d = bigInt.doubleValue() * 0.1;
System.out.println("bigInt = " + bigInt);
System.out.println("d = " + d);

Output
bigInt = 1267650600228229401496703205376
d = 1.2676506002282295E29


text:
Q: Iterating through a list to then return a value if meeting conditions I just started working with Pandas for a personal side project of mine. I've imported data from a CSV, cleaned it up and now want to use data from the CSV in the rest of my code. I want to ask a user for input and if the user input matches an entry inside the list (Which is a column inside the data) I want to get data for that instance (from the same row but other columns in the df)
I can get it to compare using the "in" statement but don't think that will work when I expand the functionality.
How would I go about looping through the list from the df to return a value from that list if it exists and then be able to return other values in the same row of the df?
import pandas as pd
import re
import math

housing_Data = pd.read_csv("/Users/saads/Downloads/DP_LIVE_26072020053911478.csv") #File to get data
housing_Data = housing_Data.drop(['INDICATOR', 'MEASURE', 'FREQUENCY', 'Flag Codes'], axis=1) #Removing unwanted Columns
print(housing_Data.columns) # Just to test if working
user_Country = str(input("What Country are you in")) # User Input

def getCountry(): # Function to compare user input to elements inside the list
    if user_Country in housing_Data.LOCATION.unique():
        print(user_Country)
    else:
        print("Sorry we don't have information about that country")

getCountry()

A: maybe what you want is all rows matching a location?
matching_rows = housing_Data[housing_Data.LOCATION == user_country]
print(matching_rows)

maybe? Im not entirely sure.

A: In case you are urgent , you can append the iteration list from the source to a newfile.txt and do a comfortable iteration. hopefully it helps.


text:
Q: IBM Watson Personality Insights: Use raw or percentile scores? I am using IBM Watson Personality Insights in the context of an academic research project.
From the analyses so far, I noticed that often there are large differences between the raw and percentile scores for the same tweets and in several cases the scores are even on opposite ends (e.g., agreeableness raw score: 0.21 and agreeableness percentile score 0.76). Moreover, on aggregate level for my sample population, the variance within the personality traits is much higher for percentile scores and very low for raw scores (all observations within a range of 0.1-0.2 per trait).
I understand that the percentiles are normalized scores and the interpretations of the scores are different. My question is which score is typically used by reseachers that aim to apply them in regression analysis (e.g., individual's personality traits - success)? In the papers I have seen that apply Personality Insights, the author's do not discuss which score they use. It would be great if you have some thoughts on this and could share any research that discusses their approach with Personality Insights in more detail.
Thanks a lot in advance for your guidance!

A: You are correct that the scores have different interpretations. The raw scores are exactly that, where as the normalized score is over a larger population. While the ranges for a trait's raw scores are from 0 - 1 in practice this isn't always the case, and the scores may be concentrated in a narrower band. This is why in the example you show above, a small change in the raw score can have a lot bigger change in the percentile score.
Note that to calculate the percentiles we ran the profiles for a larger population (100Ks) where you'd observe these trends that may not show in a smaller sample.
As for your other question; which score you'd use very much depends. In general, most use the percentile score as that gives you an idea how a given group of people compares with the population at large. For instance, if I'm interested to see how one group compares to another, using the percentile scores makes it easier to intuitively understand the differences (an agreeableness difference of 25% is easier is a lot easier to understand than a raw difference of 0.1 as you won't know whether that is significant or not).
On the other hand, the raw scores are used mostly when the you are creating a larger model and are using the PI score as 1 of the features. In that case it is typically helpful to use the raw scores as you'd draw your own conclusions from the larger model.


text:
Q: Calling HTTPS API from Angular deployed in http server I am calling HTTPS API from Angular service deployed in http server by the following code.
this.chatbotUrl = "https://something.com/api";
getDashBoardData(): Observable<any> {
    return this.http.get<IContainer>(this.chatbotUrl+"/chatbot/get-dashboard-data").pipe(
      map((response) => (response ? response : {})),
      catchError( this.handleError )
    );
  }

But when I am calling this API, then I am getting this error, "Http failure response for https://something.com/api/chatbot/get-dashboard-data: 0 Unknown Error". The following error is also get.
GET https://something.com/api/chatbot/get-time-wise-traffic/7 net::ERR_CERT_COMMON_NAME_INVALID

How can I call https API from Angular service deployed in http server?

A: I suppose you have not configured the API properly,check whether the site requires any key to get accessed.Here I have provided the component.ts file and service file for the API I am working with for your reference.
If CORS error try adding CORS extension to your browser;else clear your cache and run your code again.
Component.ts:
import { Component, OnInit } from '@angular/core';
import { DomSanitizer } from '@angular/platform-browser';
import { YoutubeService } from '../youtube.service';

@Component({
  selector: 'app-home',
  templateUrl: './home.component.html',
  styleUrls: ['./home.component.css']
})
export class HomeComponent implements OnInit {
  Name:any;
  details: any;
  info:any;
  display!:boolean;

  constructor(private service:YoutubeService,public sanitizer: DomSanitizer) { }

  ngOnInit(): void {
    this.service.GetVideos().subscribe((res:any)=> {
      this.info= res as any
      this.info=this.info.items;
      console.log(this.info);
      this.display=true
    });

  }
  onSubmit() {
    this.service.GetSearch(this.Name).subscribe(res=> {
        this.details= res as any
        this.details=this.details.items;
        // this.details.forEach((function.this.details.i) => {
        //    ele
        // });
        console.log(this.details);
        this.display=true
      });

  }

}

Service:
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { GoogleLoginProvider } from 'angularx-social-login';

@Injectable({
  providedIn: 'root'
})
export class YoutubeService {
  private APIURL = "https://youtube.googleapis.com/youtube/v3/";
  private APIKEY ="AIzaSyB40HaKwd0VggftBq8R9sEwQx_NG5xOOWc";

  constructor(private http:HttpClient) { }
  public GetSearch(name:string)
  {
    console.log(name)
    return this.http.get(this.APIURL+"search?part=snippet&key="+this.APIKEY+"&q="+name+"&type=video");
  }


text:
Q: merge multiple nodes with the same relationship anybody can help me with
MATCH(n:Customer)-[r:ORDERS]->(o:Order)<-[r1:ORDERS]-(n1:Customer)
WITH COLLECT(n)+COLLECT(n1) as nodes
CALL apoc.refactor.mergeNodes(nodes,{mergeRels:true}) YIELD node
RETURN node

I actually want to combine n and n1 because let's say n has "name" property and n2 has "email" property. I tried the code above and it says: "Neo.ClientError.Schema.ConstraintValidationFailed" with explanation: "Cannot delete node<1397>, because it still has relationships. To delete this node, you must first delete its relationships."
I've found the solution:
//SOLUTION
MATCH(n:Customer)-[r:ORDERS]->(o:Order)<-[r1:ORDERS]-(n1:Customer)
WITH o.order_id as i, HEAD(COLLECT([n,n1])) AS nodes
CALL apoc.refactor.mergeNodes(nodes, {mergeRels:true})
YIELD node
RETURN node

it works perfectly to all nodes referred as n and n1

A: Instead of collect(n) + collect(n1), use head(collect[n, n1])).  Also, you should include combine properties in your parameter.
OLD:
MATCH(n:Customer)-[r:ORDERS]->(o:Order)<-[r1:ORDERS]-(n1:Customer)
WITH COLLECT(n)+COLLECT(n1) as nodes
CALL apoc.refactor.mergeNodes(nodes,{mergeRels:true}) YIELD node
RETURN node

New:
MATCH(n:Customer)-[r:ORDERS]->(o:Order)<-[r1:ORDERS]-(n1:Customer)
WITH head(collect([n,n1])) as nodes
CALL apoc.refactor.mergeNodes(nodes,{properties:"combine",mergeRels:true}) YIELD node
RETURN node

I'm using neo4j version 4.2.4 and below is my sample test data;
CREATE (c1:Customer {name: "Charlize Theron"})
CREATE (c2:Customer {email: "char@theron.com"})
CREATE (o:Order {ID: 1234})
MERGE  (c1)-[:ORDERS]->(o)
MERGE  (c2)-[:ORDERS]->(o)
MERGE  (c2)-[:LIKES]->(o)

Reference: https://neo4j.com/labs/apoc/4.2/graph-updates/graph-refactoring/merge-nodes/


text:
Q: How can I create my own dot operator function for a string? I'm a student. Let's say I want to be able to do my_string.reverse();. I don't want to see the actual code to reverse a string, I just want to see how this function would be implemented for strings.
A side question: why have I never seen this dot operator used with types such as int or char, is that simply not possible?

A: You can't overload the member access operator; and you can't add members to an already defined class. If the type of my_string doesn't have a reverse member, and you can't (or don't want to) add one to the class definition, then you simply can't do anything to provide that syntax.
If you want to write a function to manipulate a class without changing the class definition, it will have to be a non-member function, called as e.g. reverse(my_string).

why have I never seen this dot operator used with types such as int or char, is that simply not possible?

No it isn't. The language only defines that operator for class types, and doesn't allow it to be overloaded.


text:
Q: passing a reference to useState to an object outside the React component In an attempt to implement the MVVM pattern in react I've come up with the following solution.
A Viewmodel which calls a notify method whenever it's state has changed.
class Viewmodel{
 value:number;
 notify:()=>void;
 constructor(notify:()=>void){
  this.notify = notify;
  this.value = 0;
 }

 update(){
  this.value = this.value + 1;
  this.notify();
 }
}

A component which relies on Props. Nothing different here
interface MyComponentProps{
 value:number;
}
function MyComponent(props:MyComponentProps):JSX.Element{
 return (<div>{props.value}</div>)
}

A component which uses useState to create the viewmodel object, and also uses useState to create the required notify method to be passed to the viewmodel.
function MyParentComponent(){
const notify = ()=> setProps({value:vm.value});
const [vm] = useState<Viewmodel>(new Viewmodel(notify));
const [props, setProps] = useState<MyComponentProps>({value:0});
return <MyComponent {...props} />
}

When the Viewmodels update method is called, it changes it's internal state then calls notify() which in turn executes useState and updates the Component. This all works the way I wish however I'm left wondering if this can lead to some subtle bugs. Is passing the setState method to the Viewmodel class in some way dangerous?


text:
Q: Permutations / Probability sitting around a table James and his 5 friends(Kyle,Tom,Bob,Michael,John) are about to sit around a round table there are 6 sits at the table.
What is the probability James will sit between Bob and Michael ?
My solution
A= number of ways James can sit between Bob and Michael
B= total number of ways they can sit
As James, Bob and Michael technically sit next together we can consider them as single unit
A=4!* 2! The 2! Is the number of ways Bob and Michael can swap.
B= Total number of ways the can all sit is (n-1)!
I.e 5!
P= A//B
Which is 2/5

A: That is not the right answer. Instead break the circle at James so the remaining five people form a line; there are $2\cdot3!$ seating arrangements out of $5!$ where Bob and Michael sit at the line's ends, and hence next to James in the full circle (the other three people may be permuted arbitrarily). Thus the answer is $\frac{2\cdot3!}{5!}=\frac1{10}$.

A: By convention, in a circular permutation,  only the relative order of the objects matters.
Seat James.  We will use him as our reference point.  Relative to James, there are indeed $5!$ ways to arrange his friends around the table as we proceed clockwise around the table from James.
For the favorable cases, once James is seated, there are $2$ ways to arrange Bob and Michael next to James.  That leaves three seats for Kyle, Tom, and John.  They can be seated in those three seats in $3!$ ways as we proceed clockwise around the table from James.  Hence, the number of favorable cases is $2 \cdot 3!$.
Therefore, the probability that James will sit between Bob and Michael if the six people are seated randomly around the table is
$$\frac{2 \cdot 3!}{5!}$$
In your attempt, you forgot to use a reference point for the favorable cases.

A: I am assuming that you mean that the three people are ordered [Bob, James, Michael] or [Michael, James, Bob].
You can express the probability as
$$\frac{N}{D},$$
where $D = (5!)$.
That is, since the table is round, you can arbitrarily designate anyone as the head of the table (i.e. the twelve-o'clock position).  Then you will have $(5)$ remaining people to permute.
So, based on the above discussion, the problem reduces to computing $N$.
Think of the $(3)$ people, Michael, James, Bob, as forming one fused unit.  Then, in effect, you have $(4)$ units to permute around the table.  Namely, the fused unit and the other $(3)$ units.
Since the table is round, this can be done in $(4-1)!$ ways.
Further, the fused unit permits $(2!)$ internal permutations of the three people inside the unit, since James must be in the middle.
Putting this all together, the probability is
$$\frac{[(4-1)!] \times 2!}{(6-1)!}.$$
An alternative way of computing $N$ is to arbitrarily decide that James will go in the twelve-o'clock position.  Then, Bob, Micheal can be permuted in $(2)!$ ways around James, and then the $(3)$ remaining people can be permuted in $(3!)$ ways in the three remaining seats.


text:
Q: JavaScriptResult in asp.net mvc RC1 Why do you need JavaScriptResult as a response?
Doesn't it break the pattern of clean separation of concerns? Can you suggest me some cases where this will be useful?

A: The sole purpose of JavaScriptResult is to set the ContentType to application/x-javascript.
You might want to use this if you have an action which returns a .JS file to the browser. For example, you could write an action which concatenates all of your JavaScript files together, so that you could return them in one request instead of many. You might also want to generate JavaScript from a template.
I have seen some blog posts implying that JavaScriptResult will cause the returned file to be executed within the context of the current page. This impression apparently comes from the release notes. But I can't see any mechanism by which that would actually happen in the source code. In other words, in order to get this behavior, you would have to write code within the page causing it to happen. Simply using JavaScriptResult will not have this effect. As far as I can tell, it is simply serving up a js file.


text:
Q: Referencing an HTML button to Python Script My objective in this program is to store information in a database. My problem is that I'm trying to link a button from my HTML page by using a Python script. My instructor told us that it must be written in Python. Any Libraries that support Python 2.7 would work for me.
from google.appengine.api import images
from google.appengine.ext import ndb
from models import Note
import webapp2

import jinja2
import os

jinja_env = jinja2.Environment(
    loader=jinja2.FileSystemLoader(os.path.dirname(__file__)))

class MainHandler(webapp2.RequestHandler):
    def get(self):
        template = jinja_env.get_template('./main.html')
        self.response.out.write(template.render())

class InfoHandler(webapp2.RequestHandler):
    def get(self):
        note = Note(img = images.Image(photo.usr_img))

class Note(ndb.Model):
    def get(self):
        usr_img = ndb.BlobProperty()
        desc = ndb.StringProperty()

app = webapp2.WSGIApplication([
    ('/', MainHandler),
], debug=True)

        <meta charset = "UTF-8">
        <title>Title</title>

If this is an emergency, upload a photo and provide a short description.

                        Upload image:
                        <input type = "file" name = "pic" accept = "image/*"/>
                        Description:
                        <input type = "text" />
                        <input type = "submit" href = "{{ submit_data }}"/>

I'm a noob in Python and I'm taking on a tough problem for class. Any suggestions or solutions?


text:
Q: Why clicking on my button don't alert range selected? I' ve a button, so when user clicks it, it should alert range selected. If user didn't change the range selected (slider) default value 1 should be alerted.
Why is not alerting it?
Codepen:
https://codepen.io/ogonzales/pen/abNQXLg
Error: it should only alert 1 value:

JS:
 $('#step_one_siguiente').on('click', function () {
        let val = this.value;
        alert($("#performance_options").prop("selected", true).text());
    });

A: Here is a workaround that might be helpful.
let ranges = ['1080p','1440p','2k']

$('#step_one_siguiente').on('click', function () {
        var index = parseInt($('input').val()) - 1
        alert(ranges[index]);
    });

A: I think it is because the way you use the syntax of the datalist is incorrect.
Values are not meant to be between the option tags but only in the value="" attribute.
However for this to work, the input value would need to match the list value, which is not compatible with a range control as the values you want are not a sequence.
https://www.w3schools.com/tags/tag_datalist.asp

A: Based on Ibrahim question, I was able to come up with:
Apparently I don't have to search for a selected range, as it only returns the value of the selected one.
<script>

    $('#step_one_siguiente').on('click', function () {
        alert($('[type="range"]').val());
    });
</script>


text:
Q: Can Anthill Beanshell script make a HTTP connection? I use Anthill Pro for build and deployment management. I'm attempting to configure Anthill to make a HTTP POST or GET to a web server after a deployment has completed. I'm passing basic information regarding the deployment to a web application.
It looks like writing a Beanshell script is the way to do this in Anthill (I'm open to suggestions), but the documentation does not seem to offer an obvious way to do this.
Can a Beanshell script from Anthill make a HTTP connection to accomplish this, or is there a better way?
Example of the connection I'm trying to make:
http://myServer/myScript/?param1=deployValue1&param2=deployValue2

Any help is appreciated.

A: Are you just trying to hit a URL and validate that some text on it is there? If so we have a plugin baking that does this sort of thing. Shoot me a mail at eric@urbancode.com (or file a support ticket) and we can get that over to you.


text:
Q: datastore entity with more than one unique key This question has already been asked. But my present situation is a bit different, and I am hoping there are now better answers. So here goes:
I need a datastore entity to have two unique keys, one being the primary key.
Will the following suffice? I need that when I make a keys only query for the datastore to understand that I am referring to keyA
@Entity
public class UserAccount implements Serializable{

  @Id
  @GeneratedValue(strategy=GenericType.IDENTITY)
  Key keyA;//based on email

  @PrimaryKey
  @Persistent(valueStrategy = IdGeneratorStrategy.IDENTITY)
  Key keyB;//randomly generated
  //….other data
}

I need the datastore to help enforce the uniqueness of the keys so it is not enough to let keyB be a simple field that I manage myself.

A: You'll have to enforce uniqueness yourself.  That is on the non-primary key you'll have to do a look up and see if you get a result.


text:
Q: AHB Bus : Implementing a narrow slave on a wide bus I see this image in ARM's AHB spec. This is basically an example of how we can use the AHB fabric to connect with narrower slave.
Here I am not able to understand the usage of haddr[2] as a mux select. How will this bit help us in figuring out if we need to select upper or lower half of the data bus.
Please help me in understanding this .

A: Define: Quadword=QW=a 64-bit word.
Define: Dword=DW=a 32-bit word.
Define: Byte= an 8-bit word.

The address bus HADDR[] refers to bytes.
Address 0 refers to byte 0, address 1 refers to byte 1, ...
The memory is 64-bit, therefore the 3 least significant bits of the address have no meaning to a 64-bit wide memory.
Any address from 0-7 will produce the first QW from the memory.
Any address from 8-15 will produce the 2nd QW from the memory.
...
Example of how to read out the memory to facilitate the conversion from 64->32-bit.
First, drive the memory with address 0 during the first clock cycle,  the memory will present the first QW, address[2] will be 0 so the low DW (data[31:0]) of the first QW will get selected by the mux.
Second, drive the memory with address 4 during the second clock cycle,  the memory will continue to present the first QW, address[2] will be 1 so the high DW (data[63:32]) of the first QW will get selected by the mux.
Third, drive the memory with address 8 during the third clock cycle,  the memory will present the second QW, address[2] will be 0 so the low DW (data[31:0]) of the second QW will get selected by the mux.
Repeat the pattern incrementing the address by 4 each clock to read the 64 bit memory and convert to 32-bit using the circuit shown.


text:
Q: database access from a jar inside ear In an ear-file I have a persistence-unit for managing entities inside that ear which works fine. Additionally, there is a commons jar-file located in APP-INF/lib which is a dependency in other ears as well (other ear-modules on the same level). In this commons-jar I would like to have a single entity and create the possibility for CRUD on that entity. Now it is a jar only with an additional persistence unit (but same db as for the ear) and I can't manage to set it all up. Would that persistence unit be managed as well by the container? Could I use EJBs inside that jar file as well? Is it possible at all to do what I want?
I created the entity as follows
@Entity
public class ConfigEntity {

  @Id
  private Long id;
  @Version
  private Long version;

  [further fields, getters and setters omitted]

}

With the following "Dao" I try to call isEntityManagerNull from a bean inside the ear.
public class ConfigBEDao {

  @PersistenceContext(unitName = "configurationPU")
  EntityManager entityManager;

  public boolean isEntityManagerNull() {
    return entityManager == null;
  }

}

persistence.xml
<?xml version="1.0" encoding="UTF-8"?>
<persistence xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
             xmlns="http://xmlns.jcp.org/xml/ns/persistence"
             xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence http://xmlns.jcp.org/xml/ns/persistence/persistence_2_1.xsd"
             version="2.1">

    <persistence-unit name="configurationPU" transaction-type="RESOURCE_LOCAL">
        <description/>
        <provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>
        <jta-data-source>jdbc/db</jta-data-source>
        <properties>
            <property name="eclipselink.target-database" value="${database.dialect}"/>
            <property name="eclipselink.logging.level" value="FINE"/>
            <property name="eclipselink.logging.parameters" value="true"/>
            <property name="eclipselink.cache.shared.default" value="false"/>
        </properties>
    </persistence-unit>
</persistence>

From a bean inside the ear file I call
ConfigBEDao dao = new ConfigBEDao();
dao.isEntityManagerNull();

which gives me the following exception already when trying to deploy on the server (payara):
java.lang.RuntimeException: Could not resolve a persistence unit corresponding to the persistence-context-ref-name [ConfigBEDao/entityManager] in the scope of the module called [main_ear-1.0-SNAPSHOT#main_ejb-1.0-SNAPSHOT.jar]. Please verify your application.
    at com.sun.enterprise.deployment.BundleDescriptor.findReferencedPUViaEMRef(BundleDescriptor.java:733)
    at org.glassfish.ejb.deployment.descriptor.EjbBundleDescriptorImpl.findReferencedPUs(EjbBundleDescriptorImpl.java:889)
    at org.glassfish.persistence.jpa.JPADeployer.createEMFs(JPADeployer.java:186)
    at org.glassfish.persistence.jpa.JPADeployer.prepare(JPADeployer.java:168)

Then I changed the persistence.xml as follows but that didn't work either although the application can be deployed:
<?xml version="1.0" encoding="UTF-8"?>
<persistence xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
             xmlns="http://xmlns.jcp.org/xml/ns/persistence"
             xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence http://xmlns.jcp.org/xml/ns/persistence/persistence_2_1.xsd"
             version="2.1">

    <persistence-unit name="configurationPU" transaction-type="RESOURCE_LOCAL">
        <description/>
        <provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>
        <properties>
            <property name="javax.persistence.jdbc.url" value="jdbc:postgresql://localhost:5432/db"/>
            <property name="javax.persistence.jdbc.user" value="db"/>
            <property name="javax.persistence.jdbc.password" value="secret"/>
            <property name="javax.persistence.jdbc.driver" value="org.postgresql.Driver"/>
        </properties>
    </persistence-unit>
</persistence>

which gave me
javax.persistence.PersistenceException: No Persistence provider for EntityManager named configurationPU
    at javax.persistence.Persistence.createEntityManagerFactory(Persistence.java:85)
    at javax.persistence.Persistence.createEntityManagerFactory(Persistence.java:54)


text:
Q: Deployment of new version of Flink application failed
*

*env

*

*flink 1.7.1

*kafka 1.0.1

I use Flink application in Streaming process.
Read topic from kafka and sink it to kafka new Topic.
When i change application with new version of code and deploy, it comes to application execution failure.
If i deploy the same group.id after changing the application code, could there be a conflict with previous state checkpoint information?

A: Yes, if you are trying to do a stateful upgrade of your Flink application, there are a few things that can cause it to fail.
The UIDs of the stateful operators are used to find the state for each operator. If you haven't set the UIDs, then if the job's topology has changed, state restore will fail because Flink won't be able to find the state. See the docs on Assigning Operator IDs for details.
If you have dropped a stateful operator, then you should run the new job while specifying -allowNonRestoredState.
If you have modified your data types, the job can fail when attempting to deserialize the state in the checkpoint or savepoint. Flink 1.7 did not have any support for automatic schema evolution or state migration. In more recent versions of Flink, if you stick to POJOs or Avro, this is handled automatically. Otherwise you need custom serializers.
If this doesn't help you figure out what's going wrong, please share the information from the logs showing the specific exception.


text:
Q: firebase realtime DB getting key of matched object My firebase realtime DB is structured like:
{
 "users" : {
    "P55dsK5xQaM3FhnsCcI5Oxnyi7v1" : {
      "email" : "myemail@gmail.com",
      "isAdmin" : true,
      "name" : "Vik Kumar"
    }
  }
}

I am using angularfire2 to query data like below
getUserByEmail(email:string){
    console.log("start of getUserByEmail with email:" + email)
    return new Promise((resolve, reject) =>
      {

        this.db.list("/users",
          ref => ref.orderByChild('email').startAt(email)
        ).valueChanges().subscribe(
          res => {
            console.log('response:' + JSON.stringify(res))
            resolve(res)
          },
          err => {
            console.log(err)
            reject(err)
          }
        )
      })
  }

This works as expected. However, i need the id of this node "P55dsK5xQaM3FhnsCcI5Oxnyi7v1" as well to do some operations. How do i get that?
My Business Use Case
The users get added to note users node as they sign up. The above requirement came where an admin user want to update user data. So, he searches the user via his email and then update it.
So the above code is used to search users by email. Now, to be able to update i need to get the node id.

A: I'm not sure why you're using AngularFire here. With the regular Firebase SDK for JavaScript, you can do this with:
getUserByEmail(email:string){
  console.log("start of getUserByEmail with email:" + email)
  return new Promise((resolve, reject) =>{
    firebase.database()
      .ref("/users")
      .orderByChild('email')
      .startAt(email)
      .once('child_added')
      .then(snapshot => {
        resolve(snapshot.key);
      })
      .catch(err => {
        console.log(err)
        reject(err)
      })
  });
}

By listening for once('child_added' we're getting a snapshot that only contains the first child node matching the query.

Note that the search now will match any user after the email, while I have a feeling you want to only find users starting with the value of email. In that case you'll want to add an endAt() clause too:
firebase.database()
  .ref("/users")
  .orderByChild('email')
  .startAt(email)
  .endAt(email+'\uF7FF')
  .once('child_added')

A: You can try like that
this.itemsRef = db.list('users');
this.itemsRef.snapshotChanges(['child_added'])
  .subscribe(actions => {
    actions.forEach(action => {
      console.log(action.type);
      console.log(action.key);
      console.log(action.payload.val());
    });
  });

A: So, actually i could do it using angularfire2 by replacing valueChanges to snapshotchanges as below
 getUserByEmail(email:string){
    console.log("start of getUserByEmail with email:" + email)
    return new Promise((resolve, reject) =>
      {
        this.db.list("/users",
          ref => ref.orderByChild('email').startAt(email)
        ).snapshotChanges().subscribe(
          (res:any) => {
            console.log("resp length:" + res.length)
            //console.log('response:' + JSON.stringify(res))
            //console.log('key is::' + res.key())
            resolve(res)
          },
          err => {
            console.log(err)
            reject(err)
          }
        )
      })
  }

now res.key gives me key and res.payload.val() the data object.


text:
Q: How do I convert between a measure of similarity and a measure of difference (distance)? Is there a general way to convert between a measure of similarity and a measure of distance?
Consider a similarity measure like the number of 2-grams that two strings have in common.
2-grams('beta', 'delta') = 1
2-grams('apple', 'dappled') = 4

What if I need to feed this to an optimization algorithm that expects a measure of difference, like Levenshtein distance?
This is just an example...I'm looking for a general solution, if one exists.  Like how to go from Levenshtein distance to a measure of similarity?
I appreciate any guidance you may offer.

A: If your similarity measure (s) is between 0 and 1, you can use one of these:
1-s
sqrt(1-s)
-log(s)
(1/s)-1

A: Doing 1/similarity is not going to keep the properties of the distribution.
the best way is
distance (a->b) = highest similarity - similarity (a->b).
with highest similarity being the similarity with the biggest value. You hence flip your distribution.
the highest similarity becomes 0 etc

A: Yes, there is a most general way to change between similarity and distance: a strictly monotone decreasing function f(x).
That is, with f(x) you can make similarity = f(distance) or distance = f(similarity). It works in both directions. Such function works, because the relation between similarity and distance is that one decreases when the other increases.
Examples:
These are some well-known strictly monotone decreasing candidates that work for non-negative similarities or distances:

*

*f(x) = 1 / (a + x)

*f(x) = exp(- x^a)

*f(x) = arccot(ax)
You can choose parameter a>0 (e.g., a=1)

Edit 2021-08

A very practical approach is to use the function sim2diss belonging to the  statistical software R. This functions provides a up to 13 methods to compute dissimilarity from similarities. Sadly the methods are not at all explained: you have to look into the code :-\

A: Let d denotes distance, s denotes similarity. To convert distance measure to similarity measure, we need to first normalize d to [0 1], by using d_norm = d/max(d). Then the similarity measure is given by:
s = 1 - d_norm.
where s is in the range [0 1], with 1 denotes highest similarity (the items in comparison are identical), and 0 denotes lowest similarity (largest distance).

A: similarity = 1/difference

and watch out for difference = 0

A: According to scikit learn:
Kernels are measures of similarity, i.e. s(a, b) > s(a, c) if objects a and b are considered "more similar" than objects a and c. A kernel must also be positive semi-definite.
There are a number of ways to convert between a distance metric and a similarity measure, such as a kernel. Let D be the distance, and S be the kernel:

*

*S = np.exp(-D * gamma), where one heuristic for choosing gamma is 1 /
num_features

*S = 1. / (D / np.max(D))

A: In the case of Levenshtein distance, you could increase the sim score by 1 for every time the sequences match; that is, 1 for every time you didn't need a deletion, insertion or substitution. That way the metric would be a linear measure of how many characters the two strings have in common.

A: In one of my projects (based on Collaborative Filtering) I had to convert between correlation (cosine between vectors) which was from -1 to 1 (closer 1 is more similar, closer to -1 is more diverse) to normalized distance (close to 0 the distance is smaller and if it's close to 1 the distance is bigger)
In this case: distance ~ diversity
My formula was: dist = 1 - (cor + 1)/2
If you have similarity to diversity and the domain is [0,1] in both cases the simlest way is:
dist = 1 - sim
sim = 1 - dist

A: Cosine similarity is  widely used  for n-gram count or TFIDF vectors.
from math import pi, acos
def similarity(x, y):
    return sum(x[k] * y[k] for k in x if k in y) / sum(v**2 for v in x.values())**.5 / sum(v**2 for v in y.values())**.5

Cosine similarity can be used to compute a formal distance metric according to wikipedia. It obeys all the properties of a distance that you would expect (symmetry, nonnegativity, etc):
def distance_metric(x, y):
    return 1 - 2 * acos(similarity(x, y)) / pi

Both of these metrics range between 0 and 1.
If you have a tokenizer that produces N-grams from a string you could use these metrics like this:
>>> import Tokenizer
>>> tokenizer = Tokenizer(ngrams=2, lower=True, nonwords_set=set(['hello', 'and']))

>>> from Collections import Counter
>>> list(tokenizer('Hello World again and again?'))
['world', 'again', 'again', 'world again', 'again again']
>>> Counter(tokenizer('Hello World again and again?'))
Counter({'again': 2, 'world': 1, 'again again': 1, 'world again': 1})
>>> x = _
>>> Counter(tokenizer('Hi world once again.'))
Counter({'again': 1, 'world once': 1, 'hi': 1, 'once again': 1, 'world': 1, 'hi world': 1, 'once': 1})
>>> y = _
>>> sum(x[k]*y[k] for k in x if k in y) / sum(v**2 for v in x.values())**.5 / sum(v**2 for v in y.values())**.5
0.42857142857142855
>>> distance_metric(x, y)
0.28196592805724774

I found the elegant inner product of Counter in this SO answer


text:
Q: How to Check if Column is NULL Instead of Empty Using PHP and MSSQL I have PHP Code that is supposed to display the image name that is saved into my MSSQL table's row column photo. Some rows have the photo column set to NULL while some have the data 02.jpg in the photo column. If i use the code below, 02.jpg does not show up because it starts with zero. I am looking to find a way to check if the column is set to NULL rather than empty, because empty is not allowing some image names.
Here is the PHP code:
$picature2 = "SELECT photo1 FROM used_trailers1 WHERE orderid = $sn";
$query1=mssql_query($picature2, $conn);
$array1=mssql_fetch_assoc($query1);
$picature2=stripslashes($array1['photo1']);

if (empty($picature2['photo1'])){
    $picature2= "No Image";
} else {
    $picature2=stripslashes($array1['photo1']);
}

The code above correctly displays the "No Image" if the photo column is set to NULL, but if the photo column is 02lady.jpg then it will not work because it starts with a zero.
Here is what I tried:
if (IS_NULL($picature2['photo1'])){

So far that does not work and does not display the "No Image" if the column data for photo is NULL.
Thanks for any help. All help is greatly appreciated.

A: Update
  if ($picature2['photo1']===null || ctype_space($picature2['photo1'])){
    $picature2= "No Image";
    }

     else {
        $picature2=stripslashes($array1['photo1']);
    }

A: You can use php is_null() function http://us2.php.net/manual/en/function.is-null.php

A: You have the following
$picature2=stripslashes($array1['photo1']);
if (empty($picature2['photo1'])){

which assigns photo1 to $picature2 then you check $picature2['photo1'] which $picature2 isn't a array.
You should use the following
#$picature2=stripslashes($array1['photo1']);
#remove this because if you have NULL and use stripslashes it turns into ""
if($array1['photo1'] === NULL){
    $picature2 = "No Image";
}else{
    $picature2 = stripslashes($array1['photo1']);
}


text:
Q: Shared text iPhone and iPad I need to share text on iPhone and iPad. My code works for iPhone but does not work for iPad.
I am using a static function to call from trailingSwipeActionsConfigurationForRowAt options of my tableView:
static func dialogCompartir(titulo: String, descripcion: String, view: UIViewController, url: String) -> Void {
    // Set the link to share.
    if let link = NSURL(string: url) {
        let objectsToShare = [descripcion,link] as [Any]
        let activityVC = UIActivityViewController(activityItems: objectsToShare, applicationActivities: nil)

        if UIDevice.current.userInterfaceIdiom == .pad {
            print("ipad")
            view.present(activityVC, animated: true, completion: nil)
            if let popOver = activityVC.popoverPresentationController {
                popOver.sourceView =  view.view
              //popOver.sourceRect =
              //popOver.barButtonItem
            }
        } else if UIDevice.current.userInterfaceIdiom == .phone {
            print("iphone")
            view.present(activityVC, animated: true, completion: nil)
        }
    }
}

iPad error:
[LayoutConstraints] Unable to simultaneously satisfy constraints.
    Probably at least one of the constraints in the following list is one you don't want.
    Try this:
        (1) look at each constraint and try to figure out which you don't expect;
        (2) find the code that added the unwanted constraint or constraints and fix it.
(
    "<NSLayoutConstraint:0x60000188f890 LPLinkView:0x7fdd2a70d200.leading == UILayoutGuide:0x6000002ac0e0'UIViewLayoutMarginsGuide'.leading   (active)>",
    "<NSLayoutConstraint:0x600001889d10 H:[LPLinkView:0x7fdd2a70d200]-(59)-|   (active, names: '|':_UIActivityContentTitleView:0x7fdd2a70cde0 )>",
    "<NSLayoutConstraint:0x6000018e50e0 H:|-(0)-[_UIActivityContentTitleView:0x7fdd2a70cde0]   (active, names: '|':_UINavigationBarContentView:0x7fdd27dae070 )>",
    "<NSLayoutConstraint:0x6000018e5590 _UIActivityContentTitleView:0x7fdd2a70cde0.trailing == _UINavigationBarContentView:0x7fdd27dae070.trailing   (active)>",
    "<NSLayoutConstraint:0x600001893520 'UIView-Encapsulated-Layout-Width' _UINavigationBarContentView:0x7fdd27dae070.width == 0   (active)>",
    "<NSLayoutConstraint:0x60000188f840 'UIView-leftMargin-guide-constraint' H:|-(16)-[UILayoutGuide:0x6000002ac0e0'UIViewLayoutMarginsGuide'](LTR)   (active, names: '|':_UIActivityContentTitleView:0x7fdd2a70cde0 )>"
)

Will attempt to recover by breaking constraint
<NSLayoutConstraint:0x60000188f890 LPLinkView:0x7fdd2a70d200.leading == UILayoutGuide:0x6000002ac0e0'UIViewLayoutMarginsGuide'.leading   (active)>

Make a symbolic breakpoint at UIViewAlertForUnsatisfiableConstraints to catch this in the debugger.
The methods in the UIConstraintBasedLayoutDebugging category on UIView listed in <UIKitCore/UIView.h> may also be helpful.

How can I solve this problem of sharing text on iPad for Xcode 11, iOS 13?
My TableViewController has no constraint warnings.

A: This has worked for me in iPad, xcode11, ios13:
        if UIDevice.current.userInterfaceIdiom == .phone{
            print("===== iPhone")
            view.present(activityVC, animated: true, completion: nil)

        }else if UIDevice.current.userInterfaceIdiom == .pad{
            print("===== iPad")
            view.present(activityVC, animated: true, completion: nil)

            if let popOver = activityVC.popoverPresentationController {
                popOver.sourceView = view.tableView
                popOver.sourceRect = view.tableView.rectForRow(at: indexPath)
                popOver.permittedArrowDirections = UIPopoverArrowDirection.any

            }

        }

Greetings

A: Provide source rect to popOver
popOver.sourceRect = CGRect(x: 0, y: 0, width: 100, height: 100) // You can use your sender rect here

The default value in iOS 13.2 is CGRectNull. Prior to iOS 13.2, the default value was CGRectZero.


text:
Q: Modificar formato de Excel exportado por GridView Estoy haciendo un proyecto en el cual cargo datos a mi GridView (Datos Insertados) desde mi Base de Datos.
Exporto mi GV en un Excel con este código:
private void ExportarGridExcel()
{
   int num = 0;
   Response.Clear();
   Response.Buffer = true;
   Response.ClearContent();
   Response.ClearHeaders();
   Response.Charset = "";
   lblcantidad.Text = num.ToString();
   string FileName = "Usuarios y Contraseñas" + DateTime.Now + ".xls";
   StringWriter strwritter = new StringWriter();
   HtmlTextWriter htmltextwrtter = new HtmlTextWriter(strwritter);
   Response.Cache.SetCacheability(HttpCacheability.NoCache);
   Response.ContentType = "application/vnd.ms-excel";
   Response.AddHeader("Content-Disposition", "attachment;filename=" + FileName);
   GrillaDatosInsertados.GridLines = GridLines.Both;
   GrillaDatosInsertados.HeaderStyle.Font.Bold = true;
   GrillaDatosInsertados.RenderControl(htmltextwrtter);
   Response.Write(strwritter.ToString());
   Response.End();
}

protected void Button2_Click3(object sender, EventArgs e)
{
  ExportarGridExcel();
}

Esta es la interfaz:

Al presionar el boton, se exporta el gridview.
Lo que quiero hacer es darle formato texto a todas las celdas, ya que el campo contraseña obtiene números, y algunos tienen 0 al inicio, excel reconoce como si fuera un campo numero, y le borra ese 0

A: Bueno encontré la solución en otro sitio de Google. Se las comparto por si alguien la llega a necesitar.
Inserté este codigo en el evento RowDataBound
protected void GrillaDatosInsertados_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            e.Row.Attributes.Add("style", "vnd.ms-excel.numberformat:@");
            e.Row.Cells[0].Attributes.Add("style", "vnd.ms-excel.numberformat:@");
        }
    }

Hace que todas las filas del Gridview tengan formato de texto.


text:
Q: MiKTeX | Problem with the oberdiek Package I tried using \centernot, after reading that it uses the oberdiek package.
I went to MikTeX to ensure that it's installed, and found it, yet after right-clicking it, my operation system, Windows (10, 64-bit, MikTex is running on 32-bit), didn't tell me any information from which I can infer whether the package is installed or not - if it's installed, I can't uninstall it, and if it's not installed, I can't install it.
So, I don't know if I even have it not.
I'm using LyX, and it doesn't find it - when I include it in the Premables with `\usepackage{oberdiek}.
If it is not installed, why can't install it?
I can't use the package, and I don't know how to get it, if I don't have it.
Help would be much appreciated.

A: As Ulrike Fischer already mentioned in her comment, oberdiek is a bundle of packages that the person Heiko Oberdiek provides.
This is clear if you follow the link which leads to the following page:

So you cannot use something like \usepackage{oberdiek} but you can load one of the many packages that Heiko Oberdiek provides such as \usepackage{centernot}.
You can install and uninstall the bundle of package in MiKTeX as you can see in the following screesnhot:

Maybe you need to synchronize with a/the repository if the uninstall
  option is not available.


text:
Q: UIScrollView Skips at Bottom In my app I have a UIScrollView with not many subviews that doesn't use Auto Layout but rather plain old Autosizing to fill itself to the size of the view controller. The only line of code that interacts with it is this:
settingScrollView.contentSize = CGSizeMake(320, 600);

The problem is that only on the iPhone 4/4S, it does this skip sort of thing when you reach the bottom of the scroll view. Here is a video of what happens.
Is this a UIKit bug or am I doing something wrong?

A: The problem seems to be a bug with iOS 7. This was a scrollview in a scrollview which, while I know is not best practice, worked just fine on the iPhone 5/5S form factor it had the strange behavior mentioned above on the iPhone 4/4S. Moving the daughter scrollview out of the parent scrollview and having it move as though it were in the parent scrollview.


text:
Q: после обновления Kubuntu 11.04 -> 11.10 не загружается система Добрый день, помогите, пожалуйста, с такой проблемой: после того как обновил систему на ноуте, система грузится до того момента пока не появляется окно авторизации, ввожу парольлогин и всё... дальше ничего не происходит, снова появляется это окно, а сама система не грузится. Причём клава и тачпад не работают ноутовские, почему-то работают только usb-клава и мыш. В чём может быть проблема? И как её исправить?Заранее большое спасибо!
A: зайди в защищенный режим при загрузке, создай нового пользователя.перезагрузись и в графическом режиме попробуй зайти под новым именем, может помочь, хотя не всегдаИли, если есть возможность при входе поменять графическую среду с КДЕ на какой либо легкий Х типа блекбокса, попробуй зайти с него


text:
Q: WebElement click intercepted by itself I'm receiving an ElementClickInterceptedException when trying to click on a button. Normally I would be able to handle this, but the curious thing is that the 'intercepting' element is the same element as the one I'm trying to click, as seen here:
    org.openqa.selenium.ElementClickInterceptedException: element click intercepted: Element <button type="button" name="button" class="vs-component vs-button vs-button-success vs-button-filled includeIcon includeIconOnly vs-radius small">...</button> is not clickable at point (220, 72). Other element would receive the click: <button type="button" name="button" class="vs-component vs-button vs-button-warning vs-button-filled includeIcon includeIconOnly vs-radius small">...</button>

I have checked the button in devTools using the selector:
button[class='vs-component vs-button vs-button-warning vs-button-filled includeIcon includeIconOnly vs-radius small']

Sure enough, there is exactly one element on the page with that selector.
What is going on here?
I am using chromedriver 95.

A: I think, the your selector is wrong in your code. you are trying to click on warning button but it is blocked by success button.


text:
Q: How to capture an RTSP livestream via Java? I know, there are several posts handling with this problem here on Stackoverflow, but I didn´t get a solution for my problem. I have an ipcam and I want to capture the livestream using java. The problem is, that I can only access the cam via RTSP. There is no normal http://xxx.xxx.xxx:xx access.
I use the OpenCv library but unfortunately my program only works with the webcam of my laptop because it is the default device.
protected void init()
    {
        this.capture = new VideoCapture();
        this.faceCascade = new CascadeClassifier();
        this.absoluteFaceSize = 0;
    }

    /**
     * The action triggered by pushing the button on the GUI
     */
    @FXML
    protected void startCamera()
    {
        // set a fixed width for the frame
        originalFrame.setFitWidth(600);
        // preserve image ratio
        originalFrame.setPreserveRatio(true);

        if (!this.cameraActive)
        {
            // disable setting checkboxes
            this.haarClassifier.setDisable(true);
            this.lbpClassifier.setDisable(true);

            // start the video capture
            //String URLName = "rtsp://username:password@rtsp:554/h264/ch1/main/av_stream";
            this.capture.open("rtsp://192.168.178.161:554/onvif1");

            // is the video stream available?
            if (this.capture.isOpened())
            {
                this.cameraActive = true;

                // grab a frame every 33 ms (30 frames/sec)
                Runnable frameGrabber = new Runnable() {

                    @Override
                    public void run()
                    {
                        Image imageToShow = grabFrame();
                        originalFrame.setImage(imageToShow);
                    }
                };

                this.timer = Executors.newSingleThreadScheduledExecutor();
                this.timer.scheduleAtFixedRate(frameGrabber, 0, 33, TimeUnit.MILLISECONDS);

                // update the button content
                this.cameraButton.setText("Stop Camera");
            }
            else
            {
                // log the error
                System.err.println("Failed to open the camera connection...");
            }
        }


text:
Q: How to get info about how many minutes/seconds a particular video been watched in YouTube? I was struck with a problem which needs the total view time on a particular Youtube video.
I checked with the Youtube-data API and it seems to offer the following statistics:
"statistics": {
    "viewCount": "xyz",
    "likeCount": "a",
    "dislikeCount": "b",
    "favoriteCount": "c",
    "commentCount": "d"
   }

I expect the API to give me the statistic on the total view time of a particular video of interest.


text:
Q: DRY mocha async tests Using mocha I often need to do something like the following in my acceptance tests:
beforeEach(function(done) {
  Factory.createMany('artifact', 2, function(err, result) {
    if(err) {
      return done(err);
    }
    expected = result;

    done();
  });
});

It would be nice to DRY it up a bit to get rid of the allways repeading error handling. One idea I came up with is:
function failOrRun(done, fn) {
  return function(err, result) {
    if (err) {
      return done(err);
    }

    return fn(result);
  };
}

Factory.createMany('artifact', 2, failOrRun(done, function(result) {
  expected = result;
  done();
}));

But this is also not really  readable. It would be nice if you can give me some hints for my refactoring.

A: You have two separate issues:

*

*code repetition in unit tests.

*code readability in unit tests.

Regarding the first point, DRY is a useful principle, but do not overestimate his importance when writing Unit Tests. Readability and maintainability are crucial, IMO, and I would trade just a bit of redundancy for a tangible improvement in readability.
The second point is partially opinion based, but I would say: study and learn how to use Promises. It's not that Promises are always safe (you have to remember to always return a Promise inside a then and call fail to catch runtime errors), but they are WAY easier to read.
You can use the ES6 implementation or a library like Q to leverage a robust Promise implementation.
Good luck.


text:
Q: how to read number of users number from data. Properties file in selenium I Want to create test that gets every time (in a loop) different customer number and make some operations on him and after that take the 2nd customer number and etc.
Therefore I create data.properties file containing the next data :
customernumber1=500054237
customernumber2=500054238
customernumber3=500054235

I decelerate the variable
customernumber = getObject("customernumber");

my getObject method
public static String getObject(String Data) throws IOException

    {
        loadData();
        String data = properties.getProperty(Data);
        return data;

    }

I have this code :
for (int i = 1; i < 3 ; i++ )
            {

            bo.textfield().sendKeys("customers");
            Thread.sleep(1000);
            bo.customers().click();
            Thread.sleep(1000);
            bo.opencustomers().click();
            Thread.sleep(1000);
            bo.customerid().sendKeys(customernumber + i);

But the result of this is a : "null1", in the 1st run.
How can I call every time the customer number I have in the properties file ?
I think I need to call the property name and not the property value - is this is true ? and if so how can I make it ?
Thanks.

A: Issue:
The main culprit here is that you are passing "customernumber" in the getObject method, which doesn't exist in the property file.
 customernumber = getObject("customernumber");

You can see there is no such thing as "customernumber"
//Actual Property file data:
        customernumber1=500054237
        customernumber2=500054238
        customernumber3=500054235

Also, you are passing (customernumber + i), which has not much effect, as it will only add null1, null2 or so on, as per your current code. bo.customerid().sendKeys(customernumber + i);
One more thing, the loop should be i<=3 instead of i<3

for (int i = 1; i < 3 ; i++ )
            {

            bo.textfield().sendKeys("customers");
            Thread.sleep(1000);
            bo.customers().click();
            Thread.sleep(1000);
            bo.opencustomers().click();
            Thread.sleep(1000);
            bo.customerid().sendKeys(customernumber + i);

Output:

Solution:
Inside your for loop, plz initilize your String customernumber = getObject("customernumber"+i); and pass "i" dynamic variable to get dynamic data.
public static void main(String[] args) throws IOException {
    for (int i = 1; i <= 3 ; i++ ) {
        String customernumber = getObject("customernumber"+i);
        System.out.println(customernumber);
        bo.textfield().sendKeys("customers");
        Thread.sleep(1000);
        bo.customers().click();
        Thread.sleep(1000);
        bo.opencustomers().click();
        Thread.sleep(1000);
        bo.customerid().sendKeys(customernumber);
    }
}

public static String getObject(String Data) throws IOException
{
    System.out.println(Data);
    Properties properties =  loadData();
    String data = properties.getProperty(Data);
    return data;

}

public static Properties loadData() throws IOException {
    Properties prop = new Properties();
    FileInputStream fn = new FileInputStream(new File("{YOUR-PATH}"));
    prop.load(fn);

    return prop;
}

Output:

Best Approach: is to use Dataprovider with exce and to pass the data to Dataproviders by reading the data from excel sheet. DataProvider helps to send multiple sets of data to a test method
Ref: https://www.seleniumeasy.com/testng-tutorials/import-data-from-excel-and-pass-to-data-provider


text:
Q: How to implement some of these Ruby concepts?
*

*In order to call MyClass::empty().empty Do I need to implement an empty method in side MyClass? What would I write inside it?

*Following, I am not sure how such a call could work: x = MyClass::empty().add("a").add("b")Would this be simply calling the add method if it is empty?

A: What would you write inside it? What do you want it to do?
You'd have a class method named empty that returns something having an empty method that either (a) took no parameters, or (b) had them defaulted.
class MyClass
  def self.empty
    return WithEmpty.new # Or existing WithEmpty
  end
end

It also needs to return something that has an add method, and returns itself.
class WithEmpty
  def initialize
    @a_list = []
  end

  def add x
    @a_list << x
    self
  end

  def empty
    @a_list.empty?
  end
end

It'd be easier/quicker if you described what you're trying to do. It's not immediately obvious.
pry(main)> MyClass::empty()
=> #<WithEmpty:0xa01a090 @a_list=[]>
pry(main)> MyClass::empty().empty
=> true
pry(main)> MyClass::empty.empty
=> true
pry(main)> MyClass::empty.add("hi").add("bye")
=> #<WithEmpty:0x9fc8d1c @a_list=["hi", "bye"]>

Now you have no immediate way to get to the "inner" class's list, unless you saved it in either MyClass (sketchy, since the methods are class, not instance, method), or you save the return value from the last bunch of chained methods.
But if you save the instance, what's the point of doing it through MyClass? Again, I can't help but think you need to define what you're actually trying to accomplish, rather than focusing on how you might accomplish it. What's the goal?

Firstly, there is no "add" method for an array. What you're describing, as yet, makes no sense, unless you mean something like this:
class MyClass
  def self.empty
    return MyClass.new
  end

  def initialize
    @arr = []
  end

  def empty
    @arr.empty?
  end

  def add x
    @arr << x
    self
  end
end

Then:
pry(main)> MyClass.empty
=> #<MyClass:0x9aea390 @arr=[]>
pry(main)> MyClass.empty.add("ohai").add("kthxbai")
=> #<MyClass:0x99f505c @arr=["ohai", "kthxbai"]>

But again: you're mixing class and instance methods in a way I don't find sensical. How do you want to access the array? What's the point of MyClass? Why not just use an array?
pry(main)> a = []
=> []
pry(main)> a.empty?
=> true
pry(main)> a << "ohai" << "kthxbai"
=> ["ohai", "kthxbai"]
pry(main)>
pry(main)> a.empty?
=> false

Without any guidelines for what MyClass's purpose is, telling you a reasonable way to implement it is difficult, because without context, what you've shown doesn't make a lot of sense.


text:
Q: Keras loss function is always negative I have implemented a Keras-based, Bayesian Deep Learning model (based on this repo)
My model's loss appears to be always negative as well as the logits_variance_loss (see screenshot below). Any idea why is this happening or what does it mean for the training? .
And this is after 2 epochs


text:
Q: Parameter from JSP page not visible in servlet JSP page code:
<c:forEach items="${studentInfoList}" var="studentInfo">

        ${studentInfo.student.surname} ${studentInfo.student.name} ${studentInfo.student.patronymic}
         ${studentInfo.group.name}
         ${studentInfo.semester.getYear()}
         ${studentInfo.speciality.title}

            <form name="changeStudent" method="POST" action="controller">
                <input type="hidden" name="command" value="openChangeStudentPage"/>
                <imput type="hidden" name="studentId" value="${studentInfo.student.id}"/>
                <input type="submit" value="Change"/>
            </form>

</c:forEach>

Code generated in browser:

     Surname Name Patr
      KV-01
      4
      Computer eng.

         <form name="changeStudent" method="POST" action="controller">
             <input type="hidden" name="command" value="openChangeStudentPage"/>
             <imput type="hidden" name="studentId" value="2"/>
             <input type="submit" value="Change"/>
         </form>

Now at servlet I try to get "studentId" field by following code and add to request student field:
int studentId = Integer.parseInt(request.getParameter("studentId"));
Student student = DAOFactory.getInstance().getStudentDAO().findStudentById(studentId);
request.setAttribute("student", student);

But on line int studentId = Integer.parseInt(...) occurs error:
java.lang.NumberFormatException: null
java.lang.Integer.parseInt(Integer.java:454)
java.lang.Integer.parseInt(Integer.java:527)
ua.kpi.fpm.portal.command.administrator.OpenChangeStudentPageCommand.execute(OpenChangeStudentPageCommand.java:26)
ua.kpi.fpm.portal.controller.Controller.processRequest(Controller.java:53)
ua.kpi.fpm.portal.controller.Controller.doPost(Controller.java:85)
javax.servlet.http.HttpServlet.service(HttpServlet.java:644)
javax.servlet.http.HttpServlet.service(HttpServlet.java:725)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
org.netbeans.modules.web.monitor.server.MonitorFilter.doFilter(MonitorFilter.java:393)

I can't find out why this error occures and why studentId from form can be null.

A: It should be
<input type="hidden" name="studentId" value="${studentInfo.student.id}"/>

instead of
<imput type="hidden" name="studentId" value="${studentInfo.student.id}"/>

Look at imput tag that is not valid.


text:
Q: The space of functions of gaussian random variables. Suppose $Z \sim \mathcal{N}(0,1)$. Is there anything that can be said about the space of random variables $$\{ X : X = f(Z) \text{ for some continuous } f : \mathbb{R} \rightarrow \mathbb{R} \}$$
For example, is this space dense in the space of random variables under topology induced by convergence in distribution?

A: Assume first that $G$ is a continuous strictly increasing distribution function and $H=G^{-1}$. Then $G(t) \geq x$ iff $H(x) \leq t$. Let $f=H\circ F$ where $F$ is the distribution function of $Z$. Then $f$ is continuous. We have $$P\{f(Z) \leq t\}=P\{H(F(Z)\leq t\}=P\{G(t) \geq F(Z)\}$$ $$=P\{F^{-1}(G(t)) \geq Z\}=F(F^{-1}(G(T)))=G(t).$$ Hence every continuous strictly increasing distribution is in your class.
Now let $G$ be any distribution function. Let $Y$ be a random variable with distribution $G$ independent of $Z$. Then $\frac Z n +Y \to Y$ almost surely, hence in distribution. To finish the proof we now show that $\frac Z n +Y$ has a continuous strictly increasing distribution. This is quite easy since this distribution is given by $\int F_n(x-y)dG(y)$ where $F_n$ is $N(0,\frac 1 {n^{2}})$.


text:
Q: Не могу отправить изменения из-за старого пользователя git Клонировал личный проект на рабочий ноут (macos) (до этого ноут был у моего товарища, вроде все удалил своё), но при push выдает отказ в доступе и ссылается на товарища
remote: Permission to   (name of project) denied to (old user).
fatal: unable to access (name of project): The requested URL returned error: 403

A: Вот это помогло !

*

*Откройте файл .git/config в директории вашего локального репозитория

*Найдите там запись url= под секцией [remote "origin"]

*Поменяйте ее с (например) url=https://PetyaIvanov@github.com/petyaivanov/test_test.git на url=ssh://git@github.com/petyaivanov/test_test.git (ssh-ключ к вашему репо можно найти на самом гитхабе)

*Сохраните и закройте файл конфига. Теперь можете попробовать git push origin master


text:
Q: How to create a custom route when calling an action using form_for? I created custom routes '/album' that routes to 'microposts#new'. However, when I use a form_for it routes to '/micropost' instead of returning to '/album'.
In my controller I'm using render 'album'. I would prefer to keep as render, although I can make it work using redirect_to.
I know the problem is when I'm calling the create action in my micropost controller, it goes to /micropost instead of /album. Still new to rails and help would be appreciated.
Here is routes.rb:
  root 'pages#home'

  get '/album',       to: 'microposts#new'
  post '/album',      to: 'microposts#create'

A: Add url: "/album" as an additional parameter in the form_for.
For additional options, see the doc.


text:
Q: Bootstrap is not working under Admin template I am using Bootstrap template https://startbootstrap.com/themes/sb-admin-2/
While debugging through console I'm getting the following error:

Uncaught TypeError: $(...).datetimepicker is not a function

My header section

<link href="{{URL::asset('vendor/fontawesome-free/css/all.min.css')}}" rel="stylesheet" type="text/css">
<link href="https://fonts.googleapis.com/css?family=Nunito:200,200i,300,300i,400,400i,600,600i,700,700i,800,800i,900,900i" rel="stylesheet">

<link href="http://cdn.rawgit.com/Eonasdan/bootstrap-datetimepicker/e8bddc60e73c1ec2475f827be36e1957af72e2ea/build/css/bootstrap-datetimepicker.css" rel="stylesheet">

<link href="{{URL::asset('css/sb-admin-2.min.css')}}" rel="stylesheet">

Below is HTML for Bootstrap date picker

                <input type='text' class="form-control" />

Note: I have commented on Datepicker Bootstrap Stylesheet in order to avoid stylesheet overlap issues.
Let me know what I may be doing wrong.
Thanks

A: Replace
<input type='text' class="form-control" />
with
<input type='date' class="form-control" />
You don't need to write custom code to create date picker. Happy Coding :)


text:
Q: Efficient looping of a page with multi subpages and storing all of them in one variable? lets say i have as a string the following page:
X <- "http://www.rightmove.co.uk/property-for-sale/Glasgow.html?sortType=6&maxPrice=50000&displayPropertyType=flats&numberOfPropertiesPerPage=50&index=0"

now i would like to iterate it by the last adjacent element
"index=0".
It will be incremented by 50 at every iteration lets say until 500. So I am having 11 strings now with the differences at the end:
"index=0"
"index=50"
"index=100"
...
"index=500"

My question is how to nicely and quickly store each string to the same variable so after finish I could use that variable as an parameter for further data extraction by doing greps, gsubs and regexps ?
I mean I want to download the whole page source by each of that string which is simply a pointer to a website.

A: Are you trying to build a web scraper f?
In my personal experience, the best way is to find the "next page" button in the page and parse next URL from it. This way you are emulating user clicks and your program will know exactly where to stop.
I also store already processed urls, in order to prevent an infinit loop.


text:
Q: How to return multiple values from one function postgres I have these two functions that are returning cursor and dynamically created text, but I need to do it inside one function.
CREATE OR REPLACE FUNCTION get_students2(classId integer)
    RETURNS refcursor
    LANGUAGE plpgsql
AS
$$
DECLARE
    students text DEFAULT '';
    student record;
    cursor_students CURSOR(classId integer)
        FOR SELECT firstName, surname
        FROM tests.students
        WHERE class = classId;
BEGIN
    OPEN cursor_students(classId);

    LOOP
        FETCH cursor_students INTO student;
        EXIT WHEN NOT FOUND;

    students := students || '  ' || student.firstName || ' ' || student.surname;
    END LOOP;

    CLOSE cursor_students;

    RETURN cursor_students;
END;
$$

CREATE OR REPLACE FUNCTION get_students(classId integer)
    RETURNS refcursor
    LANGUAGE plpgsql
AS
$$
DECLARE
    students text DEFAULT '';
    student record;
    cursor_students CURSOR(classId integer)
        FOR SELECT firstName, surname
        FROM tests.students
        WHERE class = classId;
BEGIN
    OPEN cursor_students(classId);

    LOOP
        FETCH cursor_students INTO student;
        EXIT WHEN NOT FOUND;

    students := students || '  ' || student.firstName || ' ' || student.surname;
    END LOOP;

    CLOSE cursor_students;

    RETURN students;
END;
$$

I've tried to find how to do it and haven't come across any solution. I thought about making it inside a table, but I don't know if that's possible and didn't find anything about this.
I am not experienced with SQL at all, so don't know if such a thing is possible.
It's a task and the rules are that there needs to be a cursor, dynamic sql and function must return them both.
Thanks.

A: To return value to a function that returns table, we have to include RETURN QUERY statement inside function.
CREATE OR REPLACE FUNCTION get_students(classId int)
    RETURNS TABLE (
        students_cursor refcursor,
        students_list text
)
AS $$
DECLARE
    students text DEFAULT '';
    student record;
    cursor_students CURSOR(classId integer)
        FOR SELECT firstName, surname
        FROM students
        WHERE class = classId;
BEGIN

    OPEN cursor_students(classId);

    LOOP
        FETCH cursor_students INTO student;
        EXIT WHEN NOT FOUND;

    students := students  '  '  student.firstName  ' '  student.surname;
    END LOOP;

    CLOSE cursor_students;

    RETURN QUERY
       SELECT cursor_students,students;

END; $$

LANGUAGE 'plpgsql';


text:
Q: Automatic void * to C++ class cast I'm trying to bind some C++ classes to Lua. When using single inheritance the problem is very easy, however when using multiple inheritance, there is a problem to determine the type of class that a void * holds.
Lua can only manage user's data via void pointers, so when you have the following:
#include <string>

class A {
public:
    A() { }
    ~A() { }
};

class B {
private:
    std::string m_name;
    int m_count;

public:
    B() { }
    ~B() { }
};

class C
    : public A
    , public B
{
private:
    std::string m_title;

public:
    C() { }
    ~C() { }
};

Declaring a pointer to C and cast it to B will auto align the pointer to the placement of B in the class C, as the following explain:
int main()
{
        C *c = new C();
        B *b = c;

        printf("c = %p, b = %p\n", c, b);

        return 0;
}

And the output:
$ ./a.out
c = 0x801807040, b = 0x801807050
So here, we see that the B class is located after the size of A plus some internal data that the compiler adds.
Now the question is, how to automatically cast the void * pointer that holds the class to the desired type using templates? The only thing we now about the void pointer is that it also holds a string with the class name, so for A, we have "A", thus we can create a kind of map to be used.
For instance, I would like to be able to do something like
B *b = castFromVoid<B>(myVoidPtr);

And because I know that the myVoidPtr has its class string set to "C" or to "B", I'm sure that it can be casted to B, but I just need to have a function that actually do the cast for me and I don't find any solution for that using templates.

A: Could this be what you want ?
template<typename T>
T *castFromVoid(void *ptr) {
    return dynamic_cast<T *>(static_cast<A *>(ptr));
}

However, you need RTTI to be enabled in your compiler, and have at least one virtual method in your classes (destructor is a good candidate, isn't it ?).
This assumes all of your classes will inherit from a same base class (here A), because RTTI cannot be performed on a pointer to void.

A: I've finally done something with a map using a from-to basis. As we know the type by string I do something like this:
typedef std::function<void * (void *)> Converter;

map<string, map<string, Converter>> converters;

template <class From, class To>
void createConverter(string fromName, string toName)
{
        converters[toName][fromName] = [&] (void *ptr) -> void * {
                From *from = static_cast<From *>(ptr);

                return static_cast<To *>(from);
        };
}

template <class To>
To * getPointer(string fromName, string toName, void *ptr)
{
        return static_cast<To *>(converters[toName][fromName](ptr));
}

int main()
{
        createConverter<C, A>("C", "A");
        createConverter<C, B>("C", "B");

        C *c = new C();
        B *b = getPointer<B>("C", "B", c);

        // Use b here..

        return 0;
}

The only drawback, is that you need to call createConverter for each possibility, but I think I will create a function that automatically create them for each parents and parents of these parents.


text:
Q: Executing libimobiledevice commands over wifi I am trying to recreate the trustjacking attack presented by Symantec at RSA 2018 but I have been unable to execute libimobiledevice commands remotely through iTunes wifi sync.
When I have a physical USB connection between my ios device and the computer all the commands work perfectly but when I enable itunes wifi sync and disconnect the cable I can no longer contact to the device.
However, when I run idevice_id -l over wifi it displays the uuid of my ios device but any other commands just display errors such as ERROR: Could not connect to device or No device found, is it plugged in?.
Any suggestions on how I can resolve this problem?

A: Its turns out that my version of libimobiledevice was corrupt as well as the dependencies. I fixed this by completely reinstalling libimobiledevice and its dependencies as well as removing all previous data stored by libimobiledevice.

A: I had a similar problem and I had to uninstall the libmobiledevice completely and re-install it again. I found this Github issue here for complete instructions and hence I am sharing the commands here as well for convenience for the future developers.
brew uninstall --ignore-dependencies libimobiledevice
brew uninstall --ignore-dependencies ideviceinstaller
brew uninstall --ignore-dependencies usbmuxd
sudo rm /var/db/lockdown/*
brew install --HEAD usbmuxd
brew unlink usbmuxd
brew link usbmuxd
brew install --HEAD libimobiledevice
brew install --HEAD ideviceinstaller

If you do not have brew installed in your machine, please follow the instruction from this website.


text:
Q: VSTO Word 2013 - How to align string in footer I have created an application that places a piece of specified text in the footer of the document when a button is pressed.
The trouble is that I would like this string to always appear on the top line of the footer, aligned to the right hand side.
Is there a way to align one piece of text in the footer so that it will always appear in the top right of the footer?

A: Well let me say that this will require more research how to get the correct position and probably some hardcoded adjustment. Takes this code as a starting point
There are quite a lot of problems you will have to solve, like
Do you really want to use only section 1?
Do you really want to use only primary footer?
Is PageSetup good enough for getting the correct position?
Also the line
shp.RelativeVerticalPosition = Word.WdRelativeVerticalPosition.wdRelativeVerticalPositionBottomMarginArea;

doesn't seem to have any impact but via Word UI you can set it. This would be good to explore in more detail as it would save you a lot of calculation
using System;
using Word = Microsoft.Office.Interop.Word;

namespace WordAddIn1
{
    public class Class1
    {
        public void InsertShape(Word.Document doc)
        {
            try
            {
                Word.Section sec = doc.Sections[1];
                Word.HeaderFooter foo = sec.Footers[Word.WdHeaderFooterIndex.wdHeaderFooterPrimary];

                Word.Range rng = foo.Range;

                float leftPos = doc.PageSetup.PageWidth - doc.PageSetup.RightMargin;
                float topPos = doc.PageSetup.PageHeight - doc.PageSetup.BottomMargin;

                Word.Shape shp = doc.Shapes.AddTextbox(Microsoft.Office.Core.MsoTextOrientation.msoTextOrientationHorizontal,
                                                       leftPos, topPos, 50, 20, rng);

                shp.TextFrame.TextRange.Text = "Text";
                shp.RelativeVerticalPosition = Word.WdRelativeVerticalPosition.wdRelativeVerticalPositionBottomMarginArea;

            }
            catch (Exception)
            {
                throw;
            }
        }
    }
}


text:
Q: Absolute value of a complex exponential I want to prove that  $ \left|e^{2iRe^{it}}\right| = e ^{ -2R\sin(t)} $  for some constant R.
I know that  $  e ^{ -2R\sin(t)}= e^{-2R\times\text{Im}(e^{it})}  $   where Im denotes the imaginary part, so i just need to prove that
$$ \left|e^{2iRe^{it}}\right| =  e^{-2R\times\text{Im}(e^{it})} $$
but i can not find the relation between the complex modulus and the imaginary part.

A: Hint: $\left| e^{x+iy} \right| =  \left| e^{x} \right| \left| \cos y + i\sin y\right| = e^x$ for $x, y \in \mathbb{R}$.


text:
Q: JQuery Draggable and Sortable placeholder I am facing a particular issue with combining draggable and sortable. The problem has to do with a placeholder not showing when a draggable is moved over the sortable and the drop is not "recognized". This behaviour occurs when the sortable ul hs NO height defined in css.
When i do define a fixed height in css for the #SortablePhotoList, the placeholder is shown and everything works as expected.
The important css :
#SortablePhotoList { list-style-type: none; margin: 2px; padding: 0px; width: 858px; }
.Thumbnail { cursor: hand; width: 136px; height: 102px; float: left; margin: 0 5px 5px 0; position: relative; border: 1px #717171 solid; }
.ThumbnailPlaceholder { width: 136px; height: 102px; float: left; margin: 0 5px 5px 0; border: 1px #000 dotted; }

The important javascript :
  $("#SortablePhotoList").sortable({
        revert: true,
        placeholder: 'ThumbnailPlaceholder',
        tolerance: 'pointer',
        revert: 50,
        distance: 5,
        items: 'li:not(.Upload)',
        stop: function (event, ui) {
            //Do stuff with the sorted thumbnail
        },
        receive: function (event, ui) {
            //Accept the dragged item and change it's appearance a bit
            var item = $('#SortablePhotoList li.NewlyAdded');
            $(".ImageRemove", item).show();
            $(".PhotoSelector", item).show();
            item.removeClass('NewlyAdded');
        }
    });

I could ofcourse play around with programmatically adjusting the height of the #SortablePhotoList to create a workaround for this issue, but i'd rather not go that far.
The question is, what could be the issue of not displaying the placeholder when no height is specified for the container.
Ragards,
avsomeren

A: Change your height in css to
min-height: 102px;

Then it will default to that and when items are added it will expand to fit.


text:
Q: Using firebase with webpack I currently have firebase and my javascript files, which use firebase loaded through <script>. Clearly, this is not a very good way of doing it.
I want to be able to use webpack with my front end javascript, but I'm facing some issues:
My layout is like this:
user/
    index.js
    file1.js
    file2.js

file1.js and file2.jsare included into index.js but all files use firebase.
My question is do I need to include firebase, and all of my requirements, like firestore, functions and messaging. into every single file, or can I include it once somewhere, to be used throughout all files?
When I include it in every file, I get an error saying that firebase could not be found.
Thanks in advance.

A: Check out the Firebase package on npm. In the instructions for using webpack, you can simply import the modules you need into file1.js and file2.js.
import * as firebase from 'firebase';
var app = firebase.initializeApp({ ... });

Note that the documentation says to only include the features you need (to not bloat your bundle.js).
// This import loads the firebase namespace along with all its type information.
import * as firebase from 'firebase/app';

// These imports load individual services into the firebase namespace.
import 'firebase/auth';
import 'firebase/database';

// In your case, include Firestore in the files you use them in.
import 'firebase/firestore';


text:
Q: How to manually set button input type in ASP.NET? I have a jQueryUI dialog with some textboxes, plus a button. Right now, the asp:Button tag used to generate the button automatically sets its type as type="submit". The structure of the dialog is such that pressing enter at any of the textboxes should not call the button click event. It seems like the cleanest way to solve the problem, if it is doable, is to manually set the button's type to something other than submit. Is there a way to do this?
Edit: Forgot to mention this, but the button text is bound to a database item by <%# Eval() %>, which doesn't work without a server-side tag.

A: You can use just a regular html button and set it to whatever you want.  It doesn't have to be a serverside asp button.
In your aspx file:
<input type="button" value="My Button" onclick="DoSomeScript();" />

A: "
        UseSubmitBehavior="false"
        OnClientClick="return" />
The UseSubmitBehavior property tells ASP.NET to render as type="button" and inserts a __doPostBack() function call into the onclick property.  The text of the OnClientClick property gets prepended to the client-side onclick event (with a trailing semicolon if you don't include it yourself), therefore putting return simply short-circuits the event handler and ends up doing nothing at all.

A: I don't think you can set the Button control's AutoPostBack to false, which would normally do what you want.
In this case, I would simply not use asp:Button and just use <input type='button'>.


text:
Q: Hibernate nested select I want from the following query to select only the myEntity (e) results
String query = "select e, to_char(message_date, 'yyyyMMdd') as dateOnly from myEntity e where e.lang = 'DE' and e.message.messageDate > sysdate-5 order by dateOnly desc, e.message.messageType asc"
so when I use the following code
entityManager.createQuery(query).getResultList();

To get the result as List<myEntity> that means to execute the following query
select e from (select e, to_char(message_date, 'yyyyMMdd') as dateOnly from myEntity e where e.lang = 'DE' and e.message.messageDate > sysdate-5 order by dateOnly desc, e.message.messageType asc)

A: My problem is solved using the following query
String query = "select e from myEntity e where e.lang = 'DE' and e.message.messageDate >     sysdate-5 order by to_char(message_date, 'yyyyMMdd') desc, e.message.messageType asc"


text:
Q: Pocketsphinx error reading hub4.5000.DMP I have configured pocketsphinx to work in ubuntu 14.04 and works in pocketsphinx_continous -inmic yes. I am working on a python program that records a .wav file using pyaudio and reads the wav file to decode the recording to text. I have used the latest version of pocketsphinx and has already installed all dependencies.
My python code:http://pastebin.com/kqLs34dC
I have posted my error: http://pastebin.com/NEG0RjGj
Thanks

A: The model hub4.5000.DMP is corrupted, it was broken originally. You need to use latest model from cmusphinx repository, they will work fine.

A: I got the answer to my own question. "print hypothesis.hypstr" prints the detected keyword to stdout.


text:
Q: Perform a certain task when action is performed Let's say we have this awesome User system before us, a User is logged in by a session key (user_id) is set. If a User however gets "banned" the user will still be logged in - until the session expire.
Ways to prevent this is:

*

*Always check if user got banned (every request)

*save session data in perhaps a database to be able to remove the data easily (on the user being banned).
Is there a better approach performing this task?

A: I would choose 1. If you don't retrieve user information from your database in each request, users may also have trouble updating their data. For instance, I can log in at home, change my profile description to 'foo' and go work. There I log in as well, which results in a different session. I change the information to 'bar', which is stored in the database and in my work session. Then I go home and continue browsing in the previously opened home session, which will still contain 'foo'.
Therefor, I think you should at least do some checking against the user database on each request, so during that step you can check if the user is banned as well.
To speed this up, you could keep a special table with storage type MEMORY to keep session information in. This table can be accessed really fast, so it may increase performance. You only need to move information there if a user has changed in the 'real' database. You may use memcache in a similar way. Both are solutions to keep database IO to a minimum while still having the same results. I would add these optimizations only when you need them. Start with just querying the user on each request.

A: Just include in the session the last time it was check to see if it has been banned. Then periodically check it against the banned list of users table.

A: You have to check it every request by user_id. It's not much computations. You can use in-memory storage such as Redis or Memcached to store user_id=>banned pairs to check it rapidly. Second will not work because session is not stable, i can log in from different computers, even browsers and you will need complicated logic and much more resources to perform such task.

A: You don't really want to be connecting to your database on every request as this will greatly increase load times on a server with many users - it's just not the best thing to do.
You could however use Memcache to store and retrieve a list of banned users from - thereby speeding up your data request times.
 if((isset($_SESSION['isloggedin']) && $memcache->get('banneduserid') === true))
 {
     session_unset();
     session_destroy();
 }

Memcache is really easy to use, and fun to learn if you haven't used it before.
You instantiate the memcache object as $memcache for example, and then you simply run methods like $memcache->set() and $memcache->get(). That's it!