text:
Q: Create a dictionary based on fields copied from a Google sheet I hardcoded a database containing personnel into one of my files because I don't know if there's a better way of doing this.
My dictionary looks like this:
autocompleteList2 = {
' ': [' ', ' '],   #so my first input value will be blank
'James': ['James@gmail.com', '555-555-5555'],

I copied a few columns containing similar data from a Google sheet. There's a ton of data. How can I quickly copy/paste this data and have it join my current dictionary? In other words, I want to copy/paste column 1 containing all first names, column 2 containing e-mail addresses, etc, and have it end up like shown above.
The second part of my question: Is this the best way to do it? Would it be better to have my program query the Google sheet for new data? I'm worried that it'll just cause issues with having to connect and authenticate all the time.

A: Yes you can use google's Sheets API to do what you want. But if you're worried about having to connect and authenticate all the time and just want something quick and dirty just export the google sheet as a csv then do something like this:
import csv

autocompletelist2 = {' ': [' ', ' ']}
with open('data.csv', mode='r') as csv_file:
    csv_reader = csv.reader(csv_file)
    for row in csv_reader:
        autocompletelist2[row[0]] = [row[1], row[2]]

The result autocompletelist2 will be the dictionary output that you want:
{
    ' ': [' ', ' '],
    'James': ['James@gmail.com', '555-555-5555'],
    'Mike': ['Mike@gmail.com', '888-888-8888'] #...and so on...
}

A: If (as you mention in the comments) it's reasonable to periodically download the Google Sheet as it's updated, the easiest solution might be to download it as a csv (comma-separated value) file and read it into a dictionary like this:
autocompleteList2 = {}
with open('googlesheet.csv') as infile:
    for line in infile:
        items = line.split(',')
        autocomleteList2[items[0]] = items[1:]

The drawback is that this would have to read the csv file every time you wanted to use the dictionary. An alternative is to create a pickle of the dictionary:
import pickle

autocompleteList2 = {}
with open('googlesheet.csv') as infile:
    for line in infile:
        items = line.split(',')
        autocomleteList2[items[0]] = items[1:]

with open('autocompleteList2.pkl', 'wb+') as outfile:
    pickle.dump(autocompleteList2, outfile)

This creates a file called 'autocompleteList2.pkl', which can then be loaded any time by doing the following:
import pickle

with open('autocompleteList2.pkl', 'wb+') as infile:
    autocompleteList2 = pickle.load(infile)

Be careful with emailing .pkl files around though; they're known to be insecure. Send the csv file and the code to create the pickle file, and have each user create the pickle on their own machine.


text:
Q: why elements of structure array are not swaping ? i am trying to sort array of student structure. based on roll no from main() i am calling function where record is array of struct.in swap() function i am seeing address are exchanging but in partation it is showing original address.
quick_sort(record,0,MAXNO-1);
void quick_sort(struct student arr[],int left,int right)
{
        int pi;
        if(left<right)
        {
                pi=partation(arr,left,right);
                quick_sort(arr,left,pi-1);
                quick_sort(arr,pi+1,right);
        }
 }
int partation(struct student str[],int low,int high)
{
        int i,j;
        struct student pivot=str[high];
        i=low-1;
        for(j=0;j<high;j++)
        {
                if(str[j].rollno < pivot.rollno)
                {
                        i++;
                        swap(&str[i],&str[j]);
                }
        }
        swap(&str[i+1],&str[j]);
        return i+1;
}
void swap(struct student *a,struct student *b)
{
        struct student *temp;
        temp=a;
        a=b;
        b=temp;
}

A: you're locally swapping the pointers in your swap method: it does nothing outside the function.
You have to dereference the pointers so it's effective, like this for instance:
void swap(struct student *a,struct student *b)
{
        struct student temp;
        temp=*a;
        *a=*b;
        *b=temp;
}

A: This is because you are swapping pointers, not structures.
You can swap structs in the same way you swap primitives, such as ints. This is how you'd swap two ints passed to you by pointers:
void swap(int *a, int *b) {
    int tmp = *a;
    *a = *b;
    *b = temp;
}

The code for the struct is nearly identical:
void swap(struct student *a, struct student *b) {
    struct student temp = *a;
    *a = *b;
    *b = temp;
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to copy created player in FIFA 11 PC? Is there any way to copy created player in FIFA 11 PC? The problem is I want to build my own team. Each player will have same physical attribute (attack, defense etc) but will have different name and face. It would be helpful if I could just copy 1 created player and only change the face and name.
Thanks

A: Googling says that the only editor around for FIFA 2011 changes the appearance of the ball… for the demo.

Thus, currently, this is not possible.


text:
Q: How to pass arguments from variables to executable in PS script properly? I'm trying to make a script that monitors a directory (where recordings from a VHF radio are saved by iSpy) for new files and applies a noise reduction process to them using the SoX binary. The simplest part of the script is where I'm failing: I'm not passing parameters to the executable properly. I've tried multiple iterations of the command I'm using based on solutions found on this site only to run into new problems. I tried various quoting strategies I do not understand and piping to CMD but there's obviously something basic that I'm missing. I'm very new to PS and scripting in general, so help would be appreciated.
The whole script (early WIP) is at the bottom of this post.
The binary expects a simple syntax:
sox.exe <file to analyze> <"-n noiseprof"> <analysis output filename>
sox.exe <file to process> <file to save> <"noisered"> <analysis filename> <"0.21 silence -l 1 0.3 5% -1 2.0 5%">

I'm trying to input the binary's path and all parameters/arguments as variables, expand and run the command. Examples of all variables used:
        $soxpath = "C:\Program Files (x86)\sox-14-4-2"
        $path = "E:\SEC Surveillance\audio\EOJNP\2_2021-07-17_10-18-00.mp3"
        $args1 = "-n noiseprof"
        $profileoutput = "E:\SEC Surveillance\audio\EOJNP\2_2021-07-17_10-18-00_noiseprofile.prof"
        $processoutput = "E:\SEC Surveillance\audio\EOJNP\processed\2_2021-07-17_10-18-00_processed.mp3"
        $args3 = "noisered"
        $args4 = "0.21 silence -l 1 0.3 5% -1 2.0 5%"
        #& $soxpath\sox.exe $path $args1 $profileoutput
        #& $soxpath\sox.exe $path $processoutput $args3 $profileoutput $args4

The executable will run just fine if I do not use variables to input paths and arguments, from a PS terminal as well as from a simple script:
& "C:\Program Files (x86)\sox-14-4-2\sox.exe" "E:\SEC Surveillance\audio\EOJNP\2_2021-07-17_10-18-00.mp3" -n noiseprof "E:\SEC Surveillance\audio\EOJNP\2_2021-07-17_10-18-00_noiseprofile.prof"

After various simpler attempts my reasoning was that if I replicate this exact syntax in a script's output, it should work. The result is not pretty:
& "`"$($soxpath)\sox.exe`"" "`"$($path)`"" $args1 "`"$($profileoutput)`""
& : The term '"C:\Program Files (x86)\sox-14-4-2\sox.exe"' is not recognized...

Going back a step results in the executable launching but not getting arguments (based on a Write-Host output I'd expect the command to be spot on):
& $soxpath\sox.exe "`"$($path)`"" $args1 "`"$($profileoutput)`""
sox.exe : C:\Program Files (x86)\sox-14-4-2\sox.exe WARN getopt: option ` ' not recognized
C:\Program Files (x86)\sox-14-4-2\sox.exe FAIL sox: invalid option

Also tried to create a parameter array using variables:
$prm = $ExecutionContext.InvokeCommand.ExpandString("'$path', $args1, '$profileoutput'")
& $soxpath\sox.exe $prm

But honestly I have no idea what I'm doing.
### SETTINGS
    $watcher = New-Object System.IO.FileSystemWatcher
    $watcher.Path = "E:\SEC Surveillance\audio\EOJNP"
    $watcher.Filter = "*.mp3"
    $watcher.IncludeSubdirectories = $false
    $watcher.EnableRaisingEvents = $true

### ACTION
    $action = {
                ### VAR STATIC
                $args1 = "-n noiseprof"
                #$args2 = "null"
                $args3 = "noisered"
                $args4 = "0.21 silence -l 1 0.3 5% -1 2.0 5%"

                ### VAR BASIC PATHS
                $path = $Event.SourceEventArgs.FullPath
                $parentpath = Split-Path -Path "$path"
                $name = $Event.SourceEventArgs.Name
                $namenoext = [IO.Path]::GetFileNameWithoutExtension($name)
                $pathnoext = ("$parentpath" + "\" + "$namenoext")

                ### VAR PROCESS PATHS
                $soxpath = "C:\Program Files (x86)\sox-14-4-2"
                $profileoutput = ("$pathnoext" + "_noiseprofile.prof")
                $processoutput = ("$parentpath" + "\processed\" + "$namenoext" + "_processed.mp3")

                ### PROCESSING AND FILE MANAGEMENT
                # Double quotes escaped
                & "`"$($soxpath)\sox.exe`"" "`"$($path)`"" $args1 "`"$($profileoutput)`""
                & "`"$($soxpath)\sox.exe`"" "`"$($path)`"" "`"$($processoutput)`"" $args3 "`"$($profileoutput)`"" $args4

                }

### START
                Register-ObjectEvent $watcher "Created" -Action $action
                #Register-ObjectEvent $watcher "Changed" -Action $action
                #Register-ObjectEvent $watcher "Deleted" -Action $action
                #Register-ObjectEvent $watcher "Renamed" -Action $action
                while ($true) {sleep 5}

A: *

*&, the call operator, is situationally required for invocation of commands (including external executables), namely if the command is specified via a quoted string and/or a variable or expression, possibly as _part of an expandable (interpolating) string ("...").

*

*However, it's safe to always use &

*To programmatically pass multiple arguments to external executables, use an array.

*

*Be sure to make each argument its own array element; that is, use $array = '-n', 'noiseprof' and not $array = '-n noiseprof' - the latter would be passed as "-n noiseprof", i.e. as a single, double-quoted argument.

*Except in edge cases due to legacy bugs relating to values with embedded " chars. and empty strings - see this answer - do not enclose arguments  in escaped " chars., e.g. "`"$var`"" - if the value of $var contains spaces, PowerShell will automatically double-quoted it behind the scenes.

*Do not use Invoke-Expression, which should generally be avoided, to invoke external programs - see this answer.
Applied to your case:
$soxpath = "C:\Program Files (x86)\sox-14-4-2"
$path = "E:\SEC Surveillance\audio\EOJNP\2_2021-07-17_10-18-00.mp3"
$args1 = '-n', 'noiseprof'
$profileoutput = "E:\SEC Surveillance\audio\EOJNP\2_2021-07-17_10-18-00_noiseprofile.prof"
$processoutput = "E:\SEC Surveillance\audio\EOJNP\processed\2_2021-07-17_10-18-00_processed.mp3"
$args3 = 'noisered'
$args4 = '0.21', 'silence', '-l', '1', '0.3', '5%', '-1', '2.0', '5%'

& $soxpath\sox.exe $path $args1 $profileoutput

& $soxpath\sox.exe $path $processoutput $args3 $profileoutput $args4

As an aside: in order to pass multiple arguments to a PowerShell-native command using named arguments (values targeting parameters by name), you must use parameter splatting.


text:
Q: Two questions on finite abelian groups Which of the following are true?
1.Every group of order $6$ abelian.
2.Two abelian groups of the same order are isomorphic

A: HINT: At this point you should have seen two groups of order $6$, $\Bbb Z/6\Bbb Z$ (sometimes called $\Bbb Z_6$) and $S_3$, and two groups of order $4$, $\Bbb Z/4\Bbb Z$ (sometimes called $\Bbb Z_4$) and the Klein $4$-group. Are both of those groups of order $6$ Abelian? Are those two groups of order $4$ isomorphic? How do you know?

A: none of them is true.
for 1. consider $S_3$.
for 2. consider $\mathbb{Z}_4$ and $\mathbb{Z}_2 \times \mathbb{Z}_2$


text:
Q: Dynamic value mapping in helm using regex and conditionals I'm trying to use conditionals and regex in my helm chart to first check if value1 equals value2 and if it does, uses regexreplaceall to replace a column in a path some/path/path2replace
In my app.yaml file I have this
 livenessProbe:
            httpGet:
            {{ if eq (regexMatch "[^-]+(?=-[^-]*$)" (include "service.name" .)) (regexMatch "[^-]+(?=-[^-]*$)" "my-sample-home-service")}}
              path: {{ .Values.home.health.path }}/app/health
            {{ else }}
              path: {{ regexReplaceAll "[a-zA-Z-]+$" .Values.home.health.path (regexMatch "[^-]+(?=-[^-]*$)" include "service.name" .) }}/app/health
            {{ end }}

In values.yaml I have
home:
  health:
    path: /api/v1/home

service.name could be any of the examples below
my-sample-home-service
my-sample-work-service
my-sample-office-service
my-sample-leisure-service

So if the value in the third row in my service.name equals the value in the third row in the my-sample-home-service then it should pick the default path value in value.yaml file, else it should replace the third column of the path value with the value in the third column of the output from service.name
What I get:
I get the default value from value.yaml even if service.name isn't the same as the default


text:
Q: Shell script to compile C files I used to have a shell script that would compile all of the FILE.c files in a directory to FILE.out
I lost it and am trying to remake it and have the following which I know is very similar but can't tell where I am going wrong.
#!/usr/bin/env bash

for i in 'ls *.c'
do
    gcc -g3 -o3 $i -o {$i%.}.out
done

A: You don't need to run the command ls *.c. Bash will expand the wildcard pattern for you automatically. So if you're completely desperate and do not want to make a Makefile you can do this:
#!/usr/bin/env bash

for i in *.c
do
    echo "gcc -g3 -o3 $i -o ${i%.c}.out"
    # gcc -g3 -o3 "$i" -o "${i%.c}.out"
done

Example
Say I had this sample data:
$ ls -1
a.c
b.c
c.bash
c.c
d.c
e.c

Running my script c.bash:
$ ./c.bash
gcc -g3 -o3 a.c -o a.out
gcc -g3 -o3 b.c -o b.out
gcc -g3 -o3 c.c -o c.out
gcc -g3 -o3 d.c -o d.out
gcc -g3 -o3 e.c -o e.out

To make the script run you'd comment out the echo line above, and uncomment the gcc line.

A: Looking specifically at your question it appears that "where you went wrong" is in your parameter expansion. I think you were trying to change the value of i when naming the output file here:
{$i%.}

I think you misplaced the dollar sign. You may have meant:
${i%.}

Although honesty that would have only removed the "." from the original file name. Whereas "filename.c" would have yielded "filenamec.out". You probably want:
${i%.*}

This would have yielded "filename.out". This parameter expansion syntax translates to a non-greedy deletion of everything starting at "." and after. For greedy deletion the syntax would be:
${i%%.*}

I hope this answers your question better as it relates to your code.

A: Your for-loop for i in 'ls *.c' is looping over the literal string "ls *.c", not the output command as you intended. This could be fixed by using the command substitution operator (e.g. for i in $(ls *.c); do...) but as slm points out in his answer the command is not necessary at all as you can use the output of shell globbing in for-loop :)
This whole issue could also be solved more properly with a simple makefile:
CC = gcc
CFLAGS = -std=c99 -pedantic -D_XOPEN_SOURCE=600 -Wall -Werror -g
RM = rm -f
SRCS = $(wildcard *.c)
PROGS = $(patsubst %.c,%,$(SRCS))

.PHONY: all clean

all: $(PROGS)

%: %.c
    $(CC) $(CFLAGS) -g3 -o3 -o $@ $<

clean:
    $(RM) $(PROGS)

Save as "Makefile", run make. Remove compiled programs (clean) by running make clean. (Partially source by Martin)


text:
Q: What should I write to resize my webbpage to view on Ipod and Iphone? Im trying to add some code when I run my code to detect a Ipod and Iphone, but I can not finde any information on the webb.
$iPod = stripos($_SERVER['HTTP_USER_AGENT'],"iPod");
$iPhone = stripos($_SERVER['HTTP_USER_AGENT'],"iPhone");
$iPad = stripos($_SERVER['HTTP_USER_AGENT'],"iPad");
if(stripos($_SERVER['HTTP_USER_AGENT'],"Android") && stripos($_SERVER['HTTP_USER_AGENT'],"mobile"))
{
    $Android = true;
}
else if(stripos($_SERVER['HTTP_USER_AGENT'],"Android"))
{
    $Android = false;
    $AndroidTablet = true;
}
else
{
    $Android = false;
    $AndroidTablet = false;
}
$webOS = stripos($_SERVER['HTTP_USER_AGENT'],"webOS");
$BlackBerry = stripos($_SERVER['HTTP_USER_AGENT'],"BlackBerry");
$RimTablet= stripos($_SERVER['HTTP_USER_AGENT'],"RIM Tablet");

//do something with this information
if( $iPod || $iPhone )
{
    // What code should It be here.
}


text:
Q: jquery: click callback is called even if button is disabled? I have this code:
// jquery
$(':button').live('click', eventHandler);

<button type="button" name="lvldown" disabled="disabled">Level down</button>

I expected the click event not to be invoked after click if the button is disabled because of this <button> disabled description at w3schools:

Definition and Usage
The disabled attribute specifies that a button should be disabled.
A disabled button is unusable and un-clickable.

However, my eventHandler is still being called after click. Why is that? Do I really need to do something like $(':button:not([disabled])').live('click', eventHandler);?
EDIT: the problem actually ocurrs only under my chrome 16.0.912.77. Under firefox and IE my code works just fine. Btw. I use jquery 1.7.1. Here are some screenshots:
the button, console after load, console after click on the button
My code now basically looks like this:
jQuery(document).ready(function() {
    $(':button').live('click', eventHandler);
    constraintActions();
});

function constraintActions() {
    // level down
    $('.shopCat').not('.shopCat[data-parent]').each(function() {
        var lvlDownButton = $(this).children('p').children('[name=lvldown]');

        if ($(this).children('.shopCat').size() > 0 ||
                $(this).next('.shopCat').size() == 0) {
            lvlDownButton.addClass('disabled');
            lvlDownButton.attr('disabled', 'disabled'); // also tried: lvlDownButton.prop("disabled", true);
        } else {
            lvlDownButton.removeClass('disabled');
            lvlDownButton.removeAttr('disabled'); //also tried: lvlDownButton.prop("disabled", false);
        }
    });

function eventHandler() {
    console.log($(this));
}

EDIT2: In fact the button html looks like this:
<button type="button" class="submit btn-generic" name="lvldown" disabled="disabled">
    Podřadit
</button>

I tried to keep just an essence but it seems that I left out something important and that important thing is the span inside because the following works (!) as expected:
<button type="button" class="submit btn-generic" name="lvldown" disabled="disabled">
    Podřadit
</button>

If i try to add inner span into the examples you provided in the comments, I get these results (under chrome 16.0.912.77):
Javascript (by j08691):
$('button').live('click', function(){alert('FIRE!')});

Html (by j08691):
<button type="button" disabled="disabled">Level down</button>
<button type="button" disabled="disabled">Level down</button>

Javascript (by Pointy, jquery is set to version 1.5.2):
$<button disabled>Hi</button>('button').live('click', function() {
    alert("click");
});

Html (by Pointy):
<button disabled>Hi</button>
<button disabled>Hi</button>

<button disabled>Hi</button>

Under firefox it does not fire no matter what, just under (my) chrome it behaves like this. Is there anything wrong with what I am doing?
P.S. sorry that my post has become so long

A: I found that this is a problem with jQuery < 1.5 and IE (at least IE8). Try one of the working examples above in IE8 and select jQuery 1.4.4 from the dropdown on the left.
To solve this problem try updating the jQuery library.

A: Ideally, you should not have any HTML tags inside a  tag, exception being the  tag which should be avoided anyway and use CSS to get the same effect.
If you are using it to hold a class attribute, you should apply this to the button itself as any formatting applied to the button will be applied to the button content, including text.
It's obvious from your question that your problem stems from the  inside the  so try removing it and applying the class to the actual button.


text:
Q: JqTree breaks on drag after nodeUpdate I have a JqTree with update options and drag and drop which breaks when I try to drag an element after execute nodeUpdate function. I have prepared a demo site here:
JqTree error demo
The way to reproduce the problem is:

*

*Double-click on the last node (VARIOS) and press "Guardar"

*Try to drag it and insert after ELECTRÓNICA

The tree breaks and console launch this error:
tree.jquery.js:2179 Uncaught TypeError: Cannot read property 'addChildAtPosition' of null

Tested on latest versions of Firefox, Chrome and IE

A: Fixed on dev branch by the developer (Marco)


text:
Q: How to convert scala.collection.Set to java.util.Set with serializable within an RDD I have a scala.collection.Set scalaSet : Set[Long].
How will I be able to convert it into a java.util.Set with serializable. I tried the following code, but got
    java.io.notserializableexception: scala.collection.convert.wrappers$setWrapper
import scala.collection.JavaConversions._

Class MySerializableClass extends Serializable {

    // method to implement the Scala to Java operations on the given RDD
    def rddOps(dummyRDD: RDD[(Long, Set[Long])]) = {
        val dummyRDDWithJavaSet = dummyRDD.map( {
            case(key, value) => (key, scalaToJavaSetConverter(value))
    }

    // scala Set to Java Set Converters
    def scalaToJavaSetConverter(scalaSet: Set[Long]): java.util.Set[Long] = {
        val javaSet : java.util.Set[Long] = setAsJavaSet(scalaSet)
        javaSet
    }
}

I have seen the thread notserializable exception when trying to serialize java map converted from scala for an answer, but the solution didn't work with serialization

A: The serialization issue with the scala.collection.JavaConvertions/JavaConverters is that these converters are wrappers that use the underlying (scala/java) object. They are merely a wrapper and therefore for it to be effectively serializable, they must have a warranty that the underlying structure is serializable.
The easiest solution in your case is to implement a structural copy in your conversion method:
// scala Set to Java Set Converters
def scalaToJavaSetConverter(scalaSet: Set[Long]): java.util.Set[Long] = {
    val javaSet = new java.util.HashSet[Long]()
    scalaSet.foreach(entry => javaSet.add(entry))
    javaSet
}


text:
Q: Sum a row of cells based on string texts to the right of the numerical cell I have inherited a monthly leave spreadsheet for employees. The spreadsheet includes all types of leave, including sick leave, for each day of that month. Each manager completes the spreadsheet by indicating the number of hours in the first column under the specific date. The next column under the day indicates the code for the type of leave, i.e. certified sick leave is csl, whereas uncertified sick leave is us.
Please see sample of spreadsheet:

1st     2nd     3rd     4th     5th     6th     7th     8th     9th

H   C   H   C   H   C   H   C   H   C   H   C   H   C   H   C   H   C

11  TIL 11  TIL         11  AL  8.5 AL  8.5 AL  8.5 AL
I am looking to sum the total number of hours in each row based on the text string in the column to the right of the numerical value. This code can reoccur on a number of occasions across each row.

A: Please try:
=SUMIFS($A:$K,$B:$L,"TIL")

and
=SUMIFS($A:$K,$B:$L,"AL")

and other codes to suit.


text:
Q: Trying to understand a line of my own code regarding nav bar Please go to: my website here. Then hover over "GCSEs" and then over "maths". You will see that when you hover over maths, or geography, another "sub-menu" appears with dropdown content "algebra" etc.. I am trying to make the sub-menu horizontally inline with the parent.
Here is the css code of the sub menu:

/*-------------- Second sub menu -----------*/
.dropdown2 {
  float: left;
  overflow: hidden;
}

.dropdown2 .dropbtn2 {
  font-size: 20px;
  border: none;
  outline: none;
  color: white;
  padding: 20px 20px;
  height: 120px;
  box-sizing: border-box;
  background-color: inherit;
}

/*--- Colour when hovered over ---*/
.redhover a:hover,
.dropdown2:hover .dropbtn2 {
  background-color: #ddd;
}

/* --- Colour of background of box when parent is hovered over but sub content is NOT hovered over --- */
.dropdown-content2 {
  display: none;
  position: absolute;
  background-color: #f9f9f9;
  min-width: 160px;
  box-shadow: 0px 8px 16px 0px rgba(0, 0, 0, 0.2);
  z-index: 1;
 margin-left: 160px;
}

/* --- Text formatting of sub-content --- */
.dropdown-content2 a {
  float: none;
  color: black;
  padding: 12px 16px;
  text-decoration: none;
  display: block;
  text-align: left;
  font-family: 'Montserrat';
}

/*--- Colour of background box when hovering over sub content ----*/
.dropdown-content2 a:hover {
  background-color: #ddd;
}

/*----- affects size of sub content block ---*/
.dropdown2:hover .dropdown-content2 {
  display: block;
}

/*-----------End of sub menu -------------*/

Which line, is the line that currently sets the "dropdown content" e.g. Algebra etc. "below" the parent? Looking through my code, I am not sure how I ever managed to get my dropdown content to appear below the button.
If I can figure out what is making it appear below the parent, I should be able to figure out how to move it horizontally inline. I have already move the dropdown content the correct distance to the "right" of the parent, but its set below.
cheers!

A: Adding a margin-top value of -44px to dropdown-content2 will achieve this, although it might not be the most effective solution.
.dropdown-content2 {
display: none;
position: absolute;
background-color: #f9f9f9;
min-width: 160px;
box-shadow: 0px 8px 16px 0px rgba(0, 0, 0, 0.2);
z-index: 1;
margin-left: 160px;
margin-top: -44px;
}

A: Add margin-top:-45px; style in dropdown-content2 class.It should work.

A: In fact you didn't do anything for it, but as long as the dropdown has no left or top position, and is after the button, it works.
Be careful with that, it could be a problem with some older browsers.
Usually I set a position: relative to the parent element then for the dropdown element left:0; top: <menu-height>


text:
Q: $\lim\limits_{x \to 1+} \frac{x-\sqrt{\arctan(x)-\frac{\pi}{4}}-1}{x-1}$ $$\lim\limits_{x \to 1+} \frac{x-\sqrt{\arctan(x)-\frac{\pi}{4}}-1}{x-1}$$
I tried this
$\frac{x-\sqrt{\arctan(x)-\frac{\pi}{4}}-1}{x-1} = 1-2\sqrt{\frac{\arctan(x)-\frac{\pi}{4}}{x-1}}.\frac{1}{\sqrt{x-1}}$
I am stuck here !

A: Let's compute
$$
\lim_{x\to1^+}\frac{\sqrt{\arctan x-\frac{\pi}{4}}}{x-1}
$$
One way could be to substitute
$$
\sqrt{\arctan x-\frac{\pi}{4}}=t
$$
so
$$
\arctan x=t^2+\frac{\pi}{4}
$$
and therefore
$$
x=\tan(t^2+\tfrac{\pi}{4})=\frac{\tan(t^2)+1}{1-\tan(t^2)},
\qquad
x-1=\frac{2\tan(t^2)}{1-\tan(t^2)}
$$
so we get
$$
\lim_{t\to0^+}\frac{t(1-\tan(t^2))}{2\tan(t^2)}=
\lim_{t\to0^+}\frac{1}{2t}\frac{t^2}{\tan(t^2)}(1-\tan(t^2))
$$
The first factor goes to $\infty$, the other two go to $1$, so the overall limit is $\infty$.
Now
$$
\lim_{x \to 1^+} \frac{x-\sqrt{\arctan(x)-\frac{\pi}{4}}-1}{x-1}=
\lim_{x\to1^+}\biggl(1-\frac{\sqrt{\arctan x-\frac{\pi}{4}}}{x-1}\,\biggr)
=-\infty
$$
A different way is considering that
$$
\lim_{x\to1^+}\frac{\arctan x-\frac{\pi}{4}}{x-1}
$$
is the derivative of $\arctan$ at $1$, so it is finite (precisely $1/2$); then our limit is
$$
\lim_{x\to 1^+}\frac{\arctan x-\frac{\pi}{4}}{x-1}
\frac{1}{\sqrt{\arctan x-\frac{\pi}{4}}}=\infty
$$

A: $$
\begin{aligned}
\lim_{x \to 1+} \frac{x-\sqrt{\arctan(x)-\frac{\pi}{4}}-1}{x-1}
& = \lim _{t\to 0^+}\left(\frac{t+1-\sqrt{\arctan \left(t+1\right)-\frac{\pi }{4}}-1}{t+1-1}\right)
\\& = \lim _{t\to 0^+}\left(\frac{t-\sqrt{\arctan \left(t+1\right)-\frac{\pi \:}{4}}}{t}\right)
\\& = \lim _{t\to 0^+}\left(\frac{2t-\sqrt{4\arctan \left(t+1\right)-\pi \:}}{2t}\right)
\\& = \lim _{t\to 0^+}\left(\frac{2t-\sqrt{\pi +2t-t^2+o\left(t^2\right)-\pi \:\:}}{2t}\right)
\\& = \lim _{t\to 0^+}\left(\frac{2t-\sqrt{-t^2+2t}}{2t}\right)
\\& =\frac{1}{2} \lim _{t\to 0+}\left(2-\sqrt{\frac{2}{t}-1}\right)
\\& = \color{red}{-\infty}
\end{aligned}
$$
Solved with substitution $t = x-1$ and Taylor expansion


text:
Q: "Remember Me" not working on server I'm implementing "Remember Me" feature, I want the user to not have to enter login/password again.
It's seems to work in local, but in a shared hosting, It last for about 15 minutes then logout. Here is the code:
controller:
FormsAuthentication.SetAuthCookie("username", true);

Web.config:
<authentication mode="Forms" >
    <forms loginUrl="~/Account/LogOn" timeout="262974" cookieless="UseCookies" />
</authentication>
<sessionState mode="InProc" timeout="262974" cookieless="UseCookies" />

EDIT
I've added the sessionState, but still the same problem, working on local and not on the server?
what am I missing?

A: Look into the sessionstate element in your web.config. For example:
<sessionState mode="InProc" timeout="60" />

Check out the following SO question for differences between the sessionstate element and the forms element in your web.config:
Differences in forms auth timeout and session timeout
The accepted answer by @womp states the following:

A session starts every time a new user hits the website, regardless of
  whether or not they are anonymous. Authentication has very little to
  do with Session.
Authentication timeout is the amount of time that the authentication
  cookie is good for on the user's browser. Once the cookie expires,
  they must re-authenticate to access protected resources on the site.
So, if Session times out before the Authentication cookie - they are
  still authenticated, but all their session variables disappear, and
  may cause errors in your website if you are not disciplined in
  checking for nulls and other conditions brought about by missing
  session.
If Authentication times out before the session, then all their session
  variables will still exist, but they won't be able to access protected
  resources until they log back in again.

A: I finally found the solution, I had to use StateServer instead of InProc and also a machine key, Here is the full solution:
Controller:
FormsAuthentication.SetAuthCookie("username", true);

Web.config:
<authentication mode="Forms" >
    <forms loginUrl="~/Account/LogOn" timeout="262974" cookieless="UseCookies" />
</authentication>

<sessionState mode="StateServer" timeout="262974" cookieless="UseCookies" />

<machineKey validationKey="5BAE63F50C69C1BBB7BFC2E696674389C307E28E9DEB60FB273B85CAD8FC3C2261FB13DF92B90A99C6EB684FDB1F6E3E92E1A42083EB77B5918126DD52245FB5" decryptionKey="11F6FE0C790413FFF3E230387168016B212216DEF727C4157CDDD0558BEAE5B7" validation="SHA1" decryption="AES" />

I have a shared hosting with Arvixe and it's in their Support where I found the solution: support.arvixe.com

A: Go to : ASP.NET Settings  and scroll to Session settings change "value" none to "Forms" It will be done!


text:
Q: Pyspark how to filter out data in datafram that exists in a list I am trying to filter out data in dataframe that exists in a different tuple list.
For example, my existing_df contains the following data:
| one_id |  another_id  | val1 | val2 | val3 |
-------------------------------------------------
| 1      |  11          | a1   | b1   | c1   |
| 2      |  12          | a2   | b2   | c2   |
| 3      |  13          | a3   | b3   | c3   |
| 4      |  14          | a4   | b4   | c4   |

list1 = ['1','2']
list2 = ['11','12']

The expected result is the following dataframe:
| one_id |  another_id  | val1 | val2 | val3 |
-------------------------------------------------
| 3      |  13          | a3   | b3   | c3   |
| 4      |  14          | a4   | b4   | c4   |

In my code I am doing the following:
keys = some_df.select("one_id", "another_id")\
    .rdd.map(lambda r: (str(r[0]),str(r[1]),)).distinct().collect()
list1, list2 = zip(*keys)

existing_df.filter(
    ~existing_df.one_id.fn.isin(list1) & ~existing_df.another_id.fn.isin(list2)
)

and I and getting the following exception:

{Py4JJavaError}An error occurred while calling z:org.apache.spark.sql.functions.lit.
: java.lang.RuntimeException: Unsupported literal type class java.util.ArrayList [oneId1, oneId2]
  at org.apache.spark.sql.catalyst.expressions.Literal$.apply(literals.scala:78)
  at org.apache.spark.sql.catalyst.expressions.Literal$.$anonfun$create$2(literals.scala:164)
  at scala.util.Failure.getOrElse(Try.scala:222)
  at org.apache.spark.sql.catalyst.expressions.Literal$.create(literals.scala:164)
  at org.apache.spark.sql.functions$.typedLit(functions.scala:127)
  at org.apache.spark.sql.functions$.lit(functions.scala:110)
  at org.apache.spark.sql.functions.lit(functions.scala)
  at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
  at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
  at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
  at java.lang.reflect.Method.invoke(Method.java:498)
  at py4j.reflection.MethodIn...

A: You are almost close.
df = spark.createDataFrame([(1,11,'a1','b1','c1'),(2,12,'a2','b2','c2'),(3,13,'a3','b3','c3'),(4,14,'a4','b4','c4')],['one_id','another_id','val1','val2','val3'])
list1 = ['1','2']
list2 = ['11','12']

You can use NOT isin() through this syntax  (isin() == False or ~isin())
from pyspark.sql.functions import col
df.where((col('one_id').isin(list1) == False) & (col('another_id').isin(list2) == False)).show()

#+------+----------+----+----+----+
#|one_id|another_id|val1|val2|val3|
#+------+----------+----+----+----+
#|     3|        13|  a3|  b3|  c3|
#|     4|        14|  a4|  b4|  c4|
#+------+----------+----+----+----+


text:
Q: Issue with monitoring custom service on prometheus in kubernetes namespace My goal is to monitor services with Prometheus, so I was following a guide located at:
https://github.com/coreos/prometheus-operator/blob/master/Documentation/user-guides/getting-started.md
I am relatively new to all of this, so please forgive my naiveness. I tried looking into the error, but all the answers were convoluted. I have no idea where to start on the debug process (perhaps look into the YAMLs?)
I wanted to monitor a custom Service. So, I deployed a service.yaml of the following into a custom namespace (t):
kind: Service
apiVersion: v1
metadata:
  namespace: t
  name: example-service-test
  labels:
    app: example-service-test
spec:
  selector:
    app: example-service-test
  type: NodePort
  ports:
  - name: http
    nodePort: 30901
    port: 8080
    protocol: TCP
    targetPort: http
---
apiVersion: v1
kind: Pod
metadata:
  name: example-service-test
  namespace: t
  labels:
    app: example-service-test
spec:
  containers:
  - name: example-service-test
    image: python:2.7
    imagePullPolicy: IfNotPresent
    command: ["/bin/bash"]
    args: ["-c", "echo \"
This is POD1 $(hostname)
\" > index.html; python -m SimpleHTTPServer 8080"]
    ports:
    - name: http
      containerPort: 8080

And deployed a service monitor into the namespace:
apiVersion: monitoring.coreos.com/v1
kind: ServiceMonitor
metadata:
  name: example-service-test
  labels:
    team: frontendtest1
  namespace: t
spec:
  selector:
    matchLabels:
      app: example-service-test
  endpoints:
  - port: http

So far, the service monitor is detecting the service, as shown:
Prometheus Service Discovery.
However, there is an error with obtaining the metrics from the service: Prometheus Targets.
From what I know, prometheus isn't able to access the /metrics on the sample service - in that case, do I need to expose the metrics? If so, could I get a step by step guide solution to how to expose metrics? If not, what route should I take?

A: I'm afraid you could miss the key thing from the tutorial you're following on CoreOS website, about how a metrics from an app are getting to Prometheus:

First, deploy three instances of a simple example application, which
  listens and exposes metrics on port 8080

Yes, your application (website) listens on port 8080, but does not expose any metrics on '/metrics' endpoint in the known to Prometheus format.
You can verify about what kind of metrics I'm talking about by hiting the endpoint from inside of Pod/Conatiner where it's hosted.
kubectl exec -it $(kubectl get po -l app=example-app -o jsonpath='{.items[0].metadata.name}') -c example-app -- curl localhost:8080/metrics

You should see similar output to this one:

# HELP codelab_api_http_requests_in_progress The current number of API HTTP requests in progress.
# TYPE codelab_api_http_requests_in_progress gauge
codelab_api_http_requests_in_progress 1
# HELP codelab_api_request_duration_seconds A histogram of the API HTTP request durations in seconds.
# TYPE codelab_api_request_duration_seconds histogram
codelab_api_request_duration_seconds_bucket{method="GET",path="/api/bar",status="200",le="0.0001"} 0
codelab_api_request_duration_seconds_bucket{method="GET",path="/api/bar",status="200",le="0.00015000000000000001"} 0
codelab_api_request_duration_seconds_bucket{method="GET",path="/api/bar",status="200",le="0.00022500000000000002"} 0
codelab_api_request_duration_seconds_bucket{method="GET",path="/api/bar",status="200",le="0.0003375"} 0
codelab_api_request_duration_seconds_bucket{method="GET",path="/api/bar",status="200",le="0.00050625"} 0
codelab_api_request_duration_seconds_bucket{method="GET",path="/api/bar",status="200",le="0.000759375"} 0

Please read more here on ways of exposing metrics.


text:
Q: Ned Stark's brother I've recently watched the first season of "Game of Thrones" again and I was wondering if it was ever established as to the whereabouts of Ned Stark's brother?  Has he been confirmed dead?

A: Season 6 spoilers.

In s06e06, Benjen rescued Bran and Mira from wights. After that, he told that during his fateful ranging beyond the wall, he was attacked by White Walkers. One of them shoved an ice sword into his gut and left him for dead. He was discovered by the Children of the Forest, who saved him and stopped him from becoming a wight by shoving a piece of dragonglass into his chest.

According to Martin, in books, Benjen is not Coldhands.
But showrunners in "inside the episode" video called character, who saved Bran and Meera, Coldhands

A: It depends which brother you're talking about.
Brandon (not to be confused with Ned's son Brandon, or any of the many other Brandon Starks in Westeros's history) is confirmed as dead, killed by Mad King Aerys nearly twenty years before the series begins.
Benjen has been missing presumed dead since almost the beginning of the series, but has never been confirmed as dead.

A: It's never actually confirmed if he is dead or not. As for the spoilers issue that's not confirmed either.

A:
 Benjen as Coldhands??
 That HAS not been confirmed at all!!

He could have been taken captive by some wildings.
He could have been killed by the same host that descends on the Fist of the First Men.
He could have been taken by the weather.
He could have fallen off a mountain top.
It is not mentioned or confirmed in any of the books or in the series so far.
Although there are many "wild" speculations rumours around!


text:
Q: windows LAN using 2 switches performance I am using my Windows Machine on a Local LAN with 2 switches. One 100Mb DLink connected to internet via WAN in the building. Recently I added another DLink fully automated 1Gb switch. All cable connections 6 machines run through than 1Gb DLink. Then one cable runs to 100Mb DLink and that runs to WAN. Is my local network operating at full 1Gb speed or maybe is all compromised to 100Mb due to older 100Mb DLink switch?

A:
Is my local network operating at full 1gb speed?

All six computers connected to the 1 Gbps switch will be able to communicate with each other at up to 1 Gbps.
This assumes they all have a Gigabit Ethernet adapter and that the wiring is all suited to gigabit networking.
Obviously the bandwidth is shared, so throughput will drop if there are multiple concurrent conversations.


text:
Q: CSS not applying to jquery ajax content I have a page that has a jquery AJAX function
$(document).ready(function() {
        var options = {
            target: '#return',
            beforeSend: function() {
                $('#processing').show();
            },
            complete: function() {
                $('#processing').hide();
                $("#SymbolSearchResults tr:even").addClass("SSOdd");
                $("#previous").click(function(){ changestart('back'); });
                $("#next").click(function(){ changestart("forward"); });
                $("#lookup").click(changestart);
            }
            };
        $('#SymbolSearchForm').ajaxForm(options);
    });

    function changestart(direction)
    {
        var rowsElement  = $("#maxrows");
        var rowsValue    = parseInt(rowsElement.val());
        var startElement = $("#startID");
        var value        = parseInt(startElement.val());
        startElement.val(direction == "forward" ? value + rowsValue : direction == "back" ?
value - rowsValue : 1);
    }

</script>

I was having trouble rebinding the click handlers to the #next, #lookup and #previous as well as the class SSOdd to the table #SymbolSearchResults tr:even. I fixed it by adding it into the complete function. However I cannot apply any styles to the target div #return. I can style elements in the #return by ID, but again, nothing to the #return div itself. Is there a solution to this? I can only style the div by using inline CSS in the html page, not desired. I also think maybe I should use the .live function for the click functions inside the complete function? can you add a class with .live?
Please help unf**ck my code!
thx

A: It doesn't appear to be linking via the ID identifier as you said, but I can change the class of that div to .purchase, and it takes on those class attributes. Possibly change the declaration to div.return and the id='return' to class='return'.
Edit
Going to update this until I find the answer on why it's not working, or someone else posts. So far, I'm able to reference the div via document.getElementById('return').style.color = '#FFFFFF';


text:
Q: Having different login pages for different ASP.NET MVC 3 areas Can I have different login URL for different ASP .NET MVC3 areas?
e.g. I would like to have different login page for Administrator and Data entry operators.
I see a web.config in each area's view portion and I have tried doing:
<authentication mode="Forms">
    <forms loginUrl="~/Administration/Account/LogOn" timeout="2880" />
</authentication>

but it does not play well.
Cheers.

A: I'm not aware of .NET handling this for you but you could create a custom AuthorizationAttribute
public class CustomAuthorization : AuthorizeAttribute {

  public string Url { get; set; }

  public override void OnAuthorization(AuthorizationContext filterContext) {

    if (!filterContext.HttpContext.User.Identity.IsAuthenticated) {
      filterContext.HttpContext.Response.Redirect(Url);
    }
    base.OnAuthorization(filterContext);

  }

}

An add that to your controllers/actions
[CustomAuthorization(Url="/Area/Login")]
public class HomeController {
  //...
}

A: My solution was based on the solution presented by David Glenn, thanks.
public class CustomAuthorization : AuthorizeAttribute
{
    public string Url { get; set; }

    // redirect to login page with the original url as parameter.
    protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
    {
        filterContext.Result = new RedirectResult(Url + "?returnUrl=" + filterContext.HttpContext.Request.Url.PathAndQuery);
    }
}

And add the Attribute to your controllers/actions
[CustomAuthorization(Url="/Area/Login")]
public class HomeController {
  //...
}

Is better use filterContext.Result than filterContext.HttpContext.Response.Redirect(Url) to redirect because the current filter will redirect immediately to the login page otherwise the original action will be called and only then redirected to login page.


text:
Q: How to display grouped data from recursive SQL query in a Twig HTML table? I want to be able to display data from a SQL database (using PDO) and present it in an HTML table, however, I am having trouble understanding how to include a subquery in the results of my original query. I have gotten close to my desired result by using the GROUP_CONCAT function to group the data as comma separated values.
Using Twig to populate the HTML table with the desired values, but I can't figure out how to group certain values (course names) underneath the student.
`PHP
SELECT classes.ID, classes.PIDM, classes.fName, classes.lName, classes.advisorOneFirst, classes.advisorOneLast, classes.advisorOneEmail,
GROUP_CONCAT(classes.courseTitle) AS courses
FROM classes
WHERE term = :cterm AND (classes.MGrade = "F" OR classes.MGrade = "F~" OR classes.MGrade = "D" OR classes.MGrade = "D~")
GROUP BY classes.ID
ORDER BY lName ASC

`HTML
{% for student in classes %}

{{student.fName}}
{{student.courses}}

{% endfor %}

To illustrate my webpage looks like this:
student1 course1,course2
student2 course3,course4

And I want it to look like this:
student1 course1
         course2
student2 course3
         course4

Also, using
GROUP_CONCAT(classes.courseTitle SEPARATOR "
")

or any other substitution results in:
student1 course1
course2
student2 course3
course4

A: Twig automatically escapes your variables to protect against XSS attacks, which is why using the
 tags wasn't working. Using the GROUP_CONCAT(classes.courseTitle SEPARATOR "
"), update your twig to use the raw filter:
{% for student in classes %}

{{student.fName}}
{{student.courses|raw}}

{% endfor %}

Update
Using the raw filter could produce other issues depending on the characters in courses. A better approach would be to use a character you can split on as the separator in group_concat, then split on that character and loop each course in twig. For example, if you used a semicolon as the character separator,
Your group concat would look like this:
GROUP_CONCAT(classes.courseTitle SEPARATOR ';')

And your twig would like this:
{% for student in classes %}

    {{ student.fName }}

    {% for course in student.courses|split(';') %}
        {{ course }}

    {% endfor %}

{% endfor %}

A: given a generalized table:
 myTable
=========
foo | bar
----+----
foo1|bar1
foo2|bar2
foo1|bar3
foo2|bar4

SQL
SELECT foo,
GROUP_CONCAT(bar SEPARATOR "@@@") AS bars
FROM myTable
GROUP BY foo

HTML
{% for foobar in myTable %}

    {{foobar.foo}}

    {% for bar in foobar.bars|split("@@@") %}
    {{bar}}

    {% endfor %}

{% endfor %}

webpage presentation
foo1 bar1
     bar3
foo2 bar2
     bar4


text:
Q: django model attribute edit & save with no extra page I rende certain objects values in django template in a form of a table.
I let user to edit the value and save the edit so I can track the history of edit.
At the moment I use django forms to let user do single object attribute value OR chosen objects attribute values OR all of them and save it.
My problem is with forms is that the way it works at the moment is:
user clicks a value in 'main' page so it links to object 'edit' page in which I return a form so user can edit it.
The problem is with that extra url or extra page. I do not want to do it via separate pages.
I would like to click on the object (like in the excel) and change the value there in 'main' page and submit the edits from the same page.
How can I achieve it with django ?
Can somebody point me into right direction and point out what I should read about to understand it or how I should do it ?
I want to edit either single or let user edit multiple objects values and save the changes and still be able to track the history of edits / changes.

A: You should look into modals. So when a user clicks to edit it will display a pop-up that you can render the form in without leaving the page.


text:
Q: Does Search Sources in Chrome work? I have a web app that has about 20 js files that are loading. I tried using Ctrl Shift F (Search Sources) to search for function names across all of the source (js) files. But when I search for myFunction using the Search Sources feature, it doesn't find anything (No matches found.). If I open the source file that contains myFunction and use Ctrl F to search, it is found right away. Opening the file containing myFunction before using Search Sources doesn't change anything.
It makes me think that Search Sources doesn't actually do what it says or I have to configure it to search js files, which seems odd.
Chrome 30.0.1599.114
Ubuntu 12.04

A: Make sure that the Search in content scripts settings is checked. It could be that you had cleared it at some point in the past and forgotten to re-set it, or perhaps an upgrade to Chrome modified the setting (I can't find any confirmation that it currently defaults to off, but others seem to have had it un-checked without realizing it).

*

*Click the gear-icon in the developer tools to open dev-tools settings

*Check Search in content scripts

*Close the tab, re-open it, re-open the dev-tools


text:
Q: How to call async function in a synchronus function? I'm trying to make a discord bot that sends Hey!! in a specific channel on a specific time daily.
but it's giving me an error
import discord
import schedule

bot = commands.Bot(command_prefix = "^")

@bot.event
async def on_ready():
   schedule.every().day.at("18:00").do(job)

   while 1:
       schedule.run_pending()
       time.sleep(1)

async def job():
        channel = bot.get_channel(72246xxxxxxxxx)
        await channel.send("Hey!!")

RuntimeWarning: coroutine 'job' was never awaited

A: @bot.event
async def on_ready():
    while True:
        await asyncio.sleep(1)
        x=datetime.today() #identify the time right now
        y=x.replace(hour=18, minute=0, second=0) #here you can modify time
        delta_t=y-x
        secs=delta_t.seconds
        print(secs) #you can delete this line if you would like to disable visual countdown
        if secs == 0: #when countdown have 0 seconds left it sends the message
            channel = bot.get_channel(1234567890) #your channel id
            await channel.send("Hey!!") #your message

I know I modified your code a lot, but I preferred to use a built-in datetime library. If you want to use schedule library you can try to use asyncio.run(job), but I'm not sure if this would work.


text:
Q: How to yield the system of equation of this plane defined by two 4-dimensional vectors? I'm stuck at a problem :
 Find the system of equations whose solution set is the plane :

I'm not sure how to fetch the system of equations and I guess c1 and c2 are free variables but I don't know how to use them.
( Sorry for posting pic I didn't know how to write those matrices. )

A: A plane $\pi$ in four dimensions is completely determined by a point $Q$ (through which it passes) and a pair $\{u,v\}$ of linearly independent vectors (to which it is orthogonal). $\pi$ is then formed by the points $P$  that satisfy the system of equations:
\begin{equation}
  (P-Q)\cdot u=(P-Q)\cdot v=0.
\end{equation}
You may expand these equations in components, with $P=(x,y,z,w)$, and then you'll find a system of two equations over the variables $\{x,y,z,w\}$.
To be able to write the equations you should find the data $\{Q,u,v\}$. The easiest point $Q$ in $\pi$ to calculate is the one for $c_1=c_2=0$. Finding vectors orthogonal to $\pi$ is the same as finding the ones orthogonal to the vectors $\{w_1,w_2\}$ that multiply $c_1$ and $c_2$ in the definition of $\pi$.
A straightforward method for doing this last part is: take $u$ to have its third and fourth components to be zero, and then you can easily determine that the first two must be equal and of opposite sign. Then take $v$ to have the first two components to be equal and of the same sign (to make sure that it is linearly independent of $u$) and the third and fourth components will follow. The modulus of both vectors is, of course, arbitrary.

Therefore, the resulting final system of equations is:
\begin{equation}
x-y=x+y-6z+2w+10=0
\end{equation}


text:
Q: Theorem 4, Section 2.3 of Hoffman's Linear Algebra
Let $V$ be a vector space which is spanned by a finite set of vectors $\beta_1,…,\beta_m$. Then any independent set of vectors in $V$ is finite and contains no more than $m$ elements.

Question: (1) How does interchanging of sum work, $\sum_{j=1}^n \sum_{i=1}^m (A_{ij}x_j)\beta_i= \sum_{i=1}^m (\sum_{j=1}^n A_{ij}x_j)\beta_i$? (2) I don't understand following sentence in the proof: "since $n\gt m$, theorem 6 of chapter 1 implies that there exists scalars $x_1,…,x_n$ not all $0$ such that $\sum_{j=1}^n A_{ij}x_j=0$, $1\leq i\leq m$". Mainly because I haven't yet studied matrix theory. Is it absolutely necessary to do matrix theory(chapter 1 of Hoffman's) before chapter 2? I'm also dodging examples involving matrix theory. Can we prove question(2) without using any matrix theory?


text:
Q: Fragment instances Or Multiple Fragment (Android) I want to display multiples fragments for each day in a week. The thing is that sometimes there are no data to be displayed in a fragment. (each fragment display the school classes that there are in a day). So it's it better to create one fragment per day and load them when there are data or have only one fragment with multiples instances but different data inside.

A: Fragment is a group of reusable interface.
So, if your "fragments" will all look the same then it's just one fragment initialized with different data.
If there is no data for some particular instance just make all its UI invisible and write something like "No data" in the center. Or do not show that fragment at all.


text:
Q: Why my "ll" command does not run in one account, but runs in another account? I haven't used Linux for many years and I've never been a sys admin, now I need to setup one account just like the other. I have root privilege.
I have 2 Ubuntu 14.04.2 accounts : *13 and *14
On *13 it's set up so that if I type ll, it will mean ls -alF, and it's saved in a file called .bashrc
But on *14, it won't recognize ll even though I've manually copied the .bashrc from *13 to *14, but I did a search online, and found if I do: . ~/.bashrc, then ll will work on *14 just like on *13.
But if I logout and log in again, it won't work again, I'll have to do . ~/.bashrc again.
So my question is, what do I need to do so on *14, it can behave just like on *13, where I can use ll right after I login and don't have to do . ~/.bashrc first?
I have no idea how these accounts are setup, they are corporate accounts in another city and they just gave me access to play with them, so I can test out some stuff. But I do have root access, so I guess I can change things if necessary, but I just don't know how to go about it.

A: My .bash_profile script starts with this preamble:
# .bash_profile

# Get the aliases and functions
if [ -f ~/.bashrc ]; then
    . ~/.bashrc
fi

# User specific environment and startup programs
# . . .

I think bash might only source the .bashrc for certain types of shell sessions. Check if you have something similar to the above in your *13 account. Maybe adding that to the .bash_profile on your *14 account will fix the problem.


text:
Q: Rest Kit Persistance/Performance issue with Multiplie MOCs This is the first time i've used the new version of RestKit and multiple MOC so this ones got my a little stumped. Im using RestKit 0.20-pre5 and am adding Managed Objects through RestKit operations as well as manually throughout the application.
RestKits provides two MOCs to manage performance: the mainQueue and PersistantStore Object contexts. From inspecting RestKits code all new managed objects are saved to the mainQueue MOC (Based on RKObjectManager line 433 and inspection of various pointer addresses). Objects created by RestKit get persisted fine (after calling a save of course) however whenever I create my own ManagedObjects in the same mainQueue MOC and save it, they do not persist when I relaunch the application. (I save the relevant MOC quite often)
This is where the persistant store comes in. Whenever I save the persistant store along with the mainQueue MOC the data persists. I imagine this has something to do with the RKManagedObjectStore merging changes whenever I call save on the persistantStoreMOC (via a notification) So... everything good right?
The problem is whenever I save both contexts there is a noticeable lag that lasts at least 1 second (it can vary up to 3!). This lag seems to increase the more NSManagedObjects I create. I have run instruments and there are no memory issues. I must be using RestKits implementation of core data incorrectly.
For the record I am saving using the following method:
- (void)saveContext
{
    __block BOOL _blockSuccess;
    __block NSError *_blockError;

    NSManagedObjectContext *persistantContext = [[[RKObjectManager sharedManager] managedObjectStore] persistentStoreManagedObjectContext];

    [globalManagedObjectContext performBlockAndWait:^{
            _blockSuccess = [globalManagedObjectContext save:&_blockError];
    }];
    if (! _blockSuccess) NSLog(@"Failed to save context: %@", _blockError);

    [persistantContext performBlock:^{
        _blockSuccess = [persistantContext save:&_blockError];
        if (! _blockSuccess) NSLog(@"Failed to save context: %@", _blockError);
    }];
}

This is called from a singleton object whenever we want to save the state of the application. (globalManagedObjectContext is simply a macro pointing to RestKits mainQueueObjectContext). Removing the persistantContext save removes the lag but of course doesn't persist the data.
Anyones help (especially Blake Watters ;) would be greatly appreciated!
Cheers,
Aron

A: I believe the answer is to use the the saveToPersistentStore: method added by the RKAdditions category to NSManagedObjectContext.
This is taken from here and here.
Do you still have issues when using that?


text:
Q: Vectors as functions? In my study of general relativity, I came across tensors.
First, I realized that vectors (and covectors and tensors) are objects whose components transform in a certain way (such that the underlying reality is one and observers in different reference systems observe the same thing differently).
This is all very intuitive.
However, I have read that the modern way to learn these concepts is to think of vectors as multilinear functions of covectors (similarly for tensors -functions of vectors and covectors- and covectors -functions of vectors-). The problem is that this is not intuitive to me, and I don't understand why this viewpoint has been adopted.
What is the advantage of thinking of vectors as functions over thinking of them as objects that have independent existence but whose components transform in a particular way?
What is the right mindset for understanding the mathematical concepts of general relativity?

A: Here's an analogy.
Consider two friends. Both friends have memorized the steps in the process of long division and use them routinely, but only one friend understands that division is defined to be the inverse of multiplication. Viewing the step-by-step process of long division as the "definition" of division is possible, but the abstract definition is simpler, more intuitively satisfying, and ultimately more empowering.
That's the advantage of the coordinate-free/component-free definition of a vector field, which in turn is used to define other tensor fields without using coordinates or components. The fact that the definition doesn't involve coordinates or components can be used to derive how (and why!) a tensor field's components in one coordinate system must change when we change the coordinate system. Sure, you could just memorize those transformation rules and use them as the "definition," but the abstract definition is simpler, more intuitively satisfying, and ultimately more empowering.

A: I don't think there is any particular advantage in thinking of vectors and tensors as functions - it just gives you another tool in your toolbox.
Starting with co-vectors, they are often introduced in linear algebra courses as linear functions that map the vectors in a vector space to the underlying field of scalars. If we change our co-ordinate system - our rules for representing vectors and co-vectors as a list of components - then scalars do not change. So if the co-vector is a physically meaningful function (and so not dependent on an arbitrary choice of co-ordinates) then its components must transform in the "opposite" way to vector components when we change co-ordinates.
In the same way, we can think of a vector as a linear function that maps co-vectors to the field of scalars, and the components of a physically meaningful vector must transform in the opposite way to co-vector components when we change co-ordinates. This gives a reason why vectors and co-vectors that represent physically meaningful quantities transform in the way that they do.
Extending this "functional" thinking to tensors, we now have four different ways of thinking about a (1,1) tensor:

*

*As a matrix of component values that transforms in a certain way when we change co-ordinates.

*As a linear function that maps a vector to a vector.

*As a linear function that maps a co-vector to a co-vector.

*As a linear function that maps a vector and a co-vector to a scalar.

A: In math, there is a strong bias toward defining the smallest number of entities possible.  If you can definte an entity from another one, then you do so.
With this in mind, covectors naturally have definitions rooted in the differentials of functions from a particular manifold to euclidean space.  With this in mind, then, once one has defined co-vectors, if vectors are then defined as functions of co-vectors, then you don't need any additional entities to define them, and all of them are ultimately rooted in just having defined the existence of functions to Euclidean space, and there are fewer independent entities to carry around in your framework.
The other thing, at least to me, when I was learning, was that that formula for how covectors and vectors transform differently, and why I should care about their transformation laws, was deeply unintuitive to me, in a way that understanding vectors and covectors as differentials and directional derivatives was not, and so, starting with the "coordinate free" version of this was helpful to me in terms of understanding "why we are doing all of this".

A: "What is the advantage of thinking of vectors as functions over thinking of them as objects that have independent existence but whose components transform in a particular way?"
While I think the other answer here are better, there is another perspective on this that I thought you might find useful, which is that (in a sense) by talking about "components" you are already thinking of a vector as a function of covectors without realising it.
The "components of a vector" are functions of a vector. The object "the x component of" takes a vector and returns a number. That's a function. We could write it as "x-component-of(v) = 3" to show it as a function explicitly. In fact, it's a covector. So here we have covectors being seen as functions of a vector.
Now we reverse this and consider a vector v and ask what its x, y, z, etc. components are. We are now looking at it as "v(x-component) = 3". When we say v(x-component) = 3, v(y-component) = 4, v(z-component) = 5 to specify a particular vector, we are doing so by applying an operation to three component directions and stating what numbers are returned.
We can switch from thinking of it as "the-x-component-of(v)" to "v's(x-component)" so automatically that we don't notice the subtle difference. But in using components as properties of and queries about vectors, we are implicitly treating them as functions mapping either a vector or component direction to a coordinate number.

A:
However, I have read that the modern way to learn these concepts is to think of vectors as multilinear functions of covectors

This is actually not quite true, though the distinction is subtle.
In the perspective you describe, one starts with the vector space $V$ as the fundamental structure.  It doesn't matter how you construct it - it could be the tangent space to a manifold (as in GR), or the element of some complex Hilbert space (as in QM), or the space of polynomials in some variable.
Covectors are then elements of the algebraic dual space $V^*$, consisting of linear maps from $V$ to the underlying field $\mathbb K$ (usually $\mathbb R$ or $\mathbb C$).  $(p,q)$-tensors are multilinear maps which eat $p$ covectors and $q$ vectors and spits out a $\mathbb K$-number.
The linear maps from $V^*\rightarrow \mathbb K$ are not elements of $V$, but rather elements of $V^{**}$, the algebraic dual of $V^*$.  However, given any vector $X\in V$, we can define a unique map $f_X\in V^{**}$ to be the one which eats a covector $\omega$ and spits out $$f_X(\omega) := \omega(X)$$
This association $X\mapsto f_X$ between $V$ and $V^{**}$ is one-to-one, and so natural and obvious that we tend to think of elements of $V$ as simply being elements of $V^{**}$.  That is what is meant by the statement that vectors can be thought of as functions of covectors - in reality, a vector $X$ is not a function of a covector, but rather can be uniquely associated to a function of a covector $f_X$ in a very natural way.
For finite-dimensional $V$, this association is also surjective, so there is a one-to-one pairing between elements of $V$ and elements of $V^{**}$, which makes it even more reasonable to say that elements of $V$ simply are elements of $V^{**}$.  In infinite-dimensional spaces, such as those encountered in QM, this isn't true.

In saying this, my intention is not to merely engage in pointlessly self-indulgent mathematical technicality.

What is the advantage of thinking of vectors as functions over thinking of them as objects that have independent existence but whose components transform in a particular way?

You can certainly think of vectors that way.  The key point is that they have a basis-independent existence, which can be captured by (i) endowing their components with the right transformation properties, or (ii) talking about them with no reference to a particular basis at all.  In most circumstances, I prefer the latter approach when possible, but that's more a personal preference than an indictment of the former.
It's also worth noting that thinking of tensors as objects which eat covectors and vectors and spit out numbers is nothing you aren't already intuitively familiar with, in the sense that you know that contracting all the indices in an expression yields a scalar.
To me, it also makes understanding the transformation properties of tensor components far cleaner.  For example, the metric tensor $g$ is a map which eats two vectors and spits out a number.  If I pick some basis $\{\hat e_\mu\}$ and plug $\hat e_\mu$ and $\hat e_\nu$ into the slots of $g$, I get $g(\hat e_\mu,\hat e_\nu) \equiv g_{\mu\nu}$.
That's what the components $g_{\mu\nu}$ are - they are the result of feeding elements of a chosen basis to the tensor $g$.  Not only does this make it obvious that the components of a tensor are basis-dependent, but it makes it clear what to do when changing basis from $\hat e_\mu \mapsto \hat \epsilon_\mu = R^\nu_{\ \ \mu} \hat e_\nu$:
$$g'_{\mu\nu} \equiv g\big(\hat \epsilon_\mu,\hat \epsilon_\nu\big) = g\big(R^\alpha_{\ \ \mu}\hat e_\alpha,R^\beta_{\ \ \nu} \hat e_\beta\big) = R^\alpha_{\ \ \mu} R^\beta_{\ \ \nu} g(\hat e_\alpha,\hat e_\beta) \equiv R^\alpha_{\ \ \mu}R^\beta_{\ \ \nu}g_{\alpha\beta}$$
where we freely used the multilinearity of $g$.
This may all be perfectly obvious and natural to you if you have a lot of experience manipulating components, but for me it provides a very clean and natural understanding of the objects I'm manipulating.

A: I'll direct you to a post I made on a question of a more technical nature, detailing exactly the mathematical definition of a tensor that was most helpful for my understanding.
The short of it is that saying "tensors are certain linear algebraic objects that transform in a certain way" is deeply unsatisfying when one wishes to go anywhere beyond a topical understanding of the subject. It does not give any intuition as to why that method of transformation ought to be preferred, and it entirely useless in developing the theory of manifolds (tensors' appearance there is exactly why they show up in GR).
Another critique of the "transformation" formalism is that it is a basis-dependent way of describing basis-transcendent phenomena. If you are to write down the definition of a tensor the conventional, physicist way, you need to choose a basis, but in the mathematical understanding, this is unnecessary.
To the title of your question, as I mention in the post I linked above that the understanding of vectors as tensors is almost entirely useless. It is more accurate to say that a vector describes a tensor, and it usually turns out the resulting tensor is wholly uninteresting (i.e. is unrelated to the starting vector, or any properties of interest about the space).


text:
Q: Merge missing XML records based on Empty XML example I have an XML template file and a previously saved XML database record:

*

*XML file - contains all the current fields I want for an object - This may change over time with items added

*XML database record - this is the saved XML.  It may be different from the XML in point one because the "template" xml may have been updated to contain more fields, etc.

An example will clear this up..
I have a "template" xml that looks like this:

<dvd displayText="">
  <field id="txtTitle" displayText="true" required="true" type="textbox" width="100" label="DVD Title" />
  <field id="txtDescription" displayText="true" required="true" type="textbox" width="50" label="Your Description" />
</dvd>

This tells the UI to collect a Title and Description when creating a new record.  This works perfectly.
So when I create a new DVD record it will display these 2 fields to the user and collect the "Title" and "Description" values and save the value into an XML field in a SQL Server table.
But what I want to do now is add a new "field" definition to the template xml.  I've done this.. for the purposes of this example, lets have a "PurchasedDate" field definition added to the template XML.

<dvd displayText="">
  <field id="txtTitle" displayText="true" required="true" type="textbox" width="100" label="DVD Title" />
  <field id="txtDescription" displayText="true" required="true" type="textbox" width="50" label="Your Description" />
  <field id="txtPurchaseDate" displayText="true" required="true" type="textbox" width="50" label="Purchase Date" />
</dvd>

If I'm creating a new DVD record, I get prompted for the 3 values; Title, Description, Purchased Date, because that's whats in the template XML..  But if I'm recalling a previously saved DVD record, it doesn't have the new "Purchased Date" field in the XML..

<dvd displayText="My DVD">
  <field id="txtTitle" displayText="true" required="true" type="textbox" width="100" label="DVD Title">My Movie DVD</field>
  <field id="txtDescription" displayText="true" required="true" type="textbox" width="50" label="Your Description">This movie is awesome</field>
</dvd>

So what I want to do is take the XML saved in the database (shown above), compare or merge any missing "field" definitions from the template XML file.. and end up with this below:

<dvd displayText="My DVD">
  <field id="txtTitle" displayText="true" required="true" type="textbox" width="100" label="DVD Title">My Movie DVD</field>
  <field id="txtDescription" displayText="true" required="true" type="textbox" width="50" label="Your Description">This movie is awesome</field>
  <field id="txtPurchaseDate" displayText="true" required="true" type="textbox" width="50" label="Purchase Date" />
</dvd>

I'm using Linq to get the value from the existing record from the database if one exists.
and I'm currently doing a XmlDocument.LoadXml(xmlstring) or XmlDocument.Load(filename) depending on whether its new or existing record.
I'd then like to take the XmlDocument and merge the template into this to produce the above XML output for displaying on screen.
If there is a better way than using XmlDocuments, can you please let me know..  I'll happily go and research it and then use it..
I'm using C#...
Many thanks..

A: Your solution has a huge redundancy problem, you will face similar problems if you for instance alters the display text for one of the fields, or change the required field.
I would separate the metadata from the actual data, i.e. keep one record that describes the fields:
<dvd displayText="">
  <field id="txtTitle" displayText="true" required="true" type="textbox" width="100" label="DVD Title" />
  <field id="txtDescription" displayText="true" required="true" type="textbox" width="50" label="Your Description" />
  <field id="txtPurchaseDate" displayText="true" required="true" type="textbox" width="50" label="Purchase Date" />
</dvd>

And strip the data records down to field ids and values:
<dvd displayText="A movie">
  <field id="txtTitle">Some title</field>
  <field id="txtDescription">Some description</field>
  <field id="txtPurchaseDate">2012-12-21</field>
</dvd>

Use the meta xml to figure out what fields are possible to load and get the values from the stripped down xml.
Otherwise you will need to sync all data every time your record layout changes.


text:
Q: QGIS 3.4.14-1 start menu is empty I am using Win7.  I had QGIS 3.4.12.1 standalone installed with QGIS-OSGeo4W-3.4.12-1-Setup-x86_64.exe.
I downloaded new LTR standalone version QGIS-OSGeo4W-3.4.14-1-Setup-x86_64.exe.
This setup asks for uninstalling my previous one.
I acepted, and anfter removing previous version, new one is not present in start menu.  I can find QGIS 3.4 entry, but is empty.
I uninstalled both versions and cleaned registry form older QGIS versions but new installation have the same problem.
How should I install 3.4.14-1 version in Windows 7?

Clarifications:
Installation is ready. No error messages. Only start menu is empty.
Qgis runs when I rename qgis-ltr.bat.tmpl to qgis-ltr.bat.
But it seems to be that something is wrong with start menu. Qgis 3.4 menu is created empty and no icons in desktop. QGIS 3.4 is present in Start menu and as a directory in desktop. But both are empty.


text:
Q: Rails - Add style/image to button_to I'm developing in rails right now and I was wondering if there are any easy ways to add some style to the button_to control.
Can you add styling to the
 <%= submit_tag 'Log in' %>

or
 <%= button_to "Show Me", {:controller => 'personal', :action => "add" } %>

It would be great to change the color....But brownie point if someone can tell me how to make it an image

A: In addittion to Mike's very fine pointer to using a pre-defined :class, you can also go for :style and define the CSS inline. Helps a great deal if you want to define your style on the fly:
<%= button_to "Show Me", {:controller => 'personal', :action => "add" }, {:style => "background: #{obj.colourname}" } %>
(With obj being some model instance that stores some HTML colour value at the colourname attribute.)

A: Since you're using an image, there is no reason to use button_to instead of link_to, "button look" will be lost to the user.  You can create an image with a link like so:
<%= link_to image_tag("rails.png"), {:controller => 'foo', :action => "bar" } %>

If, for some reason, you need to use button_to, you can give it a CSS class and apply some styles via that:
 <%= button_to "Show Me", {:controller => 'personal', :action => "add" }, {:class => "buttonTo" } %>


text:
Q: Converting EC PublicKey Hex String to PublicKey While performing Elliptic Curve cryptography with secp256k1 curve, I noticed that while the code and test cases compile on the Android Studio IDE they do not compile on the android device since the curve isn't defined in the jre/jdk that the mobile device uses. Changing the curve to a prime256v1 I seem to be facing difficulties in converting a hex string of the publicKey to PublicKey object.
Given the hex string of a PublicKey.getEncoded() which is in a database. I want an android client to convert the byte[] from converting the hex string into a PublicKey object. I am converting the byte[] using X509EncodedKeySpec() as follows:
public static PublicKey getPublicKey(byte[] pk) throws NoSuchAlgorithmException, InvalidKeySpecException {
    EncodedKeySpec publicKeySpec = new X509EncodedKeySpec(pk);
    KeyFactory kf = KeyFactory.getInstance("EC");
    PublicKey pub = kf.generatePublic(publicKeySpec);
    return pub;
}

The conversion from a hex string to a byte[] happens as follows:
public static byte[] hexStringToByteArray(String hexString) {
    byte[] bytes = new byte[hexString.length() / 2];

    for(int i = 0; i < hexString.length(); i += 2){
        String sub = hexString.substring(i, i + 2);
        Integer intVal = Integer.parseInt(sub, 16);
        bytes[i / 2] = intVal.byteValue();
        String hex = "".format("0x%x", bytes[i / 2]);
    }
    return bytes;
}

The conversion from a byte[] to Hex string is as follows:
public static String convertBytesToHex(byte[] bytes) {
    char[] hexChars = new char[bytes.length * 2];
    for ( int j = 0; j < bytes.length; j++ ) {
        int v = bytes[j] & 0xFF;
        hexChars[j * 2] = hexArray[v >>> 4];
        hexChars[j * 2 + 1] = hexArray[v & 0x0F];
    }
    return new String(hexChars).toLowerCase();
}

However when I run this on the android app (7.0, API 24) I get the following System Error
W/System.err: java.security.spec.InvalidKeySpecException: java.lang.RuntimeException: error:0c0000b9:ASN.1 encoding routines:OPENSSL_internal:WRONG_TAG
                  at com.android.org.conscrypt.OpenSSLKey.getPublicKey(OpenSSLKey.java:295)
                  at com.android.org.conscrypt.OpenSSLECKeyFactory.engineGeneratePublic(OpenSSLECKeyFactory.java:47)
                  at java.security.KeyFactory.generatePublic(KeyFactory.java:357)

What is the recommended approach for converting a Hex string to a PublicKey for EC instance on an android device.
Here's sample code that you can execute:
ECDSA.java
public class ECDSA {

    public static KeyPair generateKeyPair() throws NoSuchAlgorithmException, InvalidAlgorithmParameterException {
        KeyPairGenerator keyGen = KeyPairGenerator.getInstance("EC");
        ECGenParameterSpec ecSpec = new ECGenParameterSpec("prime256v1");
        SecureRandom random = SecureRandom.getInstance("SHA1PRNG");
        keyGen.initialize(ecSpec, random);
        KeyPair pair = keyGen.generateKeyPair();
        return pair;
    }

    public static PublicKey getPublicKey(byte[] pk) throws NoSuchAlgorithmException, InvalidKeySpecException {
        EncodedKeySpec publicKeySpec = new X509EncodedKeySpec(pk);
        KeyFactory kf = KeyFactory.getInstance("EC");
        PublicKey pub = kf.generatePublic(publicKeySpec);
        return pub;
    }

    public static PrivateKey getPrivateKey(byte[] privk) throws NoSuchAlgorithmException, InvalidKeySpecException {
        EncodedKeySpec privateKeySpec = new X509EncodedKeySpec(privk);
        KeyFactory kf = KeyFactory.getInstance("EC");
        PrivateKey privateKey = kf.generatePrivate(privateKeySpec);
        return privateKey;
    }
}

MainActivity.java
public class MainActivity extends AppCompatActivity {

    KeyPair keyPair = ECDSA.generateKeyPair();
    PublicKey publicKey = keyPair.getPublic();
    PrivateKey privateKey = keyPair.getPrivate();
    // Converting byte[] to Hex
    publicKeyHex = convertBytesToHex(publicKey.getEncoded());
    privateKeyHex = convertBytesToHex(privateKey.getEncoded());
    // Trying to convert Hex to PublicKey/PrivateKey objects
    PublicKey pkReconstructed = ECDSA.getPublicKey(hexStringToByteArray(publicKeyHex));
    PrivateKey skReconstructed = ECDSA.getPrivateKey(hexStringToByteArray(privateKeyHex));
    // This throws an error when running on an android device
    // because there seems to be some library mismatch with
    // java.security.* vs conscrypt.OpenSSL.* on android.
}

A: Finally we get a real MCVE and we can now see that you are not using the correct class for encoded private keys. X509EncodedKeySpec is only for public keys. From the javadocs (emphasis mine):

This class represents the ASN.1 encoding of a public key, encoded
  according to the ASN.1 type SubjectPublicKeyInfo.

For private keys, the correct encoding is usually a PKCS8EncodedKeySpec. The encoding can be determined by examining the output of Key.getFormat(). Therefore, change your method getPrivateKey of ECDSA to
public static PrivateKey getPrivateKey(byte[] privk) throws NoSuchAlgorithmException, InvalidKeySpecException {
        EncodedKeySpec privateKeySpec = new PKCS8EncodedKeySpec(privk);
        KeyFactory kf = KeyFactory.getInstance("EC");
        PrivateKey privateKey = kf.generatePrivate(privateKeySpec);
        return privateKey;
    }


text:
Q: Windows Server 2008 R2 Print Server - Change Printer Names on All Client Systems I have a Windows Server 2008 R2 print server set up hosting out multiple printers to my end users. I would like to change the naming convention for all of the printers hosted on the print server and want this change reflected on the client end.
For example: I have a HP4000 printer named "Cottage" on the print server. I want to rename the printer "HR-1stFloor-220a" on the print server and I want this printer to appear on every client system with the new name.
Simply renaming the printer on the server automatically creates a link from the old printer name to the new one, so all the clients work but the actual name, from their perspective, has not changed. Renaming the share name also does not visibly effect the end user (though it does update the port information).
I would like to have the names of the printers be meaningful information regarding department and location, but this means that when they change hands or move I would need to update this information, and currently I am not seeing a way short of writing custom start-up scripts and remove/replacing them through AD. Is there a simple way of accomplishing this task?
Thank you for your help.

A: You're relegated to scripts, third-party printer management tools, or changing the printer display name, so it looks like the printer is actually named correctly.  (And for what it's worth, I don't know of any third-party tools for this that I actually consider worth using, so I end up using AD and GPOs to handle this.)
There's really no way around the pain, at least the first time, so I'd suggest using the opportunity to introduce some manageability and automation to this part of your environment, and for what it's worth, I'm in the same boat myself.  And, as you should always do, document the hell out of this so you don't have to remember or relearn all this later.
I'm handling this as below.

*

*Create an Active Directory security group for each printer, such as Users of [printer name].

*

*This is an opportunity to work on your delegation or scripting skills in an environment with many printers, FYI  Learning PowerShell, or making the helpdesk guys learn PowerShell comes in handy.

*Populate security group with users of the printers.

*

*There are a number of ways to handle this, I've been using logon scripts to poll users for what printers they have installed.

*Create GPO(s) and/or logon script(s) that maps the printers to the appropriate users.

*

*There are so many different approaches to this, and their usefulness is just so environment-dependent, I can't really recommend one.

*Replace whatever mechanism you currently use to map printers with the GPO(s) or logon script(s).

*

*Slowly, use a phased appraoch.  If you do it all at once, and something goes wrong, everyone will hate you, and you may even hate yourself for making such a rookie mistake.  Everyone.

*Replace old printer names with new names, update GPO(s) and/or logon script(s) to match.

*

*Again, best to use a phased approach.

It's a good idea to give as many people as much advance warning as possible.  Invariably something will go wrong, some users will get missed, or some printer will fail to get shared back out properly.  Giving the heads up makes people more forgiving, and prevents time spent by the others on your team from hunting for the cause of any printer share problems this will create.


text:
Q: How to make CLI applications in Unix? How are apps like vim and w3m built? I was trying to find info about this online but I couldn't really find much.

A: You could check the project's source code repositories. For instance, the vim source code can be found at: https://github.com/vim/vim
However, you probably want to start a few steps earlier, as such large and grown projects tend to be very complicated.
But I don't think this was your intended question. I assume you are rather interested in how to create terminal UIs. Behind the scenes this is basically writing a bunch of magic characters with printf which make the terminal do stuff like switching to alternative buffers or printing in different colors. There is even a Wikipedia page on the codes. But normally you would use a library that is abstracting away the low level parts like ncurses.
For more details, you could for instance check this article which looks like it answers your actual question.


text:
Q: Is there any way to read .docx file include auto numbering using python-docx Problem statement: Extract sections from .docx file including autonumbering.
I tried python-docx to extract text from .docx file but it excludes the autonumbering.
from docx import Document

document = Document("wadali.docx")

def iter_items(paragraphs):
    for paragraph in document.paragraphs:
        if paragraph.style.name.startswith('Agt'):
            yield paragraph
        if paragraph.style.name.startswith('TOC'):
            yield paragraph
        if paragraph.style.name.startswith('Heading'):
            yield paragraph
        if paragraph.style.name.startswith('Title'):
            yield paragraph
        if paragraph.style.name.startswith('Heading'):
            yield paragraph
        if paragraph.style.name.startswith('Table Normal'):
            yield paragraph
        if paragraph.style.name.startswith('List'):
            yield paragraph

for item in iter_items(document.paragraphs):
    print item.text

A: It appears that currently python-docx v0.8 does not fully support numbering. You need to do some hacking.
First, for the demo, to iterate the document paragraphs, you need to write your own iterator.
Here is something functional:
import docx.document
import docx.oxml.table
import docx.oxml.text.paragraph
import docx.table
import docx.text.paragraph

def iter_paragraphs(parent, recursive=True):
    """
    Yield each paragraph and table child within *parent*, in document order.
    Each returned value is an instance of Paragraph. *parent*
    would most commonly be a reference to a main Document object, but
    also works for a _Cell object, which itself can contain paragraphs and tables.
    """
    if isinstance(parent, docx.document.Document):
        parent_elm = parent.element.body
    elif isinstance(parent, docx.table._Cell):
        parent_elm = parent._tc
    else:
        raise TypeError(repr(type(parent)))

    for child in parent_elm.iterchildren():
        if isinstance(child, docx.oxml.text.paragraph.CT_P):
            yield docx.text.paragraph.Paragraph(child, parent)
        elif isinstance(child, docx.oxml.table.CT_Tbl):
            if recursive:
                table = docx.table.Table(child, parent)
                for row in table.rows:
                    for cell in row.cells:
                        for child_paragraph in iter_paragraphs(cell):
                            yield child_paragraph

You can use it to find all document paragraphs including paragraphs in table cells.
For instance:
import docx

document = docx.Document("sample.docx")
for paragraph in iter_paragraphs(document):
    print(paragraph.text)

To access the numbering property, you need to search in the "protected" members paragraph._p.pPr.numPr, which is a docx.oxml.numbering.CT_NumPr object:
for paragraph in iter_paragraphs(document):
    num_pr = paragraph._p.pPr.numPr
    if num_pr is not None:
        print(num_pr)  # type: docx.oxml.numbering.CT_NumPr

Note that this object is extracted from the numbering.xml file (inside the docx), if it exists.
To access it, you need to read your docx file like a package. For instance:
import docx.package
import docx.parts.document
import docx.parts.numbering

package = docx.package.Package.open("sample.docx")

main_document_part = package.main_document_part
assert isinstance(main_document_part, docx.parts.document.DocumentPart)

numbering_part = main_document_part.numbering_part
assert isinstance(numbering_part, docx.parts.numbering.NumberingPart)

ct_numbering = numbering_part._element
print(ct_numbering)  # CT_Numbering
for num in ct_numbering.num_lst:
    print(num)  # CT_Num
    print(num.abstractNumId)  # CT_DecimalNumber

Mor information is available in the Office Open XMl documentation.

A: There is a package, docx2python which does this in a lot simpler fashion: pypi.org/project/docx2python/
The following code:
from docx2python import docx2python
document = docx2python("C:/input/MyDoc.docx")
print(document.body)

produces a list which contains the contents including bullet lists in a nice parse-able fashion.


text:
Q: No Module Named 'delta.tables' I am getting the following error for the code below, please help:
   from delta.tables import *
   ModuleNotFoundError: No module named 'delta.tables'
   INFO SparkContext: Invoking stop() from shutdown hook

Here is the code:
'''
   from pyspark.sql import *

   if __name__ == "__main__":
     spark = SparkSession \
        .builder \
        .appName("DeltaLake") \
        .config("spark.jars", "delta-core_2.12-0.7.0") \
        .config("spark.sql.extensions", "io.delta.sql.DeltaSparkSessionExtension") \
        .config("spark.sql.catalog.spark_catalog", "org.apache.spark.sql.delta.catalog.DeltaCatalog") \
        .getOrCreate()

    from delta.tables import *

    data = spark.range(0, 5)

   data.printSchema()

'''
An online search suggesting verifying the scala version to delta core jar version. Here is the scala & Jar versions
"delta-core_2.12-0.7.0"
"Using Scala version 2.12.10, Java HotSpot(TM) 64-Bit Server VM, 1.8.0_221"

A: or you can also
pip install delta-spark

delta-spark pip page

A: According to delta package documentation, there is a python file named tables.
You should clone the repository and copy the delta folder under python/delta to your site packages path (i.e. ..\python37\Lib\site-packages). then restart python and your code runs without the error.
I am using Python3.5.3,
pyspark==3.0.1,

A: There is a difference between spark.jars and spark.jars.packages. Since you are following the Quick Start, try replacing
.config("spark.jars", "delta-core_2.12-0.7.0")

with
.config("spark.jars.packages", "io.delta:delta-core_2.12:0.7.0")


text:
Q: NodeJS converts passed html content to entities by default In my website I want to have a tree of categories. To get this to work, I need to arrange them in a parent-child tree through a recursive loop. What I did was to fetch the category data from the database, run the loop and generate the output HTML content inside of the NodeJS code. Then I pass the generated HTML string to my EJS document to be shown in the browser.
Now here is the problem: the generated string is just how it should be as long as it is inside the NodeJS function. But the string that is passed on has some characters converted into identities, and I couldn't find a way to convert them back. For eg:

Hello world

becomes
<h1>Hello world</h1>
inside the ejs document, but when I try to print the string using console.log inside of some js file, it prints the correct HTML string instead of the converted one.

A: You should use <%- as the opening tag for this as it outputs the unescaped value into the page.
See the 'Tags' section in the EJS docs for more reference
https://ejs.co/#docs


text:
Q: Fitting problem I have two points stored in data:
data = {{0.0166667, 2.86927*10^-12}, {0.0333333, 1.12725*10^-11}};

data[[All,1]] contains the time t.
data[[All,2]] contains the first 2 points of the so called mean squared displacement.
To calculate the particle mass m the 2 points should be fitted with the following function:
k * T / m * t^2 (* fitting function *)

k = 1.3806488*10^-23;
T = 300;
(* m = particle mass in kg, is the fitting parameter *)

Manually I get a good fit if I take m = 4.1 * 10^-13kg.
dataPlot =
 ListLinePlot[data, PlotStyle -> {Blue},
  Epilog -> {PointSize[Medium], Point[data]}];
manualFitPlot =
  Plot[k*300/(4.1*10^-13)*t^2, {t, 1/60, 2/60}, PlotStyle -> {Green}];
Show[dataPlot, manualFitPlot, PlotRange -> All]

When I try to use NonlinearModelFit a wrong result for the mass is obtained:
nlm = NonlinearModelFit[data, k*300/m*t^2, {m}, t];
nlm["ParameterTable"]

$\small \begin{array}{l|llll}
 \text{} & \text{Estimate} & \text{Standard Error} & \text{t-Statistic} & \text{P-Value} \\
\hline
 m & 0.422029 & 4.36728\times 10^{11} & 9.66343 \times 10^{-13} & 1 \\
\end{array}$
I tried different initial values for m and also rescaled the small values by multiplying with (*10^10). It did not help.
How can I solve this?

A: I wouldn't be so quick to rule out rescaling your data or working in reduced units, since this works fine:
data = {{0.0166667, 2.86927*10^-12}, {0.0333333, 1.12725*10^-11}};
k = 1.3806488*10^-23;
T = 300;
nlm = NonlinearModelFit[data, k*300/(m*10^-13)*t^2, {m}, t,
   Method -> "NMinimize"];

(* Gives m = 4.07829 *)

I think the problem really lies with the numbers being so small that the default gradient-based fitting methods evaluate the gradient as zero in machine precision.
So NMinimize works, as does PrincipalAxis, since both involve derivative-free methods. You can look into it further in the documentation.

Note that you can also do it without scaling, but specifying a starting value (this time using the PrincipalAxis method, which takes two starting values).
nlm = NonlinearModelFit[data, k*300/m*t^2, {{m, 10^-14, 5*10^-13}}, t,
         EvaluationMonitor :> Print["x = ", m],
         Method -> "PrincipalAxis"];
(* Gives m = 4.09157*10^-13 *)
(* Also outputs the steps *)

A: Just a quick glance, you can try this though. I didn't have time to plot the residuals (or take a look at them for that matter...no pun intended) but it could be worth taking a look at. The function seems to predict your data points with relative accuracy.

A: This model is linear in 1/m, hence use LinearModelFit
lm = LinearModelFit[data, {k*300 t^2}, t, IncludeConstantBasis -> False]

Then just invert the result:
1/lm["BestFitParameters"][[1]]

that gives
4.07829*10^-13

If you give different weights to each point, you will find another result. The "best" result will be obtained with proper weighting.


text:
Q: Using global from different modules I have a modular project, where the main module (entrypoint) is written in javascript, meanwhile some auxiliary libs are in typescript.
The javascript module, when starts, assign some set of variables, using global.
The problem is I don't to share this variables with the typescript libs.
It runs, but I'm getting some error when publishing:
Element implicitly has an 'any' type because type 'typeof globalThis' has no index signature.
The javascript set these variables as below:
static loadProperties() {
    global.myProperties = new Map();
    global.myProperties.set('SOME_VARIABLE', 'someValue');
}

The typescript lib uses it as following:
const someVariable: string = global.myProperties.get('SOME_VARIABLE');

But when running the npm run compile command, throws the exception mentioned before.

A: since you global really don't have any such attribute
I really don't recommend using global. but if you want to, here's how:
global.d.ts:
declare namespace NodeJS {
  export interface Global {
    myProperties: Map<unknown, unknown>
  }
}

// and / or top-level module
declare var myProperties: Map<unknown, unknown>

In addition, your code has a syntax error:
static loadProperties() {
    global.myProperties = new Map();
    // global.myProperties.set('SOME_VARIABLE') = 'someValue';
    global.myProperties.set('SOME_VARIABLE', 'someValue');
}


text:
Q: Error 403 on Heroku when deploying a Django project I want to delete the repository inside my Heroku app by typing:
heroku plugins:install heroku-repo
heroku repo:reset -a appname

After that I get the error:
Expected response to be successful, got 403


text:
Q: Apply a bearing to GoogleMap camera bounds I'm working on an application that uses Google Maps API.
My map is displayed with a defined bearing and rotation/compass are disabled.
I'd like to add Camera Bounds to my map so that the user does not leave the area of interest.
However the API seems to provide only one method for that, which is
GoogleMap.setLatLngBoundsForCameraTarget(LatLngBounds)

The issue is that LatLngBounds are "boxes" aligned with latitude and longitude.
So on my map that has a bearing, the camera bounds have a diamond shape instead of a square one, which is a bit weird.
Is there a way I can set some Camera Bounds that are not Latitude/Longitude aligned ?
I thought of writing a workaround with a CameraMoveListener that would trigger a CameraUpdate, but it's a bit of work for a result that I believe would be not that great in term of user experience.