text:
Q: Biopython retrieving particular CDS from a whole genome I am new to Stackoverflow. I am trying to automate search process using Biopython. I have two lists, one with protein GI numbers and one with corresponding nucleotide GI numbers.
For example:
protein_GI=[588489721,788136950,409084506]
nucleo_GI=[588489708,788136846,409084493]
Second list was created using ELink. However, the nucleotide GIs correspond to whole genomes. I need to retrieve particular CDS from each genome which match the protein GI.
I tried using again ELink with different link names ("protein_nucleotide_cds","protein_nuccore") but all I get is id numbers for whole genomes. Should I try some other link names?
I also tried the following EFetch code:
import Bio
from Bio import Entrez
Entrez.email = None

handle=Entrez.efetch(db="sequences",id="588489708,588489721",rettype="fasta",retmode="text")
print(handle.read())

This method gives me nucleotide and protein sequences in fasta file but the nucleotide sequence is a whole genome.
I would be very grateful, if somebody could help me.
Thanking you in advance!

A: I hope help you
import Bio
from Bio import Entrez
from Bio import SeqIO
Entrez.email = "mail@example.com"

gi_protein = "GI:588489721"
gi_genome = "GI:588489708"

handle=Entrez.efetch(db="sequences", id=gi_protein,rettype="fasta", retmode="text")
protein = SeqIO.parse(handle, "fasta").next()

handle=Entrez.efetch(db="sequences", id=gi_genome, rettype="gbwithparts", retmode="text")
genome = SeqIO.parse(handle, "gb").next()

#to extract feature with 'id' equal to protein
feature = [f for f in gb.features if "db_xref" in f.qualifiers and gi_protein in f.qualifiers["db_xref"]]

#to get location of CDS
start = feature[0].location.start.position
end = feature[0].location.end.position
strand = feature[0].location.strand

seq = genome[start: end]

if strand == 1:
  print seq.seq
else:
  #if strand is -1 then to get reverse complement
  print seq.reverse_complement().seq

print protein.seq

then you get:

ATGGATTATATTGTTTCAGCACGAAAATATCGTCCCTCTACCTTTGTTTCGGTGGTAGGG
CAGCAGAACATCACCACTACATTAAAAAATGCCATTAAAGGCAGTCAACTGGCACACGCC
TATCTTTTTTGCGGACCGCGAGGTGTGGGAAAGACGACTTGTGCCCGTATCTTTGCTAAA
ACCATCAACTGTTCGAATATATCAGCTGATTTTGAAGCGTGTAATGAGTGTGAATCCTGT
AAGTCTTTTAATGAGAATCGTTCTTATAATATTCATGAACTGGATGGAGCCTCCAATAAC
TCAGTAGAGGATATCAGGAGTCTGATTGATAAAGTTCGTGTTCCACCTCAGATAGGTAGT
TATAGTGTATATATTATCGATGAGGTTCACATGTTATCGCAGGCAGCTTTTAATGCTTTT
CTTAAAACATTGGAAGAGCCACCCAAGCATGCCATCTTTATTTTGGCCACTACTGAAAAA
CATAAAATACTACCAACGATCCTGTCTCGTTGCCAGATTTACGATTTTAATAGGATTACC
ATTGAAGATGCGGTAGGTCATTTAAAATATGTAGCAGAGAGTGAGCATATAACTGTGGAA
GAAGAGGGGTTAACCGTCATTGCACAAAAAGCTGATGGAGCTATGCGGGATGCACTTTCC
ATCTTTGATCAGATTGTGGCTTTCTCAGGTAAAAGTATCAGCTATCAGCAAGTAATCGAT
AATTTGAATGTATTGGATTATGATTTTTACTTTAGGTTGGTGGATGCTTTTCTGGCAGAA
GATACTACACAAACACTATTGATTTTTGATGAGATATTGAAACGGGGATTTGATGCACAT
CATTTTATTTCCGGTTTAAGTTCTCATTTGCGTGATTTACTTGTATGTAAGGATGCAGCC
ACCATTCAGTTGCTGGATGTGGGTGCTAAAATTAAGGAGAAGTACGGTGTTCAGGCGCAA
AAAAGTACGATTGACTTTTTAATGGATGCTTTAAATATTACCAACGATTGCGATTTGCAA
TATAGGGTGGCTAAAAATAAGCGTTTGCATGTGGAGTTTGCTCTTCTTAAGATAGCACGT
GTATTAGATGAACAAAGAAAAAAGTAG

MDYIVSARKYRPSTFVSVVGQQNITTTLKNAIKGSQLAHAYLFCGPRGVGKTTCARIFAK
TINCSNISADFEACNECESCKSFNENRSYNIHELDGASNNSVEDIRSLIDKVRVPPQIGS
YSVYIIDEVHMLSQAAFNAFLKTLEEPPKHAIFILATTEKHKILPTILSRCQIYDFNRIT
IEDAVGHLKYVAESEHITVEEEGLTVIAQKADGAMRDALSIFDQIVAFSGKSISYQQVID
NLNVLDYDFYFRLVDAFLAEDTTQTLLIFDEILKRGFDAHHFISGLSSHLRDLLVCKDAA
TIQLLDVGAKIKEKYGVQAQKSTIDFLMDALNITNDCDLQYRVAKNKRLHVEFALLKIAR
VLDEQRKK


text:
Q: In Crystal, how can you tell if a file is text or binary? If you have 2 files, one text and the other binary, is it possible to determine which is a text file and which is a binary using Crystal?

A: You can use Magic Numbers to detect binary files otherwise it could be a plain text file.

is it possible to determine which is a text file and which is a binary using Crystal?

If you assume "binary" is an ELF file, then you can try this:
def filetype(filename)
  unless File.file?(filename)
    puts "Isn't a file!"
    return
  end
  File.open(filename, "r") do |f|
    case f.gets(4)
    when "\x7FELF" then puts "Is an ELF binary file"
    # when "GIF8" then puts "Is a GIF"
    # when "\x25\x50\x44\x46" then puts "Is a PDF"
    # ... and so on
    else
      puts "Probably is a plain text file"
    end
  end
end

File.write("plain.txt", "Plain Text File")

filetype("plain.txt")   # => Probably is a plain text file
filetype("/usr/bin/ls") # => Is an ELF binary file
filetype("/dev/sda")    # => Isn't a file!

This works even on non-executable ELF files (without x permission). If you want to detect executable files then use File.executable?.
Demo here: https://carc.in/#/r/44a2
Also file is a nice command that uses libmagic under the hood to detect magic numbers and get the right file type. You can do some bindings to libmagic using Crystal as well, so you don't need to specify all magic numbers by yourself.

A: I suppose, it's impossible, using native Crystal. To determine type of a file, it needs to read a part of a file and guess its type on the content basis. This can be a tricky part, so if you need a relatively reliable solution, I'd suggest invoke file --mime-type -b <file> from Crystal and parse the output, though it makes mistakes sometimes too.
Additionally you can use crystal-mime shard to handle the output of file command.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to extract a string with a regexp? Can I extract the string aaa without using subpatterns (but still using regexp)?
$str = 'abc#aaa#abc';
preg_match('/#(.*)#/', $str, $matches);
print_r($matches);

Update

*

*lookahead and lookbehind is a second solution, any other ?

I'm just trying to figure out some regexp alternatives !

A: /(?<=#).*?(?=#)/
But why wouldn't you want to use a capturing group?

A: Alternative to look-ahead / look-behind assertions:
echo preg_replace('/^.*?#|#.*?$/s', '', 'abc#aaa#abc');


text:
Q: Capture sound card line out in C++ I try to learn how to record sound from PC devices. I found an example which shows how to record sound from mic. But cannot find example how to record from sound card line out.
Please if you can help me, show me example, or give me good links, because I searched a lot and didnt found that. I'm working with Visual C++ , C++ Builder, Delphi.  Thanks.


text:
Q: Android Market Statistic Sometimes statistics Android Market makes me wonder. When app have total installs ~10000-12000 it have only 45-55% active installs. What a ratio of quantities? In most cases, the application has good reviews (4.5 stars). Why active installs are only ~50%?
Look for example one of my app statistics:
Total: 12777
Active: 6158 (48%)
What you can say about this problem?
What statistics you have, what ratio between Total and Active installs you have?

A: 254 total, 58 active (22%). It's a work in progress, but the basic functionality is sound. At the end of the day, I'd be more concerned if the active installs go down over time or you get lots of bad reviews.

What can you say about this problem?

What can I say? You're never going to please everybody, and with free apps/refunds on paid apps, you will get lots of people testing the water, deciding they don't like your app for whatever reason, and uninstalling it.
I know it doesn't do much for your ego - look at my stats for example - but that's life. You've had 12,777 people gice your app a try, and 6,158 keep it on their device. I think it's wrong to look at that as 6,619 people didn't like my app when you should be thinking of it as 6,158 people like my app enough to keep it installed. Or at the very least, 6,158 don't hate it enough to remove it.
The fact is, you have thousands of people using your app. Unfortunately there's no way to get feedback on why people remove it. What do the Market comments say? Do you notice a pattern of neutral/negative comments?
You could possibly try using something like Google Analytics in an attempt to notice a usage pattern to try to work out if there's something that people don't like.
Whatever you do, there's going to be a lot of guesswork involved and there's no easy answer.
Having said all that, I think 48% active installs is actually probably pretty good. The consensus in this thread suggests that the top dozen apps have active install ratios of about 75% or more, while the top 100 free apps have a retention ratio of around 50% or more. Everything else hovers around 50% for a month or so and then drops to around 30%.
Of course, that thread also mentions a bug in the reporting of active installs from September 2010, but there's no word on whether it's fixed or not. Either way, it looks like your app is actually doing quite well compared to others - I wouldn't worry too much about it.

A: 8250 total
4995 active installs (60 %)
I guess the percentage goes down while people download app. At first it was like 80-90%


text:
Q: JVM terminated with Exit Code 1 while accessing JFrame I am using Eclipse Mars Ide on Ubuntu 15.10. When I was trying to create JFrame, Eclipse is trying to initialize design and while initializing, it suddenly stops and showing:
JVM terminated. Exit code=1
/usr/lib/jvm/java-7-openjdk-amd64/jre/bin/java
-Dosgi.requiredJavaVersion=1.7
-XX:MaxPermSize=256m
-Xms256m
-Xmx1024m
-jar /opt/eclipse//plugins/org.eclipse.equinox.launcher_1.3.100.v20150511-1540.jar
-os linux
-ws gtk
-arch x86_64
-showsplash /opt/eclipse//plugins/org.eclipse.platform_4.5.2.v20160212-1500/splash.bmp
-launcher /opt/eclipse/eclipse
-name Eclipse
--launcher.library /opt/eclipse//plugins/org.eclipse.equinox.launcher.gtk.linux.x86_64_1.1.300.v20150602-1417/eclipse_1612.so
-startup /opt/eclipse//plugins/org.eclipse.equinox.launcher_1.3.100.v20150511-1540.jar
--launcher.appendVmargs
-exitdata 2f8001
-product org.eclipse.epp.package.java.product
-vm /usr/lib/jvm/java-7-openjdk-amd64/jre/bin/java
-vmargs
-Dosgi.requiredJavaVersion=1.7
-XX:MaxPermSize=256m
-Xms256m
-Xmx1024m
-jar /opt/eclipse//plugins/org.eclipse.equinox.launcher_1.3.100.v20150511-1540.jar

Default JDK of System is JDK8.
BUT I have written JDK7 in eclipse.ini page
code of eclipse.ini is
-startup
plugins/org.eclipse.equinox.launcher_1.3.100.v20150511-1540.jar
--launcher.library
plugins/org.eclipse.equinox.launcher.gtk.linux.x86_64_1.1.300.v20150602-1417
-product
org.eclipse.epp.package.java.product
--launcher.defaultAction
openFile
-showsplash
org.eclipse.platform
--launcher.XXMaxPermSize
256m
--launcher.defaultAction
openFile
--launcher.appendVmargs
-vm
/usr/lib/jvm/java-7-openjdk-amd64/jre/bin/java
-vmargs
-Dosgi.requiredJavaVersion=1.7
-XX:MaxPermSize=256m
-Xms256m
-Xmx1024m

doing default JDK7 producing to run other Java program.
Please help to get rid of this, so that I can work on Jframe.

A: For me deinstalling the 3d Vision Driver did the trick, like posted here


text:
Q: Formatting An Output File In Python My program outputs an .nc file, which is a plain text g-code file. When I call
        f.write(str(uniform))

the file is formatted as follows:
("('G20G90M3S200G1X' 0.03125 'F20G1X' 0.0625 'F15G1X' 0.09375 'F10G1X' 0.125 'F20S300
How can I fix my code so the output file is formatted as follows:
G20G90M3S200G1X0.03125F20G1X0.0625F15G1X0.09375F10G1X0.125F20S300
I added .replace() which removed the commas, but I don't know how to get rid of the single and double quotes or the empty spaces and I don't know how to add line breaks where I need them.
Here is my code:
from tkinter import *
from tkinter import ttk
import os
os.system('clear')

root = Tk()
root.title('Pickup Coil Turn Count Calculator')

app_width = 400
app_height = 600

screen_width = root.winfo_screenwidth()
screen_height = root.winfo_screenheight()

x = (screen_width / 2) - (app_width / 2)
y = (screen_height / 2) - (app_height / 2)
root.geometry(f'{app_width}x{app_height}+{int(x)}+{int(y)}')
root.configure(bg='light grey')

my_notebook = ttk.Notebook(root)
my_notebook.pack()

my_frame1 = Frame(my_notebook, width=400, height=600, bg='light grey')
my_frame2 = Frame(my_notebook, width=400, height=600, bg='light grey')

my_frame1.pack(fill='both', expand=1)
my_frame2.pack(fill='both', expand=1)

my_notebook.add(my_frame1, text='Turn Count Calculator')
my_notebook.add(my_frame2, text='G-Code Builder')

def turn_count():
    width, length, ohms, resistance = float(e2.get()), float(e3.get()), float(options[clicked.get()]), float(e5.get())
    turn_count = resistance / ohms * 1000 * 12 / ((width * 3.14) + length + length - width * .19) * .969
    count_label['text'] = int(turn_count)

def no_scatter():
    block1 = 'G20'\
             'G90'\
             'M3S200'\
             'G1X', float(e1.get()) * .125, 'F20'\
             'G1X', float(e1.get()) * .25, 'F15'\
             'G1X', float(e1.get()) * .375, 'F10'\
             'G1X', float(e1.get()) * .5, 'F20S300'\
             'G1X', float(e1.get()) * .625, 'F10'\
             'G1X', float(e1.get()) * .75, 'F10'\
             'G1X', float(e1.get()) * .875, 'F15'\
             'G1X', float(e1.get()), 'F20S600'\
             'G1X', float(e1.get()) * .875, 'F20'\
             'G1X', float(e1.get()) * .75, 'F15'\
             'G1X', float(e1.get()) * .625, 'F10'\
             'G1X', float(e1.get()) * .5, 'F10S1200'\
             'G1X', float(e1.get()) * .375, 'F10'\
             'G1X', float(e1.get()) * .25, 'F10'\
             'G1X', float(e1.get()) * .125, 'F15'\
             'G1X', '.000', 'F20'
    block2 = 'G1X', float(e1.get()) * .125, 'F20'\
             'G1X', float(e1.get()) * .25, 'F15'\
             'G1X', float(e1.get()) * .375, 'F10'\
             'G1X', float(e1.get()) * .5, 'F20'\
             'G1X', float(e1.get()) * .625, 'F10'\
             'G1X', float(e1.get()) * .75, 'F10'\
             'G1X', float(e1.get()) * .875, 'F15'\
             'G1X', float(e1.get()), 'F20'\
             'G1X', float(e1.get()) * .875, 'F20'\
             'G1X', float(e1.get()) * .75, 'F15'\
             'G1X', float(e1.get()) * .625, 'F10'\
             'G1X', float(e1.get()) * .5, 'F10'\
             'G1X', float(e1.get()) * .375, 'F10'\
             'G1X', float(e1.get()) * .25, 'F10'\
             'G1X', float(e1.get()) * .125, 'F15'\
             'G1X', '.000', 'F20'
    uniform = str(block1), str(block2)
    with open('No Scatter.nc', 'w') as f:
        f.write(str(uniform).replace(',', ''))

myLabel = Label(my_frame1, text='Enter Core Height', bg='light grey')
myLabel.pack(pady=10)
e1 = Entry(my_frame1, width=10, justify='center', border=0)
e1.pack()

myLabel = Label(my_frame1, text='Enter Core Width', bg='light grey')
myLabel.pack(pady=10)
e2 = Entry(my_frame1, width=10, justify='center', border=0)
e2.pack()

myLabel = Label(my_frame1, text='Enter Core Length', bg='light grey')
myLabel.pack(pady=10)
e3 = Entry(my_frame1, width=10, justify='center', border=0)
e3.pack()

myLabel = Label(my_frame1, text='Enter Target Resistance In Ohms', bg='light grey')
myLabel.pack(pady=10)
e5 = Entry(my_frame1, width=10, justify='center', border=0)
e5.pack()

myLabel = Label(my_frame1, text='Select Wire Gauge', bg='light grey')
myLabel.pack(pady=10)

options = {
    '38': '648.0',
    '39': '846.0',
    '40': '1079.0',
    '41': '1323.0',
    '42': '1659.0',
    '43': '2143.0',
    '44': '2593.0'
}

clicked = StringVar()
clicked.set(list(options.keys())[0])

drop = OptionMenu(my_frame1, clicked, *options.keys())
drop.pack()

Button(my_frame1, text='Calculate Turn Count', command=turn_count).pack(pady=30)

myLabel = Label(my_frame1, text='Turn Count', font='arial 14 bold', bg='light grey')
myLabel.pack()

count_label = Label(my_frame1, width=10, font='arial 20 bold', fg='white', bg='dark grey')
count_label.pack()

myLabel = Label(my_frame1, bg='light grey')
myLabel.pack()

myLabel = Label(my_frame2, text='Enter Winder Motor RPM', bg='light grey')
myLabel.pack(pady=10)
e6 = Entry(my_frame2, width=10, justify='center', border=0)
e6.pack()

myLabel = Label(my_frame2, bg='light grey')
myLabel.pack()

myLabel = Label(my_frame2, text='Select A Winding Pattern', bg='light grey')
myLabel.pack(pady=10)

Button(my_frame2, text='No Scatter', command=no_scatter).pack(pady=10)

Button(my_frame2, text='Minimum Scatter').pack(pady=10)

Button(my_frame2, text='Moderate Scatter').pack(pady=10)

Button(my_frame2, text='Maximum Scatter').pack(pady=10)

root.mainloop()

A: It's YOU that are making it one big string.  If you just create this as a list of strings, your problem becomes trivial.
    block1 = ['G20',
             'G90',
             'M3S200',
             'G1X'+ str(float(e1.get()) * .125)+ 'F20',
             'G1X'+ str(float(e1.get()) * .25)+ 'F15',
             'G1X'+ str(float(e1.get()) * .375, 'F10',
             'G1X'+ str(float(e1.get()) * .5)+ 'F20S300',
             'G1X'+ str(float(e1.get()) * .625)+ 'F10',
...

Once you have that, you can write it with '\n'.join(block1).  There's no point in creating your data in a way that isn't useful for you.


text:
Q: project design problem In my web applications i have to generate seven different type of forms. There is a big 7 level tree and from that each first level subnode is a separate form. So for this what i am thinking is to generate 7 different xml files and to display the form like below given image i will parse the particular xml and display it. In my xml there will be node id and for each user i will store his selected nodes in the table so that i can retrieve later in my account section.
My question now are: is this xml approach proper...? and what kind of xml should i generated so that maximum flexibility can be kept in xml.. eg if i keep attribute validation: required in any node than it becomes required field in the generated html. i have to make a parser for that.

A: To answer this question is needed to know what technologies are you using in you proyect.
For example: In a java web project I should use JSON as it can be requested from javascript to update de form selections (jQuery+AJAX) an generated in server side from any data type you have stored it. It is very easy to do it with Spring.


text:
Q: Problem understanding the keyframes in css I have the following keyframes, by which i want to animate logo of windows:
.box {
  height: 40px;
  width: 40px;
  float: left;
}

#box1 {
  #background-color: red;
  animation: box1 4s 1s infinite;
}

#box2 {
  #background-color: lightgreen;
  animation: box2 4s 1s infinite;

}

@keyframes box2 {
   0% {
    background-color: #1b2028;
  }
  25% {
    background-color:  #1b2028;
  }
  50% {
    background-color: #1b2028;
  }
  75% {
    background-color: lightgreen;
  100% {
    background-color: #1b2028;
  }

}

@keyframes box1 {
  0% {
    background-color: red;
  }
  25% {
    background-color: red;
  }
  50% {
    background-color: red;
  }
  75% {
    background-color: red;
  100% {
    background-color: #1b2028;
  }
}

The problem however is only one of the keyframe is working. ie only keyframe with name box2 works and when i place keyframe of box1 on top it works, why is that so. Can someone please provide me a good understanding of keyframes?. The link to codepen is: https://codepen.io/theredcap/pen/qvJdJa?editors=1100

A: Did you check your css with a linter?
CSS lint found 4 errors and 6 warnings.
Fix following errors.

*

*Expected RBRACE at line 54, col 9.

*Expected RBRACE at line 72, col 9.

*Expected RBRACE at line 90, col 9.

*Expected RBRACE at line 107, col 9.

You are missing a closing } :)
Check this codepen: https://codepen.io/foxfabi/pen/oVaePr


text:
Q: How do I escape characters in a vim abbreviation? I'm trying to make this abbreviation in my Vimrc for markdown editing:
iabbrev ,,img ![<alt-text>](<img-link>)
I think the parenthesis need to be escaped here, but I'm not sure how to escape these characters without including the escape character in the abbreviation as well.
What should I do?

A: Abbreviations come in the following forms (See :h abbreviations):
There are three types of abbreviations:

full-id   The "full-id" type consists entirely of keyword characters (letters
      and characters from 'iskeyword' option).  This is the most common
      abbreviation.

      Examples: "foo", "g3", "-1"

end-id    The "end-id" type ends in a keyword character, but all the other
      characters are not keyword characters.

      Examples: "#i", "..f", "$/7"

non-id    The "non-id" type ends in a non-keyword character, the other
      characters may be of any type, excluding space and tab.  {this type
      is not supported by Vi}

      Examples: "def#", "4/7$"

,,img can not be a full-id as it starts with ,. It can not be end-id as all other characters have to be non-keyword characters. It can not be non-id either.
I would recommend changing your abbreviations. e.g. img,,

A: In my attempts to reproduce your problem, I find that vim gives me an error due to the two commas in the left-hand side of your abbreviation, ,,img.
These work for me:
iabbrev img ![<alt-text>](<img-link>)
iabbrev __img ![<alt-text>](<img-link>)

while this:
iabbrev ,,img ![<alt-text>](<img-link>)

gives me error:

E474: Invalid argument


text:
Q: How to give different style to  columns and rows? How to give different styling to last row only and 1st and last column of the table . is it possible without using css classes?
See current example here http://jsfiddle.net/jitendravyas/KxmY5/1/
and this is how I want it:

A: If you are targeting A-Grade browsers with any sort of historical nature to them (IE 6, etc) you cannot do it without using a class/ID to select them. If the browser you are targeting supports :nth child selectors in CSS, you could write a rule to select them, but know that it won't be supported by all (probably) of your visitor's browsers.
Here is a reference to Sitepoint's nth child article

A: This is incredibly hacky. Doesn't work at all in IE6 (due to using the '+' adjacent-child selector). Mostly works in FF 3.6, but should give you an idea of how ugly this gets without using classes, IDs or :nth-child selectors.
<style type="text/css">

table tr + tr + tr + tr + tr + tr + tr + tr td {
        background-color: yellow; /* row 8 */
}

table tr + tr + tr + tr + tr + tr + tr + tr + tr td {
        background-color: white; /* rows 9+ */
}

table tr td {
        background-color: red; /* 1st column */
}

table tr td + td {
        background-color: white; /* reset 2nd column to white */
}

table tr td + td + td {
        background-color: green; /* 3rd column */
}

table tr td + td + td + td {
        background-color: white; /* reset cols 4-10 */
}

</style>

As this stands, the red/green columns get terminated by the yellow row. But some MORE of this ugly stuff could resume them on rows 9 and 10.

A: By using JQuery JavaScript framework it might be easier in your case.


text:
Q: How to create a HTML report with graphs for test results from data in text file? I have a framework written in python where I execute my automated test cases & the result of the automated suites are reported collectively in a text file. The contents of the text file looks like this.
Test.Case.001 - PASSED : Device-Name
Test.Case.002 - PASSED : Device-name
Test.Case.003 - PASSED : Device-name

These suites I have automated using Jenkins as well to trigger every weekend. The problem I'm facing is with reporting the results in a good format. This is a text file, so junit cannot be used here. I need to know any method where these results can be parsed and reported in a beautiful format with graphs etc. I've been able to parse the results into an excel file but pretty much remains the same.
Is there any way to do so ?

A: If you're generating an HTML file, why not use a plotting library, such as Chart.js? You can just import it in your header:
<script src="path/to/chartjs/dist/chart.js"></script>
and then proceed to make any charts you want.
Check out the docs, they're pretty solid. I also recommend importing from CDN unless you need those reports to work offline.


text:
Q: How to strip context path in nginx, zuul and oauth combined I have Nginx proxy with following configuration:
upstream gateway_server {
  ip_hash; # sticky session on as there will be more than one destination
  server app.server:8080;
}

server {

  listen                  0.0.0.0:80;
  server_name             my.domain.net;
  root                    /var/www/gateway;

  proxy_redirect          off;
  proxy_buffering         off;
  proxy_connect_timeout   5s;
  proxy_read_timeout      120s;
  proxy_next_upstream     error timeout http_502 http_503 http_504;
  proxy_set_header        X-Real-IP $remote_addr;
  proxy_set_header        X-Forwarded-For $proxy_add_x_forwarded_for;
  proxy_set_header        X-Forwarded-Host $host;
  proxy_set_header        X-Forwarded-Proto $http_x_forwarded_proto;
  proxy_set_header        Host $host;
  proxy_intercept_errors  on;

 location / {
   proxy_pass              http://gateway_server/my-application/;
 }

 location /loginPage {
   proxy_pass              http://gateway_server/loginPage;
 }

 location ^~ /login {
   proxy_pass              http://gateway_server/login;
 }

 location /logout {
   proxy_pass              http://gateway_server/logout;
 }

 location /css {
   proxy_pass              http://gateway_server/css;
 }

 error_page 502 503 504 @maintenance;
 location @maintenance {
     rewrite ^(.*)$          /maintenance.html break;
 }

 error_page 404 /404.html;
 location = /404.html {
   rewrite ^(.*)$          /404.html break;
 }

 error_page 500 /500.html;
 location = /500.html {
   rewrite ^(.*)$          /500.html break;
 }
}

The gateway-server is pointing at my zuul proxy, which is a simple SpringBoot Application annotated with @EnableZuulProxy. Routes are configured as follows:
# Zuul configuration
zuul:
  host:
    socket-timeout-millis: 300000 # 5 minutes
  sensitiveHeaders:
  routes:
    my-application:
      path: /my-application/**
      serviceId: my-application
      stripPrefix: false

my-application is a Spring Boot application combined with angular front-end. Apart from routing, gateway-server is also responsible for authentication - it communicates with out OAuth2 multi provider. When a user is not authenticated, and tries to call my.domain.net Nginx proxies the call to zuul (app.server:8080/my-application/) gateway-server starts Oauth2 protocol, and forwards user to a login page, where one can choose his/hers provider (facebook, google, internal). Whole authentication is managed by spring - I don't do any custom things. After successful login user gets redirected to my.domain.net/my-application rather than to my.domain.net.
Do you have any idea which element in my infrastructure adds this context path? Do you have any idea how could I remove it?

A: you just need to use stripPrefix: true because your config:
path: /my-application/**
serviceId: my-application
stripPrefix: false

tells spring to keep /my-application/ ( which is 'prefix' in zuul understanding ) after redirect.


text:
Q: How to write an android app to access and edit contents of a MySQL Database stored in my cPanel of my domain? I've searched a lot but couldnt find anything that could be useful or easy to understand.
Please help!

A: Android can't directory manipulate or access MySQL Databases. The easiest solution is to have Android post data to a web server which hosts some PHP scripts. The PHP scripts can then do what is needed in the database, and if returning rows from the database, encode them into JSON and return the JSON content back to android. You can then manipulate the contents of JSON for your app. http://www.androidhive.info/2012/05/how-to-connect-android-with-php-mysql/ may be of use.
It also means using this method, you don't have to expose your database to the outside world on the internet as the PHP pages will just access the database using Localhost. (Assuming you put the PHP scripts on the server that hosts the database)


text:
Q: How to get part of request body as input stream (request body mapped to multiple fields, one of them is an inputstream field) Let's consider following scenario:
I need to upload very large file, other than that I need the name, version and author.
I have created the following endpoint:
@PostMapping(path = "/upload", consumes = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<String> upload(@RequestBody MyClass myClass) {
    //do the upload using the content received as InputStream and return success
}

The MyClass.java:
public class MyClass {
  private String name;
  private String version;
  private String author;
  private InputStream fileContent;
  // constructor, getters and setters
}

Example request body:
{
  "name": "article",
  "version": "1",
  "author": "John Smith"
  "fileContent": "ZmlsZUNvbnRlbnQg" //base64 encoded tgz/zip
}

So the whole case is to save the name,version and author e.g. in database,
and then use the fileContent InputStream to stream it somewhere (as it is too big to have it as bytearray).
Is something like that possible in spring?
All help appreciated!

A: I have this function for uploading videos to a directory in my intellij workspace.
    @RequestMapping(method = RequestMethod.POST, path = "/projects/save/video")
    public String uploadVideo(@RequestParam("file") MultipartFile file, @ModelAttribute Project project) throws InterruptedException {
        // check if file is empty
        if (file.isEmpty()) {
            System.out.println("No file");
            return "redirect:/user/projects";
        }
        // normalize the file path
        String fileName = StringUtils.cleanPath(file.getOriginalFilename());

        // save the file on the local file system
        try(InputStream inputStream = file.getInputStream()) {
            Path path = Paths.get(VID_UPLOAD_DIR + fileName);
            Files.copy(inputStream, path, StandardCopyOption.REPLACE_EXISTING);

            File directory = new File(CLASS_DIR);
            if (! directory.exists()) {
                directory.mkdir();
            }
            Path classPath = Paths.get(CLASS_DIR + fileName);
            Files.copy(path, classPath, StandardCopyOption.REPLACE_EXISTING);
        }
        catch (IOException e) {
            e.printStackTrace();
        }
        String part="../videos/"+fileName;
        System.out.println(file.getSize() + " <---[]---> " + part);

        member.setVideo(part);

        MemberDB.projects.get(0).setTitle(project.getTitle());
        MemberDB.projects.get(0).setDescription(project.getDescription());
        MemberDB.projects.get(0).setLanguage(project.getLanguage());
        MemberDB.projects.get(0).setTechnology(project.getTechnology());
        MemberDB.projects.get(0).setVideoName(project.getVideoName());

        return "redirect:/user/projects";
    }

Template (using thymeleaf) looks like this
  <form action="#" th:action="@{/projects/save/video}" name="subform" method="post" id="addProject" th:object="${project}" enctype="multipart/form-data">

Add project

    <input class="exempt" th:field="*{title}" type="text">
    <textarea class="exempt" th:field="*{description}" rows="4"></textarea>

    <input class="exempt" type="hidden" th:field="*{videoName}" id="setVidName">
    <input class="exempt" type="file" id="vidName" accept="video/mp4" name="file" onchange="setNameVar(this);">
    <button class="exempt" type="button" onclick="submitForm();">Save project</button>
  </form>

And in your application properties

*

*spring.servlet.multipart.max-file-size=200MB

*spring.servlet.multipart.max-request-size=200MB

*spring.servlet.multipart.enabled=true


text:
Q: How do I make a login/ sign up code for my website using HTML, CSS, JS I am trying to make a multi user website for Alaskan fishing reports. I am going to find people from different towns, villages/ cities to write reports on their area for other people to learn from. I want to know how to make a system that can keep all the usernames with the passwords assoctiated. I already got the login system done.
Here is the HTML:
<!DOCTYPE html>

<title> LOGIN Form</title>
<meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1">
<rel='stylesheet' type='text/css'>

Login to Alaska Fishing Reports

<form>

 Username

<input type="text" name="" placeholder="Enter Username">

 Password

<input type="password" name="" placeholder="Enter Password">

<input type="submit" name="" value="Login">
Lost your password?

Don't have an acoount?
</form>

A: To create login page, you must learn server side programming, like PHP and MySQL. That might be little complicated and only with HTML CSS and JS you cannot create fully functioning login pages. You should also make security for your clients.


text:
Q: What is the meaning of the phrase "plain style" in this context? The following context comes from the book "Black Rednecks And White Liberals" by Thomas Sowell:

By contrast, religious services in colonial Massachusetts developed what has been called the "meeting and lecture" approach, where the "style of
preaching was a relentless cultivation of the plain style." these "addresses tended to be closely argued statements of great density, in which Puritans reasoned as relentlessly with their maker as they did with one another." This intellectual approach to religion carried over into their daily lives.

What is the meaning of this sentence? Especially the phrase plain style. What does it mean to cultivate the plain style. (PS. I know what cultivate means so you don't have to explain that)

A: From https://preachingsource.com/blog/what-is-a-plain-style/ :

Plain preaching is defined as much by what it lacks as what it
contains.  Plain preaching gets to the core of the message without an
embellished style which calls attention to its own ostentation.  It is
not a mere exercise of human ego.  Plain means simple and to the
point.  Plain preaching praises the Master rather than the medium.

[The article goes on to describe the five elements of plain preaching.]
From https://www.ligonier.org/posts/plain-preaching-puritan-evangelism:

The Puritan "plain style of preaching" avoided all that was not clear
or perspicuous to an ordinary listener. The greatest teacher of this
preaching style was Perkins. Perkins, often called the father of
Puritanism, wrote that preaching "must be plain, perspicuous, and
evident…. It is a by-word among us: It was a very plaine Sermon: And I
say again, the plainer, the better."

There is a scholarly article on the subject here at JStor.


text:
Q: Base class pointer assigned to derived class I created base class pointer and assigned new derived class to it.
 class Base
{
public:
    virtual void f( int );
    virtual void f( double );
    virtual void g( int i = 10 );
};

void Base::f( int )
{
    cout << "Base::f(int)" << endl;
}

void Base::f( double )
{
    cout << "Base::f(double)" << endl;
}

void Base::g( int i )
{
    cout << i << endl;
}

class Derived: public Base
{
public:
    void f( complex<double> );
    void g( int i = 20 );
};

void Derived::f( complex<double> )
{
    cout << "Derived::f(complex)" << endl;
}

void Derived::g( int i )
{
    cout << "Derived::g() " << i << endl;
}

void main()
{
    Base b;
    Derived d;
    Base* pb = new Derived;
    b.f(1.0);
    d.f(1.0);
    pb->f(1.0);
    b->g();
    d->g();
    pb->g();
    delete pb;
}

Result is:
Base::f(double)
Derived::f(complex)
Base::f(double)
10
Derived::g() 20
Derived::g() 10

Results for b and d are expected. pb->f(1.0) calls Base function f(double), but pb->g() seems to call Derived class function g but using parameter i=10 from Base class. Why?

A: Kerrek SB said it all in the comment, I will detail it a bit.
As in this answer, the mechanism of resolving default function parameters occurs at compile time. When the compiler sees pb->g();, knowing that pb is a pointer of type Base*, it consults the declaration of Base::g, that is
virtual void g( int i = 10);

It concludes:
1- The missing parameter i should be set to 10. This is a compile-time decision.
2- The method is declared virtual, which means that the actually invoked method depends on what pb will be pointing-to at run time. The compiler sets the mechanism to dispatch the call to g at runtime (usually through an indirection via the vtable). Since at runtime it happens that pb is actually pointing to an object of type Derived, the method Derived::g is called.


text:
Q: MySql desde Java con ResultSet Scroll_Sensitive Estoy utilizando el conector JDBC de MySQL 5.1.26 y, si consulto los metadatos, me indica que no admite los cursores Scroll_Sensitive:
Connection con;
try {
    con = DriverManager.getConnection("jdbc:mysql://localhost/miBD", "root", "");
    DatabaseMetaData metadata = con.getMetaData();

    boolean soportaScroolSensitive =
     metadata.supportsResultSetType(ResultSet.TYPE_SCROLL_SENSITIVE);

La llamada a este último método me devuelve falso. Ahora bien, si creo un Statement indicando que quiero un cursor de ese tipo, compruebo que sí que lo admite:
Statement stmt = con.createStatement(
            ResultSet.TYPE_SCROLL_SENSITIVE,
            ResultSet.CONCUR_READ_ONLY);

ResultSet rs = stmt.executeQuery("SELECT * FROM Clientes;");

rs.last();
while (rs.previous())
    System.out.println(rs.getString(1));

El bucle itera perfectamente los registros desde el final hasta el inicio.
¿Por qué el método supportsResultSetType() de metadata me indica que no soporta este tipo de cursor cuando realmente sí que lo hace?

A: Es posible que hayas obtenido un ResultSet de tipo TYPE_SCROLL_INSENSITIVE:
Un ResultSet "scrollable" se puede recorrer en ambos sentidos, pero hay dos tipo de "scrollable": sensitive e "insensitive". De la documentación (las negritas son mías):

static final int TYPE_SCROLL_INSENSITIVE

The constant indicating the type for a ResultSet object that is
scrollable but generally not sensitive to changes to the data that
underlies the ResultSet.
static final int TYPE_SCROLL_SENSITIVE

The constant indicating the type for a ResultSet object that is scrollable and generally
sensitive to changes to the data that underlies the ResultSet.


text:
Q: Jenkins Pipeline - executing job in docker permissions issues I have a Jenkinsfile that looks like
pipeline {
    agent {
        docker {
            image 'myartifactory/cloud-eng/sls-build:0.13'
            label 'docker'
            registryUrl 'https://myartifactory'
            registryCredentialsId 'artfifactory-cred-id'
        }
    }

    environment {
    }
    stages {
        stage('Test') {
            sh "env | sort"
            sh "make setup-ci"
            sh "make test"
        }
    }
}

When I run this I see that jenkins executed a command that looks like:
docker run -t -d -u 1318244366:1318464184 -w /jenkins_home/jenkins-rh7-a01/8b13f8c3/workspace/te_csoe-1624-switch-shared-https -v /jenkins_home/jenkins-rh7-a01/8b13f8c3/workspace/te_csoe-1624-switch-shared-https:/jenkins_home/jenkins-rh7-a01/8b13f8c3/workspace/te_csoe-1624-switch-shared-https:rw,z -v /jenkins_home/jenkins-rh7-a01/8b13f8c3/workspace/te_csoe-1624-switch-shared-https@tmp:/jenkins_home/jenkins-rh7-a01/8b13f8c3/workspace/te_csoe-1624-switch-shared-https@tmp:rw,z -e ******** -e ******** -e ******** -e ******** -e ******** -e ******** -e ******** -e ******** -e ******** -e ******** -e ********  myartifactory/cloud-eng/sls-build:0.13 cat

This project uses python, NPM, and the serverless framework (javascript).
If I run this as above it will fail
 npm ERR! correctMkdir failed to make directory /.npm/_locks
2021-03-11 16:17:02  npm ERR! code EACCES
2021-03-11 16:17:02  npm ERR! syscall mkdir
2021-03-11 16:17:02  npm ERR! path /.npm
2021-03-11 16:17:02  npm ERR! errno -13
2021-03-11 16:17:02  npm ERR!
2021-03-11 16:17:02  npm ERR! Your cache folder contains root-owned files, due to a bug in
2021-03-11 16:17:02  npm ERR! previous versions of npm which has since been addressed.
2021-03-11 16:17:02  npm ERR!
2021-03-11 16:17:02  npm ERR! To permanently fix this problem, please run:
2021-03-11 16:17:02  npm ERR!   sudo chown -R 1318244366:1318464184 "/.npm"
2021-03-11 16:17:02  make: *** [setup-ci] Error 243

I tried many solutions with varying success.  If I add this:
args '-u root' to the docker section it works as of course root has permissions to everything.... however security isn't going to like running the docker container as root.
No matter what I do with overriding $HOME in environment or args, changing users I always end up with permissions issues either with NPMs or python.
Other errors I've encountered with various hacks such as args '-e HOME=/tmp -e NPM_CONFIG_PREFIX=/tmp/.npm'
../../../../../tmp/.local/share/virtualenvs/te_csoe-1624-switch-shared-https-y_ilovXz/lib/python3.8/site-packages/_pytest/cacheprovider.py:428
2021-03-11 14:45:14    /tmp/.local/share/virtualenvs/te_csoe-1624-switch-shared-https-y_ilovXz/lib/python3.8/site-packages/_pytest/cacheprovider.py:428: PytestCacheWarning: cache could not write path /jenkins_home/jenkins-rh7-a01/8b13f8c3/workspace/te_csoe-1624-switch-shared-https/.pytest_cache/v/cache/nodeids
2021-03-11 14:45:14      config.cache.set("cache/nodeids", sorted(self.cached_nodeids))

Error: EACCES: permission denied, unlink '/jenkins_home/jenkins-rh7-a01/8b13f8c3/workspace/te_csoe-1624-switch-shared-https/.serverless/cloudformation-template-update-stack.json'
2021-03-11 14:45:19        at Object.unlinkSync (fs.js:1136:3)

Since jenkins mounts random directories to share and random users I am not sure how to modify the Dockerfile for the image to grant write permissions....
Does anyone know how to get the permissions correct?
EDIT added Dockerfile
FROM amazonlinux:2

RUN yum install -y amazon-linux-extras
RUN yum install -y unzip
RUN yum groupinstall -y "Development Tools"
RUN yum install vim-enhanced -y

# install python/pipenv
ENV PYTHON_VERSION=3.9
RUN amazon-linux-extras install python${PYTHON_VERSION}
RUN /bin/pip-${PYTHON_VERSION} install pipenv

# install node/npm
RUN curl -sL https://rpm.nodesource.com/setup_12.x | bash -
RUN yum install -y nodejs
RUN mkdir /tmp/node-cache
RUN npm config set cache /tmp/node-cache --global

# install aws-cli2
RUN curl "https://awscli.amazonaws.com/awscli-exe-linux-x86_64.zip" -o "awscliv2.zip" && \
    unzip awscliv2.zip && \
    ./aws/install && \
    rm -rf awscliv2.zip
`
# install vault client
ENV VAULT_VERSION=1.5.4
RUN curl -sSLo /tmp/vault.zip https://releases.hashicorp.com/vault/$VAULT_VERSION/vault_${VAULT_VERSION}_linux_amd64.zip && \
    unzip -d /bin /tmp/vault.zip && \
    rm -rf /tmp/vault.zip && \
    setcap cap_ipc_lock= /bin/vault

ADD ./aws-login.sh /usr/local/bin/aws-login.sh
ADD ./ghe-token.sh /usr/local/bin/ghe-token.sh
ENV PATH="/bin:${PATH}"
# indicates CI CONTAINER so processes can check if running in CI
ENV CI_CONTAINER=1
ENV LANG="en_US.UTF-8"
ENV TERM xterm
# avoid million NPM install messages
ENV npm_config_loglevel warn
ENTRYPOINT []

A: The thing that was tripping me up was I had run this as -u root many times and I only have one agent (don't ask) and jenkins caches the workspace directory.  So the file permissions had been changed in that code by the docker container running as root.  So when I got rid of -u root and it started using the jenkins user it didn't have rights to some files and directories.
The solution was to delete the workspace and make sure that all make calls had an export HOME=${WORKSPACE} before any command.
There might be a better way to export HOME but this solves the prob


text:
Q: activate/enable javascript plugins based on user options I'm building a JS client for a set of REST WebServices. The client will be delivered as an embeddable iframe, which should load JS scripts based on user options (license profile, user admin options, etc.)
I wonder what's the most effective and efficient pattern to do that.
At now I have a single "bootstrap" script, which includes the other scripts. I could create  the bootstrap script code dynamically (server side), to make it load only the set of scripts required by the user configuration. Anyway those scripts would be publicly available, even if the services are not enabled for certain users... IMHO that's not a good solution.
On the other hand, how to control the access to static javascipt files on a public folder?
I want to avoid to serve javascript code though my code. It would be an expensive overload for the application!
Mmm... I'm a bit confused...
Giovanni

A: In general, if you wish to control access to a resource based on a business requirement (licenses, user profiles etc) you have no choice but to route all requests for that resource through your application.
However, since you are you are sending the files to the client there is no guarantee that anyone in possession of the scripts is currently authorized or authenticated (license may have expired, etc). As such, you cannot infer that a request to your web services is valid based on the fact that a consumer knows how to call your web service.
There should be very little to lose in making the scripts publicly accessible (since there should be nothing that you wish to kept secret in them). So, in answer to your question, I would suggest authenticating and authorizing any requests at the web service level and allowing the javascript files to be publicly accessible.


text:
Q: Sharing Realm Between Users I am trying to implement Realm in my Android app.
I want to get all UserDetails Model Records which are registered in Realm Object Server for that I need to implement shared realm.
After searching a lot I came to know I can do by PermissionOffer and PermissionOfferResponse.
Now I am able to get token succesfully.
I was stuck in this step:
Send the token to another user Sharing Realm Between Users.
    1.Send the token to another user via any method.

Which method i need to use to send token to other user?
Screenshot

A: I believe you've come across the part of the guide they consider out-of-scope for their product. It seems Realm expect you to be able to communicate a token to another user to establish the trust between the two users.
Commonly you either setup a server which handles passing tokens between users (ironic given I think that's what I think Realm say they do after you've setup the token), or you setup a peer-to-peer communication.
The peer-to-peer can be done in many ways, a simple bluetooth communication, encode the token into a URL and share over WhatsApp, use NFC to tap two phones together.
This part is arguably quite fun given the amount of flexibility you have (albiet understandable annoying given you'd assume Realm would support this step (which it might if you look at the docs). Google around and come up with a way of communicating a token, hope you have fun :)


text:
Q: app crashes as the late init property has not been initialized in android studio I have a button, when i click on that, it should show the Alert dialog box, But app crashes when i click on that button I know the code flow is this but I dont know Where i had done my mistake
      private lateinit var btn: Button

 override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_dynam)
        btn = findViewById(R.id.add1)
        buildDialog()

        btn.setOnClickListener(object : View.OnClickListener {
            override fun onClick(v: View?) {
              dialog.show()
            }
        })
    }

    private fun buildDialog() {
        val builder=android.app.AlertDialog.Builder(this)
        val view=layoutInflater.inflate(R.layout.dialog_dynam,null)
      val name=  view.findViewById<EditText>(R.id.nameEdit)
        builder.setView(view)
        builder.setTitle("Enter name")
            .setPositiveButton("Ok",object :DialogInterface.OnClickListener{
                override fun onClick(dialog: DialogInterface?, p1: Int) {
addname(name.text.toString())

                }`

A: I think you have dialog as a lateinit variable and you forgot to  assign it in buildDialog function.
      private lateinit var btn: Button
      private lateinit var dialog:AlertDialog

      override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_dynam)
        btn = findViewById(R.id.add1)
        buildDialog()

        btn.setOnClickListener(object : View.OnClickListener {
            override fun onClick(v: View?) {
         if (this@YourActivity::dialog.isInitialized) { // to check if dialog is initialize or not
          dialog.show()
         }

            }
        })
    }

    private fun buildDialog() {
        val builder=android.app.AlertDialog.Builder(this)
        val view=layoutInflater.inflate(R.layout.dialog_dynam,null)
        val name=  view.findViewById<EditText>(R.id.nameEdit)
        builder.setView(view)
        builder.setTitle("Enter name")
            .setPositiveButton("Ok",object :DialogInterface.OnClickListener{
                override fun onClick(dialog: DialogInterface?, p1: Int) {
                addname(name.text.toString())

        // initialize dialog
        dialog = builder.create()
                }


text:
Q: Memory and CPU utilization of VMs from Vcenter I have prepared some command for pulling result of memory and cpu utilization of vm frkm vcenter.
How can we setup this command for specified Vms, like save one notepad which VMs we need and run script from that notepad.
Import-Module VMware.VimAutomation.Core Connect-VIServer -Server wbllonpvmisvc1.intl.warnerbros.com $myCol = @() $start = (Get-Date).AddDays(-30) $finish = Get-Date ##$cluster= Get-Content "C:\Cluster Peformance\Cluster.txt" ##$objServers = Get-Cluster $cluster | Get-VM ##$objServers = Get-Content "C:\Cluster Peformance\hi.txt" $objServers = Get-VM foreach ($server in $objServers) { if ($server.guest.osfullname -ne $NULL){ $stats = get-stat -Entity $server -Stat "cpu.usage.average","mem.usage.average" -Start $start -Finish $finish $ServerInfo = "" | Select-Object vName, OS, Mem_GB, AvgMem_Per, MaxMem_Per, vCPU, AvgCPU_Per, MaxCPU_Per, Host $ServerInfo.vName = $server.name $ServerInfo.OS = $server.guest.osfullname $ServerInfo.Host = $server.vmhost.name $ServerInfo.Mem_GB = $server.memoryGB $ServerInfo.AvgMem_Per = $("{0:N2}" -f ($stats | Where-Object {$.MetricId -eq "mem.usage.average"} | Measure-Object -Property Value -Average).Average) $ServerInfo.MaxMem_Per = $("{0:N2}" -f ($stats | Where-Object {$.MetricId -eq "mem.usage.average"} | Measure-Object -Property Value -Maximum).Maximum) $ServerInfo.vCPU = $server.numcpu $ServerInfo.AvgCPU_Per = $("{0:N2}" -f ($stats | Where-Object {$.MetricId -eq "cpu.usage.average"} | Measure-Object -Property Value -Average).Average) $ServerInfo.MaxCPU_Per = $("{0:N2}" -f ($stats | Where-Object {$.MetricId -eq "cpu.usage.average"} | Measure-Object -Property Value -Maximum).Maximum) $mycol += $ServerInfo } } $myCol | Sort-Object vName | Export-Csv "V_report.csv" -NoTypeInformation


text:
Q: Get the Date Difference Between two dates excluding fridays in SQL Server I have the following two dates :
startDate = '2017-04-04'  and  endDate = '2017-04-12'

I would like to find the total count of days between these two dates excluding 'Fridays' using SQL Server.
Any Help from the SQL Server Experts will be highly appreciated!! Thanks in Advance!!

A: You can use DATENAME to check for 'Friday' do this, something like this :
DECLARE @startDate DATETIME
DECLARE @endDate DATETIME
SET @startDate = '2017-04-04'
SET @endDate = '2017-04-12'

Declare @count int
set @count=0

    while @startDate < @endDate
    Begin
        IF DATENAME(dw, @startDate) <> 'Friday'
            SET @count = @count + 1
        SET @startDate = DateAdd(d, 1, @startDate)
    END
select @count

This will result in :
7

A: just add below clause to your query
select count(*) from table
where startDate >= '2017-01-12' and endDate <= '2017-04-27'
and datename(WEEKDAY,startdate))<>'Friday'


text:
Q: For each row in a data.table, get random index for matching rows in another data.table I have a data.table (dt1) with several columns of factors e.g.
ID    Factor1    Factor2    Factor3
01          A          X          J
02          B          X          L
03          C          Y          J

Each row has a unique ID, but there may be multiple rows with the same combinations of Factor variables. I have another table (dt2) which has exactly the same Factor variables, but is much larger, and has no ID column. Every combination of Factors in dt1 will appear multiple times in dt2. e.g.
Factor1    Factor2    Factor3
      A          Z          K
      A          X          J
      A          X          J
      B          J          L
      B          X          L
      C          X          J
      C          Y          J

I want to return, for each row in dt1, the index of a random row in dt2 which has the same combination of Factor variables.
I figure I can use .I[sample(.N,1)] to return a random index, but can't figure out how to group by the relevant factors for each row. Do I need to make a function that takes each row in dt1 in turn, or is there a vectorized way to achieve this?
The desired output would either be a vector of length nrow(dt1), or it could be an additional column in dt1. It would contain the row index from dt2. e.g. something like this (the Index for ID 01 could be 2 or 3):
ID    Factor1    Factor2    Factor3    Index
01          A          X          J        3
02          B          X          L        5
03          C          Y          J        7

Any help much appreciated.

A: # create index in dt2
dt2[, index := .I]
# set unique key dt1
setkey(dt1, ID)
# get factor columns
cols <- grep("Factor", names(dt1), value = TRUE)
#build code to eval/parse in a string
run.text <- paste0("dt1[dt1, index := sample(dt2[",
                   paste0(cols, " == i.", cols, collapse = " & "),
                   ", ]$index, 1), by = .EACHI]")
#eval/parse the string
eval(parse(text = run.text))
#    ID Factor1 Factor2 Factor3 index
# 1:  1       A       X       J     2
# 2:  2       B       X       L     5
# 3:  3       C       Y       J     1
# 4:  4       A       X       J     3

sample data used (with duplicate in dt1)
library(data.table)
dt1 <- fread("ID    Factor1    Factor2    Factor3
01          A          X          J
02          B          X          L
03          C          Y          J
04          A          X          J")

dt2 <- fread("Factor1    Factor2    Factor3
      A          Z          K
      A          X          J
      A          X          J
      B          J          L
      B          X          L
      C          X          J
      C          Y          J")

A: UPD
I think you want to do something like this:
dt2[, Index := as.character(.I)]
cols = c("Factor1", "Factor2", "Factor3")
dt = dt2[, lapply(.SD, list), keyby = cols]
dt = merge(dt1, dt, by = cols, all.x = T)
dt[, .(Index = sample(Index[[1]], 1)), keyby = c("ID", cols)]

A: You can also try

*

*add index

*merge dt1 and dt2 then sample with sample(.N,1)
cols = names(dt2)
dt2[,index := .I]
dt2[dt1, on = (cols)][,.SD[sample(.N,1)],.(ID)]

or one row answer
dt2[,index := .I][dt1, on = (cols)][,.SD[sample(.N,1)],.(ID)]

Updated
library(data.table)
dt1 <- fread("ID    Factor1    Factor2    Factor3
01          A          X          J
02          B          X          L
03          C          Y          J")
dt2 <- fread("Factor1    Factor2    Factor3
      A          Z          K
      A          X          J
      A          X          J
      B          J          L
      B          X          L
      C          X          J
      C          Y          J")
cols <- names(dt2)[1:3]
dt2[,index := .I][dt1, on = (cols)][,.SD[sample(.N,1)],.(ID)]
#>       ID Factor1 Factor2 Factor3 index
#>    <int>  <char>  <char>  <char> <int>
#> 1:     1       A       X       J     3
#> 2:     2       B       X       L     5
#> 3:     3       C       Y       J     7

Created on 2021-12-07 by the reprex package (v2.0.1)

A: library(data.table)

# set up the data
set.seed(94)
dt1 <- setnames(as.data.table(matrix(sample(3, 9, TRUE), 3)), paste0("Factor", 1:3))
dt2 <- dt1[sample(3, 10, TRUE)]
dt1
#>    Factor1 Factor2 Factor3
#> 1:       2       1       2
#> 2:       2       3       3
#> 3:       2       3       2
dt2
#>     Factor1 Factor2 Factor3
#>  1:       2       3       2
#>  2:       2       3       3
#>  3:       2       3       2
#>  4:       2       3       2
#>  5:       2       3       2
#>  6:       2       1       2
#>  7:       2       3       2
#>  8:       2       3       2
#>  9:       2       3       2
#> 10:       2       3       3

# create helper columns and do a rolling join
dt2[, R := seq_len(.N)/.N, by = names(dt2)][, Index := .I]
print(dt2[dt1[, R := runif(.N)], on = names(dt1), roll = -Inf][, R := NULL])
#>    Factor1 Factor2 Factor3 Index
#> 1:       2       1       2     6
#> 2:       2       3       3     2
#> 3:       2       3       2     3


text:
Q: Git pushes to wrong heroku app This I'm sure is based solely on my lack of understanding of git, The problem is I don't know what I don't know.
I have a successful app deployed to Heroku. It tracks work orders for my fire dept. In my normal work flow, I use $ git push heroku master from the app directory to deploy my changes. I needed to set this same app up for another fire dept. So I figured I'd make a copy of it on my local machine, set up a new heroku app, make the changes needed to make the new copy specific to the new fire dept. I'd run git init etc, then push it up to the new heroku app. Problem is, it pushes up to the old one.
I figure this is because all the git settings were copied when I copied the app directory. How do I make it separate, so they act like 2 unique apps?
Is there a certain feature/area of git that I should learn about to understand what's going on here?

A: Indeed, you should understand what is a remote repository.
You can for example type git remote -v and see the result to clearly see where you are pushing.
from there, git remote rm heroku allows you to remove the remote repository.
And git remote add heroku {address} allows you to add a remote repository whose address you should specify.
The address of the corresponding remote is provided by heroku. Go on the app details on the heroku website and copy paste it from there. After that, the git push heroku master should push to the good repository.
When you copy pasted, the project, you also copy pasted the .git directory of the project so all the old settings of git for it. I think that a git clone would have been a better approach


text:
Q: Как сделать анимацию только внутри дива? Есть вот такая кнопка с анимацией, которая находится внутри div kor

#kor {
    color: #343424;
    display: block;
    background: url('https://i.stack.imgur.com/W2pe2.jpg');
    background-repeat: no-repeat;
    padding: 21px 0 21px 20px;
    border-radius: 18px;
}
.cat{
    text-align: center;
    margin-bottom: 15px;
    font-size: 18px;
    background-color: #029e40;
    width: 185px;
    color: red;
    padding: 8px 0;
    position: relative;
    border-radius: 3px;
    overflow: hidden;
    background: -webkit-repeating-linear-gradient( 45deg,#029e40,#029e40 10px,#02AA43 10px,#02AA43 20px );
    background: repeating-linear-gradient( 45deg,#029e40,#029e40 10px,#02AA43 10px,#02AA43 20px );
    }

.cat::before {
    animation: 2s ease-in-out 0s normal none infinite running pulse-bed;
    background-color: #f00;
    border-radius: 100%;
    bottom: -870px;
    content: "";
    display: block;
    height: 130px;
    left: -130px;
    margin: auto;
    opacity: 0.3;
    position: absolute;
    top: -870px;
    width: 500px;
}

    добавить в корзину

Анимация выходит за края дива kor, не могу понять, как сделать что бы она была только по размеру дива.
 вот фоновая картинка кнокпи


text:
Q: decode LPR media I'm trying to decode a SIP call like below but I don't know anything about this codec. Please help me or suggest me some documents that I should read.
m=audio 49198 RTP/AVP 118
a=rtpmap:118 SIRENLPR/48000/1
a=fmtp:118 bitrate=64000
...
m=video 49200 RTP/AVP 116
b=TIAS:512000
a=content:main
a=label:1
a=rtpmap:116 vnd.polycom.lpr/9000
a=fmtp:116 V=1;minPP=0;PP=150;RS=52;RP=10;PS=1400
...

A: It's a proprietary Polycom format. Some of the Siren codecs have been standardised as ITU formats (G.722.1 implements part of Siren 7, for instance G.722.1C implements part of Siren 14 and G.719 is based on Siren 22). LPR is "lost packet recovery", a method Polycom uses to adjust the amount of Forward Error Correction to compensate for high packet loss.
In particular, I think it's a Siren 22 (so G.719) stream, because it's using 48 kHz sampling and a 64kbit bitrate.


text: Q: Error UTF8 - PYROCMS when setting SetEnv PYRO_ENV production in .htaccess When running webside in production mode [  SetEnv PYRO_ENV production (.htaccess line 3) ], the titles of error utf8 which contain "là, và..." showing wrong (see the picture below). Could you help me how to fix it?


text:
Q: Close `showModalBottomSheet` after a timeout I tried to close showModalBottomSheet widget through an event listener.
          showModalBottomSheet(
              useRootNavigator: true,
              context: context,
              builder: (newcontext) {
                return MyBottomDialog();
              });

I tried to close this through an event listener:
class _MyBottomDialogState extends State<MyBottomDialog> {
...
...
  void initState() {
    _myEventStream.listen((state) {
      if (state == 'timeout') {
        Navigator.of(context, rootNavigator: true).pop();
      }
    });
    super.initState();
  }

TypeError: Cannot read property 'findAncestorStateOfType' of null
.
.
.
Looking up a deactivated widget's ancestor is unsafe.
At this point the state of the widget's element tree is no longer stable.
To safely refer to a widget's ancestor in its dispose() method, save a
reference to the ancestor by calling dependOnInheritedWidgetOfExactType() in
the widget's didChangeDependencies() method.

How do I achieve this?

A: The stream class actually comes with a timeout method. You just have to feed it a duration and if it exceeds that duration it throws a TimeoutException. Wrap the execution in a try block and call the close modal sheet method from the on TimeoutException catch (e) block perhaps.

A: May be I didn't capture properly what the error is saying.
Even after closing the dialog the stream subscription persists. So the handler is called even if the dialog is not open.
Adding _streamSubscription.cancel() in the widget's dispose method helps solve this problem.


text:
Q: Laravel how to disable usage of HTTP Authentication Header I have a Laravel project (without API) that I access trough a Webserver that has HTTP Authentication activated.
The Laravel App try to authenticate me with the submitted HTTP Authentication Headers (this are only used for the Webserver), how I can disable this?

A:
this are only used for the Webserver

This sense not make any statement does.
If Laravel could influence the configuration of your webserver then your site is very broken. If PHP could override headers added by the webserver then your site is very broken.
You need to change your webserver config to remove the header.


text:
Q: Show different text with different figures clicking button This code currently show figures and texts all together in the canvas all at once.
I want to show the text "Figure Number: 1" with the first figure, "Figure Number: 2" with the second and similarly with the third as I press the buttons.
This enables to show different information for different figures.
I haven't been able to figure this out.
How can I do this in the code?
The code is executable.
import tkinter as tk
import matplotlib.pyplot as plt
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg, NavigationToolbar2Tk

all_figures1 = []
selected_figure1 = 0

class MyClass1():

    def __init__(self):

        self.sheets = [[1,2,3], [3,1,2], [1,5,1]]
        self.W = 2
        self.L = 5

    def plot_sheet(self, data):
        """plot single figure"""

        fig, ax = plt.subplots(1)

        ax.set_xlim([0, self.W])
        ax.set_ylim([0, self.L])

        ax.plot(data)

        return fig

    def generate_all_figures(self):
        """create all figures and keep them on list"""
        global all_figures

        for data in self.sheets:
            fig = self.plot_sheet(data)
            all_figures1.append(fig)

dataPlot1 = None

def on_window1():

    def show_figure(number):
        global dataPlot1

        current_num = str(number+1)
        total_num = str(len(all_figures1))
        counter = tk.Label(top, text = current_num + "/" + total_num)
        counter.grid(row=4,column=0)

        # remove old canvas
        if dataPlot1 is not None: # at start there is no canvas to destroy
            dataPlot1.get_tk_widget().destroy()

        # get figure from list
        one_figure = all_figures1[number]

        # display canvas with figuere
        dataPlot = FigureCanvasTkAgg(one_figure, master=top)
        dataPlot.draw()
        dataPlot.get_tk_widget().grid(row=0, column=0)

        toolbar_frame = tk.Frame(top)
        toolbar_frame.grid(row=1,column=0)
        toolbar = NavigationToolbar2Tk(dataPlot, toolbar_frame)
        toolbar.update()

    def on_prev():
        global selected_figure1

        # get number of previous figure
        selected_figure1 -= 1
        if selected_figure1 < 0:
            selected_figure1 = len(all_figures1)-1

        show_figure(selected_figure1)

    def on_next():
        global selected_figure1

        # get number of next figure
        selected_figure1 += 1
        if selected_figure1 > len(all_figures1)-1:
            selected_figure1 = 0

        show_figure(selected_figure1)

    top = tk.Toplevel()
    top.wm_geometry("794x470")
    top.title('Optimized Map 1')

    selected_figure1 = 0
    dataPlot = None # default value for `show_figure`
    show_figure(selected_figure1)

    frame = tk.Frame(top)
    frame.grid(row=3, column=0)

    canvas1 = tk.Canvas(top, width=400, height=280)
    canvas1.grid(row=0,column=200)

    for i in range(3):
        l3 = tk.Label(canvas1, text="Figure Number:" + str(i+1))
        canvas1.create_window(50,21*i, window=l3, anchor=tk.NW)

    myscrollbar= tk.Scrollbar(top,orient=tk.VERTICAL,command=canvas1.yview)
    myscrollbar.grid(row=0,column=200, sticky=tk.NS)
    canvas1.configure(yscrollcommand=myscrollbar.set)
    canvas1.bind_all('<MouseWheel>', lambda event: canvas1.yview_scroll(int(-1*(event.delta/120)), "units"))
    canvas1.configure(scrollregion=canvas1.bbox("all"))

    b1 = tk.Button(frame, text="<<", command=on_prev)
    b1.grid(row=2, column=0)

    b2 = tk.Button(frame, text=">>", command=on_next)
    b2.grid(row=2, column=1)

window = tk.Tk()

mc1 = MyClass1()
mc1.generate_all_figures()

b1 = tk.Button(window, text="Next", command=on_window1)
b1.grid(row=0, column=0)

window.mainloop()

A: Your for loop is setting the descriptions all at once, you need to create a global variable to hold the figure number and then increment that value in your on_window1 function:
figure_num=0
def on_window1():
         ...
   global figure_num
   figure_num+=1
   l3 = tk.Label(canvas1, text="Figure Number:" + str(figure_num))
   canvas1.create_window(50,21*figure_num, window=l3, anchor=tk.NW)


text:
Q: Composite Key with Date Key I have a Dimension which uses a composite Primary key to identify a single row (3 keys), and one of those keys happens to be the Date from the Source Table. This Date from the Source i do a Left Join join with the Date Dimension to populate the Fact Table.  Is it a problem that i would have Date in the Fact table (FK_Date) and also in this Dimension?
CREATE TABLE [dbo].[Dim_Stg_Visitor]
(
    [TestCall] INT NOT NULL,
    [VisitorTD] INT NOT NULL,
    [Date] Date NOT NULL,
    [ISP] NVARCHAR(250) NOT NULL,
    [Origin] INT NOT NULL,
    [SubOrigin] INT NOT NULL,
    [Page] INT NOT NULL,
    [SubContact] INT NOT NULL,
    ...
    PRIMARY KEY (TestCall, VisitorTD, Date)
);


text:
Q: `xdg-open` does not open files in the preferred applicaton xdg-open does not work as expected. It opens most my files in browser, directories in my code editor(VS code) and plain text files using less. It also throws this error message,
$ xdg-open $HOME
xdg-mime: mimetype argument missing
Try 'xdg-mime --help' for more information.

then it opens the folder in my code editor. Whereas,
$ xdg-mime query default inode/directory
org.gnome.Nautilus.desktop

the default file manager application is Nautilus. How do I fix this?

A: The following answer suggests that Gnome uses gvfs-open in the background.
https://unix.stackexchange.com/a/144048/421466
gvfs-open has been deprecated and the new command is gio open.
$ gio open
libffi.so.6: cannot open shared object file: No such file or directory

Running gio open threw this error. This error was due to python looking for libffi6.so file which wasn't present in my environment. I am using miniconda and there are other people as well who are facing this issue. Most of the answers suggests to create a symlink for libffi6.so or reinstall python,
https://github.com/conda/conda/issues/9957
https://stackoverflow.com/q/61875869/11701676
But simply installing libffi, using conda fixed the issue.
conda install libffi


text:
Q: Top users who are teenagers or underage I am 21 years old. I have always been fascinated when I see teens or young users on Stack Overflow, who are younger than me but in reputations wise, ah!!! I can't compare with mine. They are at that much heights.
And, I have been telling my friends about such users.
In most of the cases, such users' reputation will be more than 10 times of mine.
And the more fascinating fact, is that a subset of such users gained that reputation in less time on SO (i.e they will have been a member for just one year or less).
Ok. I could mention BoltClock as one such user (also a moderator).
Now, if I sort users based on reputation/memberfor(indays) , and then by ascending order of age, I think I could get my heroes in the front page.
But sadly, there is no such option on SO.
So, could you pick some top 10 such users so that I could at least read their blogs, visit their websites, follow them on Twitter, Facebook and at last share them to my friends.
It would also useful for me, if I get some hints on how to learn concepts that much quickly as them.
Whether it is inborn skill, or it needs a specific method of learning?

A: This is actually very easy with a simple Data.SE query:
https://data.stackexchange.com/stackoverflow/query/110601
SELECT TOP 50
  Id as [User Link],
  Reputation,
  Age
FROM Users
WHERE Age < 20
ORDER BY Reputation DESC

Obviously it doesn't have a lower limit, because if you have significant any rep at age 12, you're epic!


text: Q: Google authentication screen inside application I am using Google auth token for signing in my app. All is working fine but for the first time whenever a user sign in in my application it shows message token could not be found (because user hasnt given permisson to acces its gmail account ) and  it gives a notification on clicking on it a screen opens for asking to access my app some of there account data.So user have to again open my application  after giving permission.My question is this  can't I open that page for asking user to permit access inside application only? If yes then how?


text:
Q: Como guardar variables dentro de un for He conseguido que en un bucle pregunten los datos de una persona, puede ser de 1 a 3 como max, y al final de preguntar a todas las personas hacer una funcion llamada informe y que diga los datos de cada una de ellas, tal como lo tengo me dice solo una persona, no sé muy como se debería hacer, pongo también los metodos o funciones que estoy usando por si os sirve de ayuda...
    Scanner sc=new Scanner (System.in);
    //todo No consigo hacer que una vez pedido 1,2,3 personas me las guarde el informe...
    int i;
    String nombrePersona;
    String apellidoPersona;
    byte edadPersona;
    String nacionalidadPersona;
    boolean gen;
    int numeroPersonas = cuantasPersonas();
    for ( i = 0; i < numeroPersonas; i++) {
        System.out.println("Voy a pedir datos de una persona (pedir nombre, nacionalidad)");
        nombrePersona = pideNombre ("Dime tu nombre");
        apellidoPersona= pideNombre ("Dime tu 1º apellido");
        System.out.println("Dime tu edad");
        edadPersona = pideedad ();
        nacionalidadPersona=pideNombre ("Dime tu nacionalidad");
        gen =generos ("Eres Hombre/Mujer");
    }
    System.out.println("");
}

public static String informe(String nombre, String apellido, byte edad, String nacionalidad,boolean genero) {
    return nombre +" "+ apellido +", de "+ edad + " años , y nacionalidad " + nacionalidad + " Su género es" + genero;
}

public static boolean generos (String pregunta){
    Scanner scan = new Scanner(System.in);
    String gen;
    do {
        System.out.println(pregunta);
        gen=scan.nextLine();
    }while (!gen.equals("Hombre")&&!gen.equals("Mujer"));

    if(gen.equals("Hombre")){
        return true;
    }
    return false;
}

public static String pideNombre(String mensaje) {
    Scanner scan = new Scanner(System.in);
    System.out.println(mensaje);
    return scan.nextLine();
}
/**
* Sirve para pedir el total de personas que vamos a pedir los datos
* @param personas Cantidad de personas que vamos a pedir los datos
* @return el numero de personas que vamos a pedir los datos
*/

public static int cuantasPersonas ( ){
    Scanner scan=new Scanner (System.in);
    int personas;
    do{
        System.out.println("Cuantas personas quieres pedir los datos, debe de ser entre 1 y 3");
        personas=Integer.parseInt(scan.nextLine());
    } while (personas>=4||personas<1);
    return personas;

    public static Byte pideedad() {
        Scanner scan = new Scanner(System.in);
        return Byte.parseByte(scan.nextLine());
    }
}

A: Si no deseas crear una clase Persona solo necesitas hacerle unas pequeñas modificaciones al código. Lo que sucede es que estas utilizando las mismas variables para guardar los datos de cada una de las personas lo que hace que los valores se sobrescriban, para solventar este problema puedes hacer uso de arreglos:
import java.util.Scanner;

public class Main {

    public static String informe(String nombre, String apellido, byte edad, String nacionalidad, boolean genero) {
        return nombre + " " + apellido + ", de " + edad + " años , y nacionalidad " + nacionalidad + " Su género es" + genero;
    }

    public static boolean generos(String pregunta) {
        Scanner scan = new Scanner(System.in);
        String gen;
        do {
            System.out.println(pregunta);
            gen = scan.nextLine();
        } while (!gen.equals("Hombre") && !gen.equals("Mujer"));
        return gen.equals("Hombre");
    }

    public static String pideNombre(String mensaje) {
        Scanner scan = new Scanner(System.in);
        System.out.println(mensaje);
        return scan.nextLine();
    }

    /**
     * Sirve para pedir el total de personas que vamos a pedir los datos
     *
     * @param personas Cantidad de personas que vamos a pedir los datos
     * @return el numero de personas que vamos a pedir los datos
     */
    public static int cuantasPersonas() {
        Scanner scan = new Scanner(System.in);
        int personas;
        do {
            System.out.println("Cuantas personas quieres pedir los datos, debe de ser entre 1 y 3");
            personas = scan.nextInt();
        } while (personas >= 4 || personas < 1);
        return personas;

    }

    public static Byte pideEdad() {
        Scanner scan = new Scanner(System.in);
        return scan.nextByte();
    }

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int numeroPersonas = cuantasPersonas();
        String[] nombrePersona = new String[numeroPersonas];
        String[] apellidoPersona = new String[numeroPersonas];
        byte[] edadPersona = new byte[numeroPersonas];
        String[] nacionalidadPersona = new String[numeroPersonas];
        boolean[] gen = new boolean[numeroPersonas];
        for (int i = 0; i < numeroPersonas; i++) {
            System.out.println("Voy a pedir datos de una persona (pedir nombre, nacionalidad)");
            nombrePersona[i] = pideNombre("Dime tu nombre");
            apellidoPersona[i] = pideNombre("Dime tu 1º apellido");
            System.out.println("Dime tu edad");
            edadPersona[i] = pideEdad();
            nacionalidadPersona[i] = pideNombre("Dime tu nacionalidad");
            gen[i] = generos("Eres Hombre/Mujer");
        }

        System.out.println("");

        // Mostrando los datos
        for (int i = 0; i < numeroPersonas; i++) {
            System.out.println("Persona #" + (i + 1));
            System.out.println("Nombre: " + nombrePersona[i]);
            System.out.println("Apellido: " + apellidoPersona[i]);
            System.out.println("Edad: " + edadPersona[i]);
            System.out.println("Nacionalidad: " + nacionalidadPersona[i]);
            System.out.println("Genero: " + (gen[i] ? "Hombre": "Mujer"));

            System.out.println("");
        }
    }

}

Otra forma mucho mas sencilla sería crear una clase persona con todos esos datos y guardar cada objeto en una lista o arreglo.


text:
Q: What is a Fractional Remainder in the context Python's division always returning a float? What is a Fractional Remainder in Python? In the context of division in Python:
>>> 2 / 1
2.0

Excerpt from the book Learning Python by Mark Lutz to provide the context to the question:
enter image description here

A: The Modulo expression returns remainders
2 % 1 => 0
3 % 2 => 1
5 % 3 => 2

According to text, they are explaining how Python reads expressions.
 5 / a + b ==> (5 / a) + b

Where:
 5 / (a + b) != 5 / a + b

A: My best interpretation of "always retains fractional remainders" is the author means that, in Python 3, the / operator performs a floating-point division. The author is trying to say that the fractional part of the quotient, not the remainder, is retained. E.g., in 7/4, the result is 1.75, keeping the .75, rather than 1, discarding the .75. The author is incorrect to call this a "fractional remainder."


text:
Q: tcl return file name chosen by user Been banging my head against this for a day now, reminds me of learning MFC 20 odd years ago :-(
I want the user to choose a file name. Having chosen it, I want to be able to use the file name in other parts of the program. My efforts to date have ended with this:
package require Tk

wm title . "get user specified file name (how hard can it be?)"

labelframe .lfInput -text "user specified file name goes here"

set userChoice "userChoice is bound to this field"
# note not $userChoice in next line
entry .lfInput.ent -width 40 -textvariable userChoice
button .lfInput.but -text "Kindly press this button and choose a file.\nNot only will I write the file name\nin the the field to the left, I'll make\nit available to anyone who cares\n to press the button below."\
 -command "fileDialog .lfInput .lfInput.ent"

pack .lfInput.ent -side left -padx 10 -expand yes -fill x
pack .lfInput.but -side left -padx 10 -pady 3
pack .lfInput -fill x -padx 2c -pady 3
focus .lfInput.ent

button .b -text "Press this button to write\nuserChoice to the console\nthereby demonstrating\nthe ability to get a file\nname from the user."\
    -command "writeTheArg {$userChoice}"
pack .b

proc fileDialog {w ent} {
    set types { {"All files"       *} }

    set userFile [tk_getOpenFile -multiple false -filetypes $types -parent $w -typevariable "All files"]

    if {[string compare $userFile ""]} {
        $ent delete 0 end
        $ent insert 0 $userFile
        $ent xview end
    }

    puts "line 34: local userFile is $userFile"
}

proc writeTheArg {s} {
    puts "line 38: puts $s"
}

puts "line 41: user choice is {$userChoice}"
puts "when pressing second button, the file chosen by the user should show up here\n\
      by virtue of the textvariable option at line 9\n...\n"

This is overkill for it's stated purpose, anything we do here could have been done in proc fileDialog. However if there were more user choices to collect
presumably we could sort them all out in proc UpdatedUserFile and proceed.
proc fileDialog should return a local $userFile, it's all about remembering the $$$

A: The simplest method is to use a global variable.
proc fileDialog {w ent} {
    global userFile
    set types { {"All files"       *} }

    set file [tk_getOpenFile -filetypes $types -parent $w]

    if {[string compare $file ""]} {

        # Only update the global if the user didn't cancel
        set userFile $file

        $ent delete 0 end
        $ent insert 0 $userFile
        $ent xview end
    }

    puts "line 34: local userFile is $userFile"
}

The rest of your code can then read that global to get the file. The main tricky bit is that the global will change when the user accepts a file in the dialog; you handle that by setting a write trace on the userFile global variable, and update the UI when that changes. Of course, you can do the easiest version of this by using the -textvariable option of a label: that sets the trace for you behind the scenes so it always shows you the current contents of the variable:
pack [label .showTheUserFile -textvariable userFile]

You only need to set the trace directly (with trace) for more complex interactions:
trace add variable userFile write UpdatedUserFile
proc UpdatedUserFile {args} {
    # Note that we're ignoring the arguments to the callback here; we only ever apply
    # this trace to one event on one variable so we know what's going on without
    # being told explicitly

    # Here's a very simple version; for more complicated versions, see your imagination!

    global userFile
    puts "The user has selected the file $userFile"
}

A: The problem I was having (and still am) is forgetting to use $ to reference a variable. This leads to bizarre errors when trying to pass parameters and can lead the inexperienced to start doing weird and wonderful things, as in the original question. Thanks for the help, I think I'd have given up altogether otherwise!
Proper version follows:
package require Tk

wm title . "get user specified file name"

labelframe .fileSelectorGroup -text "press the button to choose your file"

set userFileChoice "userFileChoice is bound to this field"
# note not $userFileChoice in next line
entry .fileSelectorGroup.ent -width 40 -textvariable userFileChoice
button .fileSelectorGroup.but -text "Kindly press this button and choose a file.\nNot only will I write the file name\nin the the field to the left, I'll make\nit appear in the console."\
 -command "getUserFileAndProceed .fileSelectorGroup .fileSelectorGroup.ent"

pack .fileSelectorGroup.ent -side left -padx 10 -expand yes -fill x
pack .fileSelectorGroup.but -side left -padx 10 -pady 3
pack .fileSelectorGroup -fill x -padx 2c -pady 3
focus .fileSelectorGroup.ent

proc getUserFileAndProceed {w ent} {
    set userChoice [fileDialog $w $ent]
    puts "line 21: userChoice is $userChoice"
    puts "have a nice day"
}

proc fileDialog {w ent} {
    set types { {"All files"       *} }

    set userFile [tk_getOpenFile -multiple false -filetypes $types -parent $w -typevariable "All files"]

    if {[string compare $userFile ""]} {
        $ent delete 0 end
        $ent insert 0 $userFile
        $ent xview end
    }

    return $userFile
}


text:
Q: Is there a serialization overhead in unindexed lists stored in app engine datastore? My understanding is indexed lists on app engine are stored by duplicating all data for each value of the list. So multiple lists create cartesian product type explosions, and getting an entity requires gathering all of these "rows" (up to 5000) into 1 entity which google calls serialization overhead, and is best avoided. Is my understanding correct?
If this is how app engine works I am wondering if an unindexed list is stored in the same way (requires the same data duplication, and the same serialization overhead) or if they are stored in binary or something since you never need to know what they are for querying/retrieving.
So I guess what I'm asking is: Do unindexed lists have serialization overhead and a 5000 row limit? If so how can avoid this.
Thanks

A: You're confusing two different topics here. Indexed and unindexed lists alike are stored as part of a serialized entity protocol buffer, with each element of the list stored separately. There's space overhead here, since the name of the property is stored with each element - foo = [1,2,3] gets stored as [(foo, 1), (foo, 2), (foo, 3)], in effect.
Indexed lists are automatically added to the built-in indexes, with each list element requiring an index row. If you have two lists with 5 elements each, 10 index rows will be required in the built-in indexes.
If you use custom indexes to define an index on multiple list properties, or the same list property multiple times, every unique combination of items will be indexed. So an entity with two lists a=[1,2,3] and b=[4,5,6] and an index on a and b will generate index entries [(1, 4), (1, 5), (1, 6), (2, 4), (2, 5), (2, 6), (3, 4), (3, 5), (3, 6)], and an entity with one list c=[7,8,9,10] and an index on c twice will generate index entries [(7, 8), (7, 9), (7, 10), (8, 9), (8, 10), (9, 10)]. These are what's referred to as exploding indexes, and only occur in custom indexes that specify at least two instances of list properties in a given index.
Unindexed list properties still take the same amount of space in the entity protocol buffer and still require the same time to serialize and deserialize that PB, but don't have any of the index overhead.


text:
Q: (others too)picasso is not working with simple image display using URL dependency=implementation "com.squareup.picasso:picasso:2.4.0"

String url1="https://www.google.com/search?

    ImageView image;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        image= (ImageView)findViewById(R.id.image);

        Picasso.with(this)
                .load(url)
                .placeholder(R.drawable.ic_launcher_foreground)
                .resize(200,200)         //optional
                .centerCrop()            //optional
                .into(image);
    }
}

A: First please add this URL, and confirm that the image is not uploading:
https://cdn.pixabay.com/photo/2015/04/23/22/00/tree-736885__480.jpg

Picasso.with( context )
        .load( your_path )
        .error( R.drawable.ic_error )
        .placeholder( R.drawable.progress_animation )
        .into( image_view );


text:
Q: setcookie and ask cookie value for voting system I want to set a cookies to get the users only vote once in 4 categories (sad, enraging, funny, cool).
I'm a beginner so I know my code is very inconvenient but it is my first try and so it doesen't matter to me if I have a few lines more or less.
For some reason the browser won't load the vote.php files (that are called when the user clicks one voting option). I just can't find the error...maybe someone sees it immediatly?
[Before I inserted the cookie thing the code files loaded perfectly, so the calling isn't the matter.]
<?php
require_once('connect.php');
$newsid = $_POST['id'];

if (isset($_POST['submit'])) {
    if(isset($_COOKIE['votecookie']) && $_COOKIE['votecookie'] !== 'sad') {
        if($_COOKIE['votecookie'] == 'cool') {
            $query = mysql_query('UPDATE `index` SET cool=cool-1 WHERE id = {$newsid}');
        }
        if($_COOKIE['votecookie'] == 'funny') {
            $query = mysql_query('UPDATE `index` SET funny=funny-1 WHERE id = {$newsid}');
        }
        if($_COOKIE['votecookie'] == 'sad') {
            $query = mysql_query('UPDATE `index` SET enraging=enraging-1 WHERE id = {$newsid}');
        }
        setcookie('votecookie', 'sad');
        $query = mysql_query('UPDATE `index` SET sad=sad+1 WHERE id = '{$newsid}'');
        $hosts = $_SERVER['HTTP_HOST'];
        $uris = rtrim(dirname($_SERVER['PHP_SELF']), '/\\');
        $extras = 'news.php?id={$newsid}&sad=1';
        header('Location: http://$hosts$uris/$extras');
        exit;
    }
    if(!isset($_COOKIE['votecookie']) {
            setcookie('votecookie', 'sad');
            $query = mysql_query('UPDATE `index` SET sad=sad+1 WHERE id = '{$newsid}'');
            $hosts = $_SERVER['HTTP_HOST'];
            $uris = rtrim(dirname($_SERVER['PHP_SELF']), '/\\');
            $extras = 'news.php?id={$newsid}&sad=1';
            header('Location: http://$hosts$uris/$extras');
            exit;
        }

        if(isset($_COOKIE['votecookie']) && $_COOKIE['votecookie'] == 'sad') {
            $hosts= $_SERVER['HTTP_HOST'];
            $uris = rtrim(dirname($_SERVER['PHP_SELF']), '/\\');
            $extras = 'news.php?id={$newsid}&sad=0';
            header('Location: http://$hosts$uris/$extras');
            exit;
        }
        }
    else {
        $hosts= $_SERVER['HTTP_HOST'];
        $uris = rtrim(dirname($_SERVER['PHP_SELF']), '/\\');
        $extras = 'news.php?id={$newsid}&sad=0';
        header('Location: http://$hosts$uris/$extras');
        exit;
        ?>

A: If someone is interested in the answer: This is how I did it now (I had a few more mistakes in my code and an error in reasoning).
<?php
require_once('connect.php');
$newsid = $_POST['id'];
if (isset($_POST['submit'])) {
    if(isset($_COOKIE[$newsid]) && $_COOKIE[$newsid] != 'sad') {
        if($_COOKIE[$newsid] == 'cool') {
        $query = mysql_query("UPDATE `index` SET cool=cool-1 WHERE id = '{$newsid}'");
        }
        if($_COOKIE[$newsid] == 'funny') {
        $query = mysql_query("UPDATE `index` SET funny=funny-1 WHERE id = '{$newsid}'");
        }
        if($_COOKIE[$newsid] == 'enraging') {
        $query = mysql_query("UPDATE `index` SET enraging=enraging-1 WHERE id = '{$newsid}'");
        }
    $query = mysql_query("UPDATE `index` SET sad=sad+1 WHERE id = '{$newsid}'");
    setcookie($newsid, "sad", time() + (10 * 365 * 24 * 60 * 60));
    $hosts = $_SERVER['HTTP_HOST'];
    $uris = rtrim(dirname($_SERVER['PHP_SELF']), '/\\');
    $extras = "news.php?id={$newsid}&sad=1";
    header("Location: http://$hosts$uris/$extras");
        exit;
    }
    if(!isset($_COOKIE[$newsid])) {
        $query = mysql_query("UPDATE `index` SET sad=sad+1 WHERE id = '{$newsid}'");
        setcookie($newsid, "sad", time() + (10 * 365 * 24 * 60 * 60));
        $hosts = $_SERVER['HTTP_HOST'];
        $uris = rtrim(dirname($_SERVER['PHP_SELF']), '/\\');
        $extras = "news.php?id={$newsid}&sad=1";
        header("Location: http://$hosts$uris/$extras");
            exit;
    }
    if(isset($_COOKIE[$newsid]) && $_COOKIE[$newsid] == 'sad') {
        $hosts= $_SERVER['HTTP_HOST'];
        $uris = rtrim(dirname($_SERVER['PHP_SELF']), '/\\');
        $extras = "news.php?id={$newsid}&sad=0";
        header("Location: http://$hosts$uris/$extras");
            exit;
    }
}
else {
    $hosts= $_SERVER['HTTP_HOST'];
    $uris = rtrim(dirname($_SERVER['PHP_SELF']), '/\\');
    $extras = "news.php?id={$newsid}&sad=0";
    header("Location: http://$hosts$uris/$extras");
    exit;
}
?>


text:
Q: Recurrence relation to closed form of generating function I have the following recurrence relation:
$$a_n=F_0a_{n-1}+F_1a_{n-2}+F_2a_{n-3}...+F_{n-1}a_0
$$
with $a_0=5$ and $F_n$ being the nth Fibonacci number. How would I find the closed form of the generating function of this? The Fibonacci sequence is really confusing me here, and I'm not sure where to start.

A: Let
$$f(x)=\sum_{n\geq 0}a_n\, x^n. \tag{1}$$
Since:
$$g(x)=\sum_{n\geq 0}F_n\,x^n = \frac{x}{1-x-x^2}\tag{2}$$
and, for every $n\geq 1$:
$$ [x^n](f(x))=a_n=F_0 a_{n-1}+\ldots F_{n-1} a_0 = [x^{n-1}]\left(f(x)\cdot g(x)\right)\tag{3}$$
we have (by multiplying both sides of the previous line by $x^{n-1}$ and summing over $n\geq 1$):
$$ \frac{f(x)-5}{x}=f(x)\cdot g(x)\tag{4}$$
from which it follows that:

$$ f(x) = 5\cdot\frac{1-x-x^2}{1-x-2x^2}.\tag{5}$$


text:
Q: How do I create a string containing A of an arbitrary length in bash? How do I create a string of arbitrary length containing A's in bash?
In Ruby or Python, to create a string 5 characters long, I'd do:
'A' * 5 #-> 'AAAAA'


text:
Q: javascript odometer restarts at zero with postback I have two javascript odometers that are used to display cyclists mileages as miles YTD, and # of centuries. They should update only when the cyclist adds miles to their log, however, at this time they are going back to zero and rolling up to the same total with every pageback. This is the js on the design (aspx) page

Then, in the body the odometers are displayed:

The code behind retrieves the mileages from SQL and assigns that value to a variable that is passed to   the aspx. I can see that the values will be updated too often, since the code that pulls from SQL is in the page load event, but I don't know how to fix it. If anyone has experience with this please give me a clue or  two.

*

*How do you initialize the odometer on open to the current mileage?

*Should I be using an update panel? and if so do I use one for each odometer?


text:
Q: onclick triggered automatically - how to create button on the fly I tried to search through similar questions but I can't get a solution.
I have a snippet of code which is creating some HTML to append to a div:
      var list="
";
      for(i=0; i<data.length; i++) {

        sid=data[i].sid;
        list += "blablabla delete
";
      }
      list +="
";
      document.getElementById("my_container").innerHTML = list;

The function delete(sid):
function delete(Sid){
  doSomething(taskSid,
  function(error) {
    if(error) {
        console.log(error.code);
        console.log(error.message);
        return;
    }
    console.log("deleted");
}
);

The problem is that the function delete(sid) is called automatically.
I have read that it's because I am calling directly the function, and I have tried different proposed solutions, but cannot really make them work.
My code will create a several rows which have this button or link which need to call the function delete.
Probably it is completely wrong also the approach of having one container and define the list in javascript?
Any help appreciated.
Thanks

A: You should try binding the function
delete

Something like this bind prepares your listener to be executed here you are calling the function so because of that it get executed right away. You can also try arrow function here and calling delete function from inside it, like this
delete(sid)>delete

A: Better approach is to use createElement method. Something like this:
let list = document.createElement('ul');
for(i = 0; i<data.length; i++) {
   let sid=data[i].sid;
   let link = document.createElement('li');
   link.innerHTML = 'delete';
   link.onclick = function(){
      deleteTask(sid);
   };
   list.appendChild(link);
}
document.getElementById("my_container").appendChild(list);