text:
Q: Can Fortify scan results be saved into a file? Can I save fortify scan results into a file, so I can send to someone to Analyze them?

A: You can run a report using Audit Work Bench or Software Security Center. PDF reports typically don't contain enough detail to see all of the information regarding a vulnerability, but if the other person doesn't have Fortify it's better than nothing.
You can also try posting Fortify issues to their online forum at https://protect724.hp.com. The support group monitors those forums.


text:
Q: Permanently deleted files from the desktop (OneDrive cloud) The most terrible problem of every person or teenager has arisen. I decided to clean the computer, as I noticed that the "C" disk was clogged. Logged into the WizTree app. I scanned it, saw where it was most busy, and began deleting files. And accidentally deleted the OneDrive folder that had the Desktop folder in it. Everything you need has been deleted. In particular, the folder with all the photos of my mom, where there were a lot of photos, about 10 GB for sure.
Scoured the entire Internet, how to recover deleted files. Nothing helps, Recuva sees nothing at all. What can be done at all in this situation?

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to make a generic of generic with trait? pub struct Triangle<T: Float + std::clone::Clone, V: vector::Vector<T>> {
    point1: V,
    point2: V,
    point3: V,
}

This chunck of code doesn't compile because T isn't used (Nevertheless, T is used later in a method)
I have tried this syntax
pub struct Triangle<V: vector::Vector<T: Float + std::clone::Clone>> {
    point1: V,
    point2: V,
    point3: V,
}

Error:
expected one of `!`, `(`, `+`, `,`, `::`, `<`, or `>`, found `:`

expected one of 7 possible tokens here

and this syntax
pub struct Triangle2<V> where V: vector::Vector<T> where T: Float {
    point1: V,
    point2: V,
    point3: V,
}

Error:
expected `where`, or `{` after struct name, found keyword `where`

expected `where`, or `{` after struct name

that doesn't work.
Is there a way to fix this problem?

A: I assume your type Vector looks more or less like this.
pub trait Vector<T> {
    // Some functions
}

The solution is to declare multiple generic types and to list their type constraints individually: Type V must implement Vector<T> and type T in turn must implement Float and Clone.
pub struct Triangle<V, T>
where
    V: vector::Vector<T>,
    T: Float + Clone,
{
    point1: V,
    point2: V,
    point3: V,
    phantom: PhantomData<T>,
}

I'm using std::marker::PhantomData to save the otherwise unused type information.
Link to full working code.


text:
Q: Django user groups only for permissions? I'm a bit unsure what to use Django user groups for.
I have an application where every user belongs to a different organisation. The organisations don't have anything to do with read/write permissions. It's just a way to separate groups of users. Every organisation needs some additional fields, like a name, URL, and email address. New organisations will be added to the system over time.
Within every organisation, users can have different permissions for moderation and administration, for which I (also) want to use user groups.
My question: Should I use Django's user groups to define the organisations, or should I just make an 'Organisation' model with a relation to the user?

A: Nope. User groups are made for different reasons. You CAN use them to define organisations but  I think you should think bit further ahead:

*

*will the organisation require more fields than just name?

*perhaps you will need permissions in the future to define users roles within organisations?

I'm sure you can come up with more things to think of. But if you answered yes to one of those questions then just create your Organisation model.

A: 1) You need to add group from django admin side under group table.
2) And while creating new user, assign specific group to user using user_obj.groups.add(group_id). Or Let user select group at frontend.
and then user_obj.save()
in Group table, you can create organization
OR
You can create individual organization table and assign assign user to specific organization.


text:
Q: designing android ui in java instead of xml? anyone know some good guides for this? there seems to be almost nothing out there. the best I've found is this but it isn't very comprehensive.
also, I'm really new to android development. I know there are resources like the api out there but I'm looking for more of a guide, and doing the ui in java just seemed more appealing than xml.

A: The lack of guides in this matter is simple: Android UI is designed around XML layouts. Building your UI with XML is far more superior to building it programmatically (please refer to my comment to your post for some of the reasons). Adding and tweaking some UI components in the code is common but should not replace but rather supplement the XML-based UI.
You may also consider defining reusable components in XML and then to use Activity#getLayoutInflater to "inflate" these snippets. For example that's how items in the list are frequently build. And of course nothing stops you from building your layouts and components entirely within your code. Good practice there would be to create these once in the Activity#onCreate and then reuse throughout the rest of the code


text: Q: Affine transformation of different sized polygons layer to equal area units I would like to transform a layer of polygons of different sizearea to become equal in areasize. I have QGIS 2.18 and GRASS GIS 7 available and some basic Python knowledge. Does anyone have an idea of how to do that?


text:
Q: Graphing of $y = (x^2 - a)^2$ I was graphing the equation $y = x^2 - a$ and I know why the graph is a parabola intersecting at the points $(-1,0)$ and $(1,0)$.
However, when I graph $y = (x^2 - a)^2$, the graph oddly changes, as if two parabolas have subtracted each other. The greater the value of $a$ gets, the further up this change occurs.
I understand that the $a$ is squared, so as it is further increased/decreased away from $0$, the $y$ intercept changes.
From a mathematical perspective, how can this be explained further - why it looks like the subtracting each other?
Thanks.

A: If $a>0$ is the same in the two functions, the correct graph is this.

Note that $y=x^2-a$ is a parabola that has negative values $y<0$ in the interval $x \in(-\sqrt{a},\sqrt{a})$.
For the squared equation $y=(x^2-a)^2$ we can have only positive values, so the graph become positive in the interval $(-\sqrt{a},\sqrt{a})$, but we have always $y=0$ for $x=\pm \sqrt{a}$, so these values are roots of the function and are also local minima. They are double roots i.e. values in which the function an its derivative are $0$.
Also note that the intercept at $x=0$ is simply the square of $a$.


text:
Q: Median of Medians algorithm not working consistently I have implemented the select/median of medians algorithm using the following as a reference http://www.ics.uci.edu/~eppstein/161/960130.html (this has previously been linked here Median of Medians in Java).
My code seems to work for small arrays (~100) and even works for arrays of size 100001 http://pastebin.com/mwRc4Hig (answer 5008), but then fails on an input array of size 10001 http://pastebin.com/YwVBmgDk (answer 4960, my code outputs 4958).
Note that the correct answers for the texts above are equivalent to sorting the array and returning the element at array[array.length / 2], regardless of whether the array size is even or odd.
I'm not sure how to debug this issue. The functionality seems arbitrary and I'm just lost. Here below is my code:
public class MedianOfMedians {

public static void main(String[] args) {
    MedianOfMedians mds = new MedianOfMedians();
    mds.run();
}

private void run() {
    Scanner in = new Scanner(System.in);
    int n = in.nextInt();
    int[] numArray = new int[n];
    for (int i = 0; i < n; i++) {
        numArray[i] = in.nextInt();
    }
    int median = select(numArray, numArray.length / 2);
    System.out.print(median);
}

private int select(int[] numArray, int k) {
    if (numArray.length <= 10) {
        int[] sorted = insertionSort(numArray);
        return sorted[k];
    }

    int divCount = (numArray.length % 5 == 0) ? numArray.length / 5 - 1 : numArray.length / 5;
    int[] medOfMed = new int[divCount + 1];
    int counter = 0;
    int[] subArray;

    while (counter <= divCount) {
        subArray = splitByFive(counter, divCount, numArray);
        medOfMed[counter] = select(subArray, subArray.length / 2);
        counter++;
    }

    int M = select(medOfMed, numArray.length / 10);

    List<Integer> lt = new ArrayList<>();
    List<Integer> eq = new ArrayList<>();
    List<Integer> gt = new ArrayList<>();
    for (int i : numArray) {
        if (i < M) {
            lt.add(i);
        } else if (i == M) {
            eq.add(i);
        } else {
            gt.add(i);
        }
    }
    if (k < lt.size()) {
        return select(createArray(lt), k);
    } else if (k > lt.size() + eq.size()) {
        return select(createArray(gt), k - lt.size() - eq.size());
    } else {
        return M;
    }
}

private int[] splitByFive(int splitIter, int divisions, int[] toSplit) {
    int numToCopy;
    if (splitIter == divisions) {
        numToCopy = toSplit.length - (5 * splitIter);
    } else {
        numToCopy = 5;
    }
    int[] subArray = new int[numToCopy];
    System.arraycopy(toSplit, splitIter * 5, subArray, 0, numToCopy);
    return subArray;
}

private int[] createArray(List<Integer> list) {
    int[] result = new int[list.size()];
    for (int i = 0; i < list.size(); i++) {
        result[i] = list.get(i);
    }
    return result;
}

private int[] insertionSort(int[] numArray) {
    for (int i = 1; i < numArray.length; i++) {
        int j = i;
        while (j - 1 >= 0 && numArray[j] < numArray[j - 1]) {
            int temp = numArray[j];
            numArray[j] = numArray[j - 1];
            numArray[j - 1] = temp;
            j--;
        }
    }
    return numArray;
}
}

A: I don't have time to debug your code, but maybe I can offer a debugging technique for you to try yourself that's useful for recursive algorithms like this.
If there is an input that the algorithm fails on (and there is, as you found) then there is a smallest such input -- and the smaller this input, the easier it is to figure out what's going wrong.  Because the algorithm is recursive, you have a nice way to isolate the first place that things go wrong: you can test that the result you are about to return from select() is correct (using a slow, trusted method like copying the data to a temporary buffer, sorting it and then grabbing the half-way element) just before returning the value.  Doing this will be much easier if you rearrange the function to use just a single return statement, e.g.:
private int select(int[] numArray, int k) {
    int knownCorrectAnswer = selectSlowlyButDefinitelyCorrectly(numArray, k);
    int willReturn;
    if (numArray.length <= 10) {
        int[] sorted = insertionSort(numArray);
        willReturn = sorted[k];    // Just remember what we will return
    } else {    // Need to add else branch here now

        ...

        if (k < lt.size()) {
            willReturn = select(createArray(lt), k);
        } else if (k > lt.size() + eq.size()) {
            willReturn = select(createArray(gt), k - lt.size() - eq.size());
        } else {
            willReturn = M;
        }
    }    // End of inserted else branch

    if (willReturn == knownCorrectAnswer) {
        return willReturn;
    } else {
        yell("First problem occurs with numArray=<...> and k=<...>!");
    }
}

yell() should print out the entire problem instance and halt the program (e.g. by throwing an exception).  The nice thing about this setup is that you know that when yell() gets called, every call to select() that has already completed was correct -- since if it wasn't, yell() would have already been called and the program would have halted before now.  So the output produced by yell() is guaranteed to be the first (not necessarily the smallest, but often that also) subproblem in which things went wrong.


text:
Q: Averaging accumulated cost surfaces/shortest paths [r] [gdistance] I'm trying to find a way to be able to average two accumulated cost surfaces so I can find the optimal route from both A to B and B to A. Although the difference is cost surface is due to the travel direction, the travel route is the same for the origin and goal point, therefore I need to average these.
As can be seen, the accumulated cost surfaces are different based on whether the travel is from A to B or B to A. And so, the optimal route calculated differs.

Is there a way to average the two accumulated cost surfaces to create a new cost surface that is based on both travels?
reproducible code:
library(gdistance)
r <- raster(system.file("external/maungawhau.grd", package="gdistance"))

altDiff <- function(x){x[2] - x[1]}
hd <- transition(r, altDiff, 8, symm=FALSE)

slope <- geoCorrection(hd)

adj <- adjacent(r, cells=1:ncell(r), pairs=TRUE, directions=8)
speed <- slope
speed[adj] <- 6 * exp(-3.5 * abs(slope[adj] + 0.05))

Conductance <- geoCorrection(speed)

A <- c(2667670, 6479000)
B <- c(2667800, 6479400)
AtoB <- shortestPath(Conductance, A, B, output="SpatialLines")
BtoA <- shortestPath(Conductance, B, A, output="SpatialLines")

AtoBacc <- accCost(Conductance, A)
BtoAacc <- accCost(Conductance, B)

par(mfrow=c(1,3))
plot(AtoBacc, main="A to B")
plot(BtoAacc, main="B to A")

plot(r, xlab="x coordinate (m)", ylab="y coordinate (m)", legend.lab="Altitude (masl)", main="Both")
lines(AtoB, col="red")
lines(BtoA, col="blue")
text(A[1] - 10, A[2] - 10, "A")
text(B[1] + 10, B[2] + 10, "B")

I understand that the accumulated cost surface is a raster layer, and so I could just do a raster calculation. However, I would need to then convert it back into a transition layer, which would change the values.


text:
Q: SSTableLoader java.nio.Buffer.limit / Failed to list files Using SSTableLoader (data source instance and target of SSTableLoader are both cassandra 3.0.23), succeeds on all the tables except one:
How should I go about diagnosing this: (note, the folder in question, /var/lib/cass-bk-tmp/local/intervals, does appear to have the sstables and other data produced by nodetool snapshot)
Failed to list files in /var/lib/cass-bk-tmp/local/intervals
java.lang.IllegalArgumentException
java.lang.RuntimeException: Failed to list files in /var/lib/cass-bk-tmp/local/intervals
        at org.apache.cassandra.db.lifecycle.LogAwareFileLister.list(LogAwareFileLister.java:77)
        at org.apache.cassandra.db.lifecycle.LifecycleTransaction.getFiles(LifecycleTransaction.java:599)
        at org.apache.cassandra.io.sstable.SSTableLoader.openSSTables(SSTableLoader.java:76)
        at org.apache.cassandra.io.sstable.SSTableLoader.stream(SSTableLoader.java:165)
        at org.apache.cassandra.tools.BulkLoader.main(BulkLoader.java:106)
Caused by: java.lang.IllegalArgumentException
        at java.nio.Buffer.limit(Buffer.java:275)
        at org.apache.cassandra.utils.ByteBufferUtil.readBytes(ByteBufferUtil.java:669)
        at org.apache.cassandra.utils.ByteBufferUtil.readBytesWithShortLength(ByteBufferUtil.java:678)
        at org.apache.cassandra.db.marshal.CompositeType.splitName(CompositeType.java:201)
        at org.apache.cassandra.db.Serializers$1.deserialize(Serializers.java:88)
        at org.apache.cassandra.db.Serializers$1.deserialize(Serializers.java:60)
        at org.apache.cassandra.io.sstable.IndexHelper$IndexInfo$Serializer.deserialize(IndexHelper.java:148)
        at org.apache.cassandra.db.RowIndexEntry$Serializer.deserialize(RowIndexEntry.java:218)
        at org.apache.cassandra.io.sstable.format.SSTableReader.buildSummary(SSTableReader.java:825)
        at org.apache.cassandra.io.sstable.format.SSTableReader.openForBatch(SSTableReader.java:429)
        at org.apache.cassandra.io.sstable.SSTableLoader.lambda$openSSTables$0(SSTableLoader.java:121)
        at org.apache.cassandra.db.lifecycle.LogAwareFileLister.lambda$innerList$2(LogAwareFileLister.java:99)
        at java.util.stream.ReferencePipeline$2$1.accept(ReferencePipeline.java:174)
        at java.util.TreeMap$EntrySpliterator.forEachRemaining(TreeMap.java:2969)
        at java.util.stream.AbstractPipeline.copyInto(AbstractPipeline.java:482)
        at java.util.stream.AbstractPipeline.wrapAndCopyInto(AbstractPipeline.java:472)
        at java.util.stream.ReduceOps$ReduceOp.evaluateSequential(ReduceOps.java:708)
        at java.util.stream.AbstractPipeline.evaluate(AbstractPipeline.java:234)
        at java.util.stream.ReferencePipeline.collect(ReferencePipeline.java:566)
        at org.apache.cassandra.db.lifecycle.LogAwareFileLister.innerList(LogAwareFileLister.java:101)
        at org.apache.cassandra.db.lifecycle.LogAwareFileLister.list(LogAwareFileLister.java:73)
        ... 4 more

A: It looks like sstableloader is running into an issue when extracting the column name reading through the -Index.db file of one of the SSTables based on this section of the stacktrace:
  ...
  at org.apache.cassandra.db.marshal.CompositeType.splitName(CompositeType.java:201)
  at org.apache.cassandra.db.Serializers$1.deserialize(Serializers.java:88)
  at org.apache.cassandra.db.Serializers$1.deserialize(Serializers.java:60)
  at org.apache.cassandra.io.sstable.IndexHelper$IndexInfo$Serializer.deserialize(IndexHelper.java:148)
  at org.apache.cassandra.db.RowIndexEntry$Serializer.deserialize(RowIndexEntry.java:218)
  at org.apache.cassandra.io.sstable.format.SSTableReader.buildSummary(SSTableReader.java:825)
  ...

I don't have enough information to really understand what's going on but perhaps try to workaround it by loading a handful of SSTables at a time.
If you could load just one SSTable, it would at least confirm that it's not a mismatch between the schema in the target cluster and the schema of SSTable when the snapshot was taken. Cheers!


text:
Q: Microsoft edge browser crashes the JS engine on regex replace I found a way to mysteriously crash the edge JS interpreter but i have NO CLUE why it's broke. It works fine in firefox and chrome, but it blows up Edge entirely.
var foo = "Change or cancel my flight booking";
var match = "a";
foo.replace(new RegExp(match + "(?!([^<]+)?>)", 'gu'), '${match}');

The problem seems to be with the regex itself because if i swap that for empty string all goes well.
Really not sure how trying to match a regex could destroy the browser :(
Edit: For clarity, when executed via html in the browser, it goes into a non-responsive state. Nothing can be clicked and eventually edge asks if you want to close the page because its nonresponsive. When executed in the dev console, it doesn't print a return, and any further statements are never executed. You can keep typing, but nothing happens.

A: If I run the regex without the u Unicode flag no timeout or crash happens in Edge (or any other major browser):

var foo = "Change or cancel my flight booking";
var match = "a";
console.log(foo.replace(new RegExp(match + "(?!([^<]+)?>)", 'g'), '${match}'));

The ES2015 u flag for regular expressions is actually associated with a number of bugs on different browsers, e.g. the HTML pattern attribute is broken in Edge.
So, this issue seems to be a similar but different bug related to the u flag and should be reported on the Microsoft Edge issue tracker.


text:
Q: addEventListener not detecting children (even with bubbles) there's probably a very simple solution but I'm at my wit's end here.
I have a sprite called content
In this sprite there are multiple children that I add and remove (lot's of traffic there)
these children dispatch events that bubble.
I have an event listener listening to content and checking for the same type of event.
The order goes
content = new Sprite();
content.addEventListener(AttentionEvent.NEED_FOCUS,focusEventTarget);
content.addChild(new someChildThatDispatches());

this DOESNT work, however.
content = new Sprite();
content.addChild(new someChildThatDispatches());
content.addEventListener(AttentionEvent.NEED_FOCUS,focusEventTarget);

that works..
But the problem with the second model is that I would have to track every time something is changed in the children tree and add the event listener which kinda defeats the entire purpose of bubbling for me.
Does anyone know what I'm doing wrong?
Thank's in advance

A: strange, it should work with the first model…
do you mind posting your custom event manager?


text:
Q: Creating uiviewcontroller as weak programmatically I am creating uiviewcontroller in my one of the singleton like this.
BrowserVC *vc = [BrowserVC loadFromNib];
vc.titleName = @"Password Management";
[vc setData:@{@"url":url.absoluteString}];
vc.successBlock = ^(NSString *urlStr){
    if (![urlStr isEqualToString:url.absoluteString])
        [vc dismissViewControllerAnimated:YES completion:nil];
};

Then, I got this usual error.

Capturing 'vc' strongly in this block is likely to lead a retain
  cycle.

To solve that warning, I have used either __Weak or __unsafe_unretained. Now, problem come in. My vc is released immediately after I initiate. I can't even set titleName. How shall I do?

A: The pattern is this
BrowserVC *vc = [BrowserVC loadFromNib];
vc.titleName = @"Password Management";
[vc setData:@{@"url":url.absoluteString}];

__weak __typeof(vc) weakVC = vc;

vc.successBlock = ^(NSString *urlStr){
    __typeof(vc) strongVC = weakVC;

    if (strongVC && ![urlStr isEqualToString:url.absoluteString])
        [strongVC dismissViewControllerAnimated:YES completion:nil];
};

You create the view controller as you normally would but then you create a weak reference to the view controller and pass that into the block


text:
Q: How to know which terminal emulator I'm using? I heard there are plenty of terminal emulator: xterm, aterm, terminator, etc.
Since I'd like to play with the color escape code \033[, and wiki said some of its feature is not wildly support, so I need to know which terminal I'm running on.
I use Ubuntu 12.04 LTS, and pretty sure that I'm running on GNU Screen in GUI mode, but couldn't figure out which terminal I'm on when I hit Ctrl+Alt+F3.

A: You can run this command in your terminal.
echo $TERM

The output will be what kind of terminal emulator you are using.


text:
Q: Are these arguments to inflationary predictions in this Fact-Checking page legitimate? ISL(Anna Ijjas,Paul Steinhardt,Abraham Loeb) have put together a Fact-Checking page in response to the letter.
https://physics.princeton.edu/~cosmo/sciam/index.html#facts

In their letter, the authors claim four successful "predictions" of inflation to have been proven right by observations: (1) critical mass density; (2) nearly "scale-invariant" perturbations; that are (3) "adiabatic," and (4) "Gaussian."
  What the letter omits is that, before the observations were made, some of the same authors who signed the rebuttal wrote papers claiming exactly the opposites of (1) through (4) are also compatible with inflation.
One cannot claim a theory predicts an observation if the observation and the opposite outcome are both compatible with the theory.

I have read the detailed explanations and examples of the arguments in the link, unfortunately, I don't have enough knowledge to tell if these arguments are legitimate.

A: The simplest models of inflation are so-called canonical ("normal" kinetic energy term), single field (a single field, the inflaton, is responsible for both driving the inflationary expansion and generating the initial density perturbations), slow roll (smooth, gradually decreasing potential energy function) models.  These generically predict near-spatial flatness and a nearly scale invariant spectrum of Gaussian, adiabatic density perturbations.  Primordial gravitational waves may or may not be generated at observable levels by these models.  If any of these predictions are disconfirmed, then canonical, single field, slow roll inflation is false.
Inflation is a broad and phenomenologically rich paradigm, and there's much more to it than these simplest of models.  If the universe turns out not to be near-critical, then there's a model for this: so-called open inflation which was studied by Linde and others in the 90's before the universe was seen to be accelerating.  If the perturbations are non-Gaussian, then depending on the type, either the kinetic term is noncanonical, there is transient non-slow roll behavior, or there are multiple fields contributing to the generation of perturbations (the curvaton, for example).  If the spectrum is not nearly-scale invariant, then we either have non-slow roll behavior across some range of scales, or there are multiple fields driving inflation such that there are rather abrupt changes in "direction" in field space.  Another possibility is hybrid inflation which can generate a very blue spectrum ($n > 1.5$), but these models require an additional auxiliary field to end inflation, and so are not single field models. If the perturbations are non-adiabatic, then there's likely an isocurvature component, for instance, via the curvaton mechanism.
The point being that there are enough knobs to turn across the inflationary model space to accommodate a wide range of predictions.  But, the "generic" predictions: flatness, near scale invariance, Gaussian, adiabatic perturbations are the hallmark of the most basic and best studied family of models.  It is doubtless that this is the inflation that Guth, Linde and others are referring to in their statement, if not explicitly stated.


text:
Q: Toggle fullscreen I want a simple function for toggling full screen. Here is what I've written:
  function toggleFullScreen() {
    var elem = document.documentElement,
      request = elem.requestFullscreen || elem.msRequestFullscreen || elem.mozRequestFullScreen || elem.webkitRequestFullscreen,
      exit = document.exitFullscreen || document.msExitFullscreen || document.mozCancelFullScreen || document.webkitExitFullscreen;
    if (!document.fullscreenElement && !document.msFullscreenElement && !document.mozFullScreenElement && !document.webkitFullscreenElement) {
      request.call(elem);
    } else {
      exit.call(document);
    }
  }

Any better or simple solution?
Thanks.


text:
Q: Trouble connecting iOS App with AWS EC2 server I am testing registration codes for an iOS app to a server hosted on AWS EC2 (tomcat, apache). I keep getting errors, like these:

TIC SSL Trust Error [1:0x283bc6280]: 3:0
NSURLSession/NSURLConnection HTTP load failed
  (kCFStreamErrorDomainSSL, -9813)
Task <2F787366-D258-488D-AD2C-2FE696D08BF2>.<1> HTTP load failed
  (error code: -1202 [3:-9813]).

I searched and changed the info.plist according to several suggestions:
// Here are my sample codes
// Send HTTP Request to Register user
let myUrl = URL(string: "https://ec2xxx.compute.amazonaws.com:8080/MyAPISever/api.json")
var request = URLRequest(url:myUrl!)

request.httpMethod = "POST"// Compose a query string

let postString = "username=\(userName)&password=\(userPassword)&first_name=\(firstName)&last_name=\(lastName)&email=\(userEmail)"

request.httpBody = postString.data(using: String.Encoding.utf8);

let task = URLSession.shared.dataTask(with: request) { (data: Data?, response: URLResponse?, error: Error?) in

 // parse response....

 task.resume()

Still the problem persists. I am using Swift 4.0 and Xcode 10.2. Here is my info.plist additions:
Allow Arbitary Loads

Exception Domains : amazonaws.com

IncludeSubdomains : true

NSExceptionAllowsInsecureHTTPLoads : true

NSExceptionRequiresForwardSecrecy : false

NSExceptionMinimumTLSVersion : TLSv1.2

NSRequiresCertificateTransparency : false


text:
Q: C Programming "Segmentation fault (core dumped)" when using free() I'm trying to create a two dimensional array but when i use free at the end of my program i always get "Segmentation fault (core dumped)" error. The sleep function is only used because i wanted to see if it crashes after creating the array or later, and the program crashes as soon as i use free(array)
#include  <stdio.h>
#include  <stdlib.h>
#include  <unistd.h>

void check(int number)
{
    if(number < 0)
    {
        fprintf(stderr, "You cannot use a value below zero!\n");
    }
}

int create_array(int **array, int size)
{
    array = (int**)malloc(size * sizeof(int*));

    for(int i = 0; i < size; i++)
    {
        array[i] = (int*)malloc(size * sizeof(int));
    }

    printf("Successfully created the array!\n");
    printf("The size of the array is %d * %d = %d", size, size, sizeof(array) / sizeof(int));

    return EXIT_SUCCESS;
}

int main(void)
{
    int N;
    printf("Please enter a value for N: ");
    scanf("%d", & N);
    check(N);

    int R;
    printf("Please enter a value for R: ");
    scanf("%d", & R);
    check(R);

    int **array;
    create_array(array, N);
    sleep(1);
    free(array);

    return EXIT_SUCCESS;
}

A: You are only modifying a local copy of array in create_array() function. In order to be able to modify the pointer array in main(), you need to pass a pointer to it (i.e. the function needs to receive a int***).
More simply, you can return the array from the function and assign it to the array in main() and you wouldn't need to pass the first argument.

A: you are creating dynamic array but you are not returning the reference of that array, thats why you are failing to free it.

A: You need to call create_array() as follows:
int **array;
create_array( &array, N);

Then define it as:
int create_array(int*** array, int size)
{
    *array = (int**)malloc(size * sizeof(int*));

    for(int i = 0; i < size; i++)
    {
        (*array)[i] = (int*)malloc(size * sizeof(int));
    }

    printf("Successfully created the array!\n");
    printf("The size of the array is %d * %d = %d", size, size, sizeof(array) / sizeof(int));

    return EXIT_SUCCESS;
}

You will still have a memory leak however since you are only freeing array and not freeing array[0] to array[N-1].  It would be safer to create a corresponding destroy_array() function.


text:
Q: In Gnuplot, how can I plot the sum of two columns when I'm plotting by header name I have the following data file:
denst densu densd denss
3     1     1     1
4     1     1.5   1.5
5     1     2.5   1.5

I can plot, say, densu(denst) as:
plot 'file.txt' u 'denst':'densu'
Which is very convenient syntax. But if I want to plot, say, the sum of densu and densd, with respect to denst the only way I can do it is:
set key autotitle columnhead to tell gnuplot the first line is headers and not data
plot 'file.txt' u 1:($2+$3) to plot
The question is how can I do operations with column values like that, but using the name notation? The actual file is a csv with ~40 columns, and it's very tedious to manually count which column is which number so I can use the $n syntax to do math with column data.
I would want to do something like plot 'file.txt' u 1:($'densu'+$'densd'), using header name syntax analogously to how I can do it with column number syntax. Is there any way to do this?

A: I've discovered a way to do it. These two commands are equivalent:
plot 'file.txt' u 1:($2+$3)
plot 'file.txt' u 1:(column(2)+column(3))

You can't do
plot 'file.txt' u 'denst':($'densu'+$'densd')

but you can do
plot 'file.txt' u 'denst':(column('densu')+column('densd'))

to the same effect.


text:
Q: grafana dashboard is not working with nginx ingress controller I have deploy kube-prometheus-stack on my eks cluster. Nginx ingress controller is configured with NLB. I am teminating SSL at NLB. I am trying to expose grafana on subdomain with nginx ingress. When i open subdomain nginx ingress is showing 504 error response.
I'm using this helmchart
k8s verison -> 1.22
values.yaml
grafana:
  ingress:
    enabled: true
    ingressClassName: tf-test
    hosts:
       - my-dashboard.example.com
    path: /

A: i had the same issue, it turns out in the grafana value part, there is an extra path like this
      extraPaths:
        - path: "/"
          pathType: Prefix
          backend:
            service:
              name: ssl-redirect
              port:
                name: use-annotation

that ssl-redirect service does not exist. it works me by just removing it.


text:
Q: Deriving Geometric Brownian Motion's solution? The Black Scholes model assumes the following underlying dynamics, known as Geometric Brownian Motion: $$dS_t=S_t(\mu dt+\sigma dW_t)$$
Then the solution is given: $$S_t=S_0\,e^{\left(\mu-\frac{\sigma^2}{2}\right)t+\sigma W_t}$$
It can be shown by Ito Lemma on function $f(t,W_t)=\ln S_t$ that this solution is correct as it leads to above dynamics.
But how do we solve the above SDE originally to find this solution?
Guessing the above solution to apply Ito seems unlikely to me.

A: By applying Ito's Lemma on $f(t,x) = \ln x$ we get
$$d(\ln S_t) = \frac{1}{S_t}dS_t - \frac{1}{2}\frac{1}{S_t^2}dS_tdS_t$$
Substituting the expression for $dS_t$ we obtain
$$d(\ln S_t) = (\mu-\frac{1}{2}\sigma^2)dt + \sigma dW_t$$
This is an expression that you can integrate in a straightforward way if you know $\mu$ and $\sigma$. That leads to the expression for $S_t$ you had in your question.

A: Although very few SDEs have exact solutions, those that do are often found using some ansatz -- as is common for deterministic ODEs.
Without making the a priori choice of $\ln(S_t)$ you would use an ansatz like
$$S_t = X_te^{\sigma W_t},$$
where $X_t$ is a deterministic function.  Apply Ito's lemma to $f(t,w) = A_te^{\sigma w}.$  Then
$$d(X_te^{\sigma W_t}) = \frac{dX_t}{dt}e^{\sigma W_t}dt + \sigma X_te^{\sigma W_t}dW_t+\frac1{2}\sigma^2X_te^{\sigma W_t}dt.$$
Comparing with the SDE for $S_t$, we find
$$\frac1{X_t}\frac{dX_t}{dt}+\frac1{2}\sigma^2= \mu,$$
with solution
$$ X_t = X_0e^{(\mu - \frac1{2}\sigma^2)t}.$$
Then $S_0 = X_0e^{\sigma W_0}=X_0$ and the solution is
$$ S_t = S_0e^{(\mu - \frac1{2}\sigma^2)t}e^{\sigma W_t}.$$


text: Q: Dose NiTE work with Kinect v2 I try to make openni2(32bit) and NiTE2(32bit) work with kinectv2 on win10(64bit),and NiViewer did work after I use kinect2.dll from github,but any sample in NiTE2 does not work,so is there any way to get NiTE2 work with Kinectv2?


text:
Q: Not able to connect to database in ASP IIS I was able to deloy my asp project on IIS and it shows the front page, there I have a login page , after entering the credentials it does not logs in, I used try and catch , and in catch it gave me an error, stating thread has aborted, it was on

page.redirect["master.apsx",true]

so I changed it to

page.redirect["master.aspx",false]

and it didnt gave error, but it was not able to login further, I guess it is not able to connect to database. So any help would be appreciable.
Thanks
CODE:
protected void Page_Load(object sender, EventArgs e)
{

strconn = @"Data Source=.\SQLEXPRESS;AttachDbFilename=" +    Server.MapPath("~/App_Data/Securityservice.mdf") + ";Integrated Security=True;User Instance=True";
    Label1.Text = "  conn string";

}
protected void Button2_Click(object sender, EventArgs e)
{

}
protected void btn_popup_quick_login_Click(object sender, EventArgs e)
{

    try
    {
       if (txt_username.Text != null)
        {
            if (txt_password.Text != null)
            {

                DataTable dt = new DataTable();
                conn = new SqlConnection(strconn);

                conn.Open();

                cmd = new SqlCommand("Select * From UserMaster Where Username=@username and Password=@password", conn);

                cmd.Parameters.AddWithValue("@username", txt_username.Text);

                cmd.Parameters.AddWithValue("@password", txt_password.Text);

                da = new SqlDataAdapter(cmd);

                da.Fill(dt);
                {
                    if (dt.Rows.Count > 0)
                    {
                        userloginname = txt_username.Text;

                        userloginpassword = txt_password.Text;

                        Session["username"] = txt_username.Text;

                        MessageBox.Show("User Login Sucessfully", "Login", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);

                        Response.Redirect("Marketing.aspx",false);

                    }

                    else
                    {
                        Label1.Text = "else part";
                        MessageBox.Show("Invalid User Name and Password", "Login", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
                        txt_username.Focus();

                    }
                    txt_username.Text = "";
                    txt_password.Text = "";
                }
            }
        }
    }
    catch (Exception ex) { MessageBox.Show(ex.Message,"Error",MessageBoxButtons.OK,MessageBoxIcon.Error); }
    conn.Close();
    Label1.Text = "login";
}

A: You should check the connection strings in web.config, to make sure they still point to the proper location of the database after you deployed the site.

A: I think the problem could be the Application_Start method.
Look if you have written some thing there.
Make a break point there and see is there any error.
Or have you written Response.End() in you code?
 You need to provide more detail

*

*You need to check weather you are able to connect to database or not.

*You also need to check weather the page is called or not (which comes after login).


text:
Q: How to convert a CSV file to XML with powershell? Is Convert-To-Xml available in dotnet, or powershell core?
Convert-To-Xml : The term 'Convert-To-Xml' is not recognized as the name of a cmdlet, function, script file, or operable program.
Check the spelling of the name, or if a path was included, verify that the path is correct and try again.
At line:1 char:32
+ Import-Csv "./Processes.csv" | Convert-To-Xml
+                                ~~~~~~~~~~~~~~
+ CategoryInfo          : ObjectNotFound: (Convert-To-Xml:String) [], CommandNotFoundException
+ FullyQualifiedErrorId : CommandNotFoundException

I'm trying the Microsoft example: Import-Csv "./Processes.csv" | Convert-To-Xml


text:
Q: Are you guaranteed to get the rare special item in a case if it appears? So I just got Prime status in CS:GO and wanted to open my first case. I saw on YouTube and other platforms that when a yellow boy slides by in cases (Rare special items), people seem to always get them instead of miss them. So my question is: Are you guaranteed to get the rare special item when it appears on the case?

A: No, there are no guarantees that you'll get something, it's all by chance. As far as I'm aware these drop rates have to made public due to gambling laws in China and other places. That being said there are a couple of stats available online that are shared through Chinese communities as well as some people online testing it for themselves.
Category 1: Weapon boxes that require a key to open

Mil-spec (Blue): 79.923%
Restricted (Purple): 15.985%
Classified (Pink): 3.197%
Covert (Orange): 0.639%
Exceedingly Rare (Yellow): 0.256%

Class 11: Capsules containing premium, exotic quality prints

Normal Drops: 83.333%
Rare Drops: 16.667%

And so on...

What you see on YouTube and other sites are usually edited to make it seem like they're getting constant winning, usually to boost viewership.

A: As a CS:GO player with over 900 hours, I feel equipped to answer this question.
In the past, when a Gold item would appear whilst opening a case, it was possible for it to slide past and cause you to miss out on it.
However, now if a Gold item appears, you are guaranteed it will land on that and award you with a knife/pair of gloves.


text:
Q: How do I wrap using flexbox and media queries? I have a container with four boxes. The container all together should be the width of the window.
Above 720px, there should be one row of four boxes.
Below 720px, there should be two rows of two boxes.
Below 600px, there should be four rows of one box.
I'm confused what I should put in the media queries.

html,
body {
  width: 100%;
  height: 100%;
}

.container {
  border: 1px solid black;
  display: flex;
  height: 100%;
  width: 100%;
}

.column {
  border: 1px solid red;
  flex: 1;
}

@media (max-width: 720px) {
  .container {
    ?
  }
}

@media (max-width: 600px) {
  .container {
    ?
  }
}

A: Set the flex items to wrap at your breakpoints.
Here's a fiddle demo.

.container {
  display: flex;
  flex-wrap: wrap;
  height: 100vh;
}

.column {
  flex: 1;
  border: 1px solid black;
  background-color: lightgray;
}

@media (max-width: 720px) {
  .column {
    flex-basis: 34%;
    background-color: orange;
  }
}

@media (max-width: 600px) {
  .column {
    flex-basis: 51%;
    background-color: lightgreen;
  }
}

body {
  margin: 0;
}

Note that with flex-grow: 1 defined in the flex shorthand, there's no need for flex-basis to be exact (25%, 50%, 100%), which can result in unequal wrapping if you were to add margin space.
Since flex-grow will consume free space on the row, flex-basis only needs to be large enough to enforce a wrap. This will ensure plenty of space for margins, but not enough space for an extra item.

A: You could use grids to achieve this. If you name them like I did in the snippet, it is easy to alter the sequence of the columns.

.container {
      display: grid;
      grid-auto-rows: 200px;
      grid-auto-columns: auto;
      grid-template-areas:
      "column1 column2 column3 column4";
      border: 1px solid black;
      width: 100%;
      height: 100%;
    }

    .column {
      display: flex;
    }

    .column1 {
      grid-area: column1;
      background-color: red;
    }

    .column2 {
      grid-area: column2;
      background-color: yellow;
    }

    .column3 {
      grid-area: column3;
      background-color: green;
    }

    .column4 {
      grid-area: column4;
      background-color: blue;
    }

    @media (max-width: 720px) {
      .container {
        grid-template-areas:
        "column1 column2"
        "column3 column4";
      }
    }

    @media (max-width: 600px) {
      .container {
        grid-template-areas:
        "column1"
        "column2"
        "column3"
        "column4";
      }
    }
<!DOCTYPE html>

      <meta charset="utf-8" />
      <meta http-equiv="X-UA-Compatible" content="IE=edge">
      <title>Page Title</title>
      <meta name="viewport" content="width=device-width, initial-scale=1">
      <link rel="stylesheet" href="main.css">

More info about grids in CSS here


text:
Q: How to remove a yum repo GPG key? I have a custom RPM repo in Artifactory, and GPG signing keys were recently enabled.
When I ran sudo yum check-updates I was prompted to add the key:
Retrieving key from https://artifactory.example.com/myrepo/repodata/repomd.xml.key
Importing GPG key 0x12345678:
 Userid     : "John Doe <jdoe@example.com>"
 Fingerprint: 1234 5678 90ab cdef 1234 5678 90ab cdef 1234 5678
 From       : https://artifactory.example.com/myrepo/repodata/repomd.xml.key

I added the key, which was successful. However, I would now like to remove the key. I need to add the key programmatically (e.g. via Ansible) to numerous servers, and so I would like to reproduce the same behavior as before (where I am prompted to add the key) so that I can confirm that adding the key programmatically changes this behavior.
I have tried using yum-config-manager to unset the gpgkey, but the behavior remains the same (yum does not prompt me to accept the key):
sudo yum-config-manager --setopt=artifactory.gpgkey='' --save

I've additionally deleted the yum cache (sudo yum clean all and sudo rm -rf /var/cache/yum).
How can I remove this key from the yum repo configuration?
Version info:
$ yum --version
3.4.3

A: Using rpm you can list keys and remove them.
[root@apps2 ~]# rpm -q gpg-pubkey --qf '%{NAME}-%{VERSION}-%{RELEASE}\t%{SUMMARY}\n'
gpg-pubkey-f4a80eb5-53a7ff4b    gpg(CentOS-7 Key (CentOS 7 Official Signing Key) <security@centos.org>)
gpg-pubkey-352c64e5-52ae6884    gpg(Fedora EPEL (7) <epel@fedoraproject.org>)
[root@apps2 ~]# rpm -e gpg-pubkey-352c64e5-52ae6884
[root@apps2 ~]# rpm -q gpg-pubkey --qf '%{NAME}-%{VERSION}-%{RELEASE}\t%{SUMMARY}\n'
gpg-pubkey-f4a80eb5-53a7ff4b    gpg(CentOS-7 Key (CentOS 7 Official Signing Key) <security@centos.org>)
[root@apps2 ~]#

A: Yum has a GPG keyring for repos that support GPG metadata signing. On my system, the relevant paths for this particular repo were:

*

*/var/lib/yum/repos/x86_64/7/artifactory/gpgdir

*/var/lib/yum/repos/x86_64/7/artifactory/gpgdir-ro
I was able to delete the GPG keys from those keyrings:
sudo gpg --homedir /var/lib/yum/repos/x86_64/7/artifactory/gpgdir --delete-key 12345678
sudo gpg --homedir /var/lib/yum/repos/x86_64/7/artifactory/gpgdir-ro --delete-key 12345678

Running sudo yum check-update at this point still did not prompt me to accept the key. I ran sudo yum clean metadata, and after that sudo yum check-update did re-prompt me to accept the GPG key.
I found PackageCloud's page on YUM GPG keys helpful in arriving at this solution.


text:
Q: why can I not use my generic in Record type I'm currently trying to use a generic (that's based on an array of string) to create an object which has known keys.
I am getting the following error message:
Type '{}' is not assignable to type 'Record<T[number], string>'.
What I am trying to do is something like:
const a = ["find", "delete", open"];
const n = new NamedItems<typeof a>(a)
// n.named_items will show and intellisense
{
    "find" : 0,
    "delete" : 1,
    "open" : 2
}

with the following code:
class NamedItems<T extends string[]> {
    constructor (private order_of_named_items : T) {
    }

    GET_ITEMS (inNumber : number) {
        return inNumber.toString();
    }

    get named_items () {
        const { GET_ITEMS } = this;
        const i = this.order_of_named_items;
        const obj : Record<T[number], string> = {};
        for (const index in this.order_of_named_items) {
            const name = this.order_of_named_items[index];
            Object.defineProperty(obj, name, {
                get : () => {
                    return GET_ITEMS(+index);
                },
            });
        }
        return obj;
    }
}

A: Well, unless T happens to be an empty array, then the value {} is definitely not going to be assignable to type Record<T[number], string>.  So the compiler is warning you about that.
It looks like your intent is to initialize obj as an empty object, and then gradually populate that object so that when you're done it truly will be of type Record<T[number], string>.  Unfortunately the compiler isn't smart enough to follow how the type of obj would evolve during your loop, so you can't do this initialization in a purely type-safe way.  If you want to pretend that obj is of type Record<T[number], string> even at the beginning when it's just an empty object, you can use a type assertion to tell it so:
const obj = {} as Record<T[number], string>; // okay

This will make the error go away.

Note that your desired usage
const a = ["find", "delete", "open"];
const n = new NamedItems(a);

will not work how you want since the compiler will infer that a is of type string[], and therefore n.named_items will be of type Record<string, string>.  If you want T to be an array of string literal types, you will need to change how the compiler infers the type of a.  The easiest way is with a const assertion:
const a = ["find", "delete", "open"] as const;
// const a: readonly ["find", "delete", "open"]

If you want to pass that into new NamedItems then you should make T allow readonly arrays (which will also allow regular arrays):
class NamedItems<T extends readonly string[]> { /* ... */ }

And now everything will work as you expect:
const n = new NamedItems(a)
console.log(n.named_items.find) // "0"
console.log(n.named_items["delete"]) // "1"
console.log(n.named_items.open)  // "2"

Playground link to code


text:
Q: How to increase size of label fonts in barplot I have the following R code for creating barplot:
# ... here I read cvs file

mx <- rbind(results$"AVG.P10.")
colnames(mx) <- results$"RUN"
rownames(mx) <- "AVG P"
postscript(file="avg_p_result.ps")
barplot(mx, beside=T,  col=c("grey"), names.arg= results$"RUN",
        cex.axis = 1.5, cex.lab=1.5)

I have tried cex.lab=1.5 but it does not work at all.

A: According to ?barplot, you need to use cex.names=1.5.
barplot(mx, beside=TRUE, col=c("grey"), names.arg=results$"RUN",
        cex.axis=1.5, cex.names=1.5)


text:
Q: Why are causal inference diagrams so useful or effective? Is there a short explanation of why Pearl's casual inference diagrams are so highly-regarded, useful or effective?
I can't help but think it's just so simple an idea that I can't tell why it could be such a big deal: It's just like a set of equations where functions are composed in an 'acyclic' way? And apparently it's like groundbreaking and there's a whole field of 'causality'?

A: There are two prongs to this answer. First, why is the New Causal Revolution useful? For reference, see my answer on CrossValidated. The New Causal Revolution is useful because it allows the researcher to gain causal information, given the right model and data, from observational studies with no manipulated variables. Before the New Causal Revolution, the mantra was that you had to do an experiment and manipulate variables to get causal information. There are still Design of Experiments books that baldly (and incorrectly) state that you have to do an experiment to get causal information.
That you can get causal information, now, from an observational study is especially important for fields like medicine, where often the experiment you might like to run is unethical.
Second, Pearl's causal diagrams allow the researcher to gain some information even without any Structural Causal Models (SCMs) (the "set of equations" to which you referred). By putting together the causal graph (which can either be learned to some extent through data, or assembled by subject matter experts), it is possible to determine the answer to questions such as "If we are interested in the causal effect of $X$ on $Y,$ which variables do we need to condition on to get an unbiased result?" There are various graph algorithms that can be run on the causal graph, again without needing to refer to SCMs.
I am actually working on a project right now that uses causal diagrams in a very simple way (not doing any graph surgery or counterfactuals) just for reporting. And that reporting is of very high value, because it allows us to track processes all the way from start to finish.


text:
Q: Checking for the accessibility of Smart Card Private Keys in Windows 10 So Windows change the way it handles Smart Cards in Windows 10. I have an application that remembers the last selected certificate the user logged into the web application with.  If the smart card was inserted, we'd give the user the
X509Certificate2UI.SelectFromCollection

With a collection built from scanning the personal stores for certs with the private key's value of CspKeyContainerInfo.Accessible was true.
While technically, everything still works, whenever Windows 10 attempts to see if the Private key is available, it prompts the user to "Insert the correct smart card."
So whenever a user get a new smart card, or logs in locally, they must go through some ugly prompts and clicking cancel until they get the correct certificate picker.
Currently, my code that checks if the hardware token is available looks like this:
    public static bool IsCertificateAvailable(X509Certificate2 cert)
    {
        try
        {
            AsymmetricAlgorithm akeyInfo = cert.PrivateKey;
            ICspAsymmetricAlgorithm keyInfo = akeyInfo as ICspAsymmetricAlgorithm;
            if (keyInfo.CspKeyContainerInfo.Accessible)
            {
                Logger.Log(LogLevel.Info, "Certificate {0} has a private key", cert.GetSerialNumberString());
                return true;
            }
            else //has no private key
            {
                Logger.Log(LogLevel.Info, "Certificate {0} has no private key", cert.GetSerialNumberString());
                return false;
            }
        }
        catch (CryptographicException)
        {
            return false;
        }
    }

Is there a way to accomplish the same task without the user having to click cancel?


text:
Q: 18.04 LTS: How to take disk space from Windows 10 and use it to install Ubuntu I have Windows 10 Home.There are:-
1- C: 83.86 GB (where windows is installed)
2- D: 16.34 GB (where recovery is stored)
3- F: 244.14 GB (where personal data stored e.g. songs,videos,softwares)
4- G: 244.14 GB (where movies are stored)
5- H: 341.8 GB (where i want to install Ubuntu 18.04 LTS)
So how to dual boot and install Ubuntu 18.04 in H: where i have 341.8 GB ?

A: First, while still in Windows, right click on the [START] button of Windows (the Windows icon at far bottom left) and choose Disk Management. Find your H: drive; you will need to know which physical drive it is on and which partition it is.
Also, confirm by looking in the columns Layout and Type that it is a Basic Disk Type with Simple Layout and not a Dynamic Disk, because Linux can't use a Dynamic Disk.

Once you've done that, while you are still in Disk Management, delete the H: drive partition, and make note of the physical drive it was on from the Volume column.
Download the ISO file for the version of your choice from https://ubuntu.com/download or for a 'flavour' with a different Desktop Environment, download from https://ubuntu.com/download/flavours .
The ISO file you use to create a LiveUSB should be checked for download errors.
Creating the LiveUSB, as per Ubuntu's publishers, is typically done following these instructions on either another Linux PC  or on a Windows PC .
Once you make a LiveUSB, boot with it, after shutting Windows down completely (no Sleep, no Hibernate) by clicking on the Windows START icon at bottom far left, hold down the Shift key, and while holding it down, choose Shutdown. Power up after Shutdown and, using the Boot Order key of your computer (which varies according to make and model), boot from that LiveUSB.
Follow these steps, but when you get to 6. Allocate Drive Space, find the space on your drive(s) previously used for H:, and then choose to install Ubuntu in there.


text:
Q: Remove undefined from a string I'm trying to do, binary search using Javascript, everything is working fine, but I'm unable to console(display) the undefined value(I want to print 'the number is not in the list' if the item is not in the list.)
Thanks in advance.
Here is my code:
function bSearch(userInput, numb){
//var inputSplit = userInput.toString().split('');
var input = numSort(userInput);
//console.log(input);
var start = 0;

var n = input.length;
//console.log(n);
var end = n-1;
var output = '';
//var mid = (start + end) / 2;
// console.log(mid);
while(start <= end){
var mid = (start + end) / 2;
mid = Math.floor(mid);
//console.log(mid);
if(input[mid] == numb){
    output = input[mid];
    return output;
}else if(numb < input[mid]){
    end = mid - 1;
}else if(numb > input[mid]){
    start = mid + 1;
}

}
}
function numSort(num){
var temp = '';
var res = '';
arr = num.toString().split('');
var n = arr.length;
for(i=0; i<n-1; i++){
    for(d=0; d<n-i-1; d++){
        if(arr[d] > arr[d+1]){
            temp = arr[d];
            arr[d] = arr[d+1];
            arr[d+1] = temp;
        }
}

}
for(i=0; i<n; i++){
    res += arr[i];
}return res;

}

A: Add the return statement at the end of the function
function bSearch(userInput, numb) {
    // lots of code (some vars without declarations ...)
    // ...
    return 'the number is not in the list';
}

This is preventing undefined. Instead it is returning the string.


text:
Q: How to resolve maven dependency chaos to do versioning right? I come into the situation that I'm responsible for a legacy Java maven project, and I'm facing some problems with the versioning and the dependencies.
The Project consists of some sub applications, which consists of some modules + all applications (or their modules) also depend on something like a commons module (or better depend on some sub modules of that commons module)
Now I'm facing problems:
1) Seeing the dependencies and changing the version of a module would lead me to a big mess as I don't know where the module is used so I wound have to search for its usings and update manually the version.
Is there a better or other approach that can be used for this dependencies/version mash - maybe tool support (currently using IntelliJ Idea)
2) I'm struggling with an clear approach of versioning for the modules/applications in different Branches.
It is clear for normal release/maintaining breaches - like semantic  versioning, eg minor version is increased and  is stable for that branch, no other branch is using same minor version - that would be the best.
But what if I have to have a branch for same minor version, for another customer - and it has to be in different brunch (it seems in the past and also to the management common product development is a unknown - do other features that should not make it in the other branch (not even disabled, not allowed to be in the code by regulation)).
How to distinguish between the branches? Should I use one of the for version digits for the branch or should I attach to the last digit some characters (eg.: An abbreviation of the project)?
A) 1.5.3.2 (
B) 1.0.3.2-US vs 1.0.3.2-EU
(And yes I know that product with feature toggle it something similar would be the best solution but that's not an option (due to management and regulation obligations))
Question is also if there tooling supports the chosen way.

A: for 1): Yes, it is. You can use parent pom and set version as variable in parent pom. When updating a module version, just update parent pom is enough.
for 2): You can use git branches to set different versions for customers. If you use git branches, you need to update all branches when there's new commit. It's also convenient to use different fixes for different customers.
Or you can also solve it by maven through maven profiles. With different package command like
mvn package -PEU


text:
Q: Using Elasticsearch bucket_script in Grafana I have an Elasticsearch query to track %age of 50x hits from Elasticsearch Logstash indexes.
I would like to implement this in Grafana, but I can't find any good docs or examples of how to configure this query via the UI. The UI apparently does support bucket_script, but it's not clear how to implement.
The ES query is:
{
    "aggs" : {
        "all_hits" : {
            "date_histogram" : {
                "field" : "@timestamp",
                "interval": "day"
            },
            "aggs": {
                "total_hits": {
                    "value_count": {
                        "field": "http_status_code"
                    }
                },
                "50x": {
                  "filter": {
                    "terms": {
                      "http_status_code": [500,501,502,503,504]
                    }
                  },
                  "aggs": {
                    "hits": {
                      "value_count": {
                        "field": "http_status_code"
                      }
                    }
                  }
                },
                "error_rate": {
                    "bucket_script": {
                        "buckets_path": {
                          "total_hits": "total_hits",
                          "error_hits": "50x>hits"
                        },
                        "script": "params.error_hits / params.total_hits * 100"
                    }
                }
            }
        }
    }
}


text:
Q: Passing list of objects to create with arguments to constructor or method Basically what I'm trying to do is to make a class that can mass-create objects using
Activator.CreateInstance(Type type, params object[] args)

I will need to pass all the object blueprints to a constructor of a class called ObjectMap. It will need to be pairs of a type and the arguments. It can also be a method in another class instead of a constructor if that allows for a solution.
sort of like
new ObjectMap([Type, somevalue, somevalue, somevalue], [Type, somevalue], [Type] ...)

or
Resources.AddObjectMap([Type, somevalue, somevalue, somevalue], [Type, somevalue], [Type] ...)

I have no idea how to make it so that you can pass a variable amount of pairs with a variable amount of arguments (even 0). Heck I'm even having a hard time trying to explain the issue. Ask me anything that's unclear to you =S
Gr.Viller

A: I would suggest you encapsulate the "type and args" into a specific type... then you can use a params array of that. For example:
// TODO: Find a better name :)
public class TypeBlueprint
{
    public Type Type { get; set; }
    public List<object> Arguments { get; set; }

    public TypeBlueprint()
    {
        this.Arguments = new List<object>();
    }

    public TypeBlueprint(Type type, params object[] arguments)
    {
        this.Type = type;
        this.Arguments = arguments.ToList();
    }
}

Then:
public ObjectMap(params TypeBlueprint[] blueprints)

And call it with:
var map = new ObjectMap(new TypeBlueprint(typeof(Foo), "x", "y", "z"),
                        new TypeBlueprint { Type = typeof(Bar),
                                            Arguments = { 1, 2, 3 } });

That demonstrates using both constructor parameters and object initializers to specify the type and arguments. Use whichever is best for you.

A: I think this is what you are asking for... (I think the real answer yo our question is the use of params in the function parameter list)
Implementation:
public class ObjectMap
{
    public object[] ActivatedObjects { get; private set; }

    public ObjectMap(params object[][] itemsToMap)
    {
        ActivatedObjects = itemsToMap.Select(ActivateItem).ToArray();
    }

    private object ActivateItem(object[] itemToActivate)
    {
        return Activator.CreateInstance((Type)itemToActivate[0], itemToActivate.Skip(1).ToArray());
    }
}

Basic unit test:
[TestClass]
public class UnitTest3
{
    [TestMethod]
    public void TestMethod1()
    {
        var map = new ObjectMap(new object[] {typeof(Class1)},
                  new object[] {typeof(Class2), "Arg One", 2});

        Assert.AreEqual(2, map.ActivatedObjects.Length);
        Assert.IsInstanceOfType(map.ActivatedObjects[0], typeof(Class1));
        Assert.IsInstanceOfType(map.ActivatedObjects[1], typeof(Class2));
    }
}

public class Class1
{
    public Class1()
    {
    }
}

public class Class2
{
    public Class2(string arg1, int arg2)
    {
    }
}


text:
Q: Approximating an unknown value in Python I need to approximate an unknown value, a bound that separates divergent values from those that converge.
I'm trying to do so like this:
# dont worry about the value of i, its one of many bounds checks
bounds = 1.0
for j in range(niters):
    if does_converge(i, bound):
        bound += bound / 2.0
    else:
        bound /= 2.0

I've been googling for better approximation algorithms, but they all seem to assume I know something about the function, but I don't. All I get is a black box that tells me whether or not a value diverges or not.
Any ideas would be appreciated!
edit: I can't say for certain, but I would be fine assuming the function is continuous, and the boundary of convergence is most likely between 0 and 1.

A: With the given information, there is nothing better available than some form of binary-search.
Edit: See edit/remark at the end of this answer for a better solution (although without a rigorous theoretic explanation)!
This can be implemented using scipy's minimize_scalar. It is important to use method: golden!

Method Golden uses the golden section search technique. It uses analog of the bisection method to decrease the bracketed interval.

The problem is the absence of any real-valued answer. Only yes/no does not allow to form any kind of gradient-information or surrogate-model.
I'm assuming:

*

*we are looking for the smallest value at which the black-box returns 1

*the black-box is deterministic

Idea: build some wrapper-function, which has a minimum at the smallest value for which 1 is returned.
As x should be in [0,1], trying to minimize x, we can formulate the wrapper-function as: x + 1 - black_box(x). Every solution with answer 0 is >= every solution with answer = 1 (probably some safeguard needed at the bound; e.g. x + (1 - eps) - black_box(x) with eps very small!; might need to be chosen with xtol in mind).
Code:
from scipy import optimize

SECRET_VAL = 0.7

def black_box(x):
    if x > SECRET_VAL:
        return 1.
    else:
        return 0.

def wrapper(x):
    return x + 1 - black_box(x)

res = optimize.minimize_scalar(wrapper, bracket=(0,1), method='golden')

print(res)

Output:
     fun: 0.7000000042155881
    nfev: 44
     nit: 39
 success: True
       x: 0.7000000042155881

Or with secret_val=0.04:
     fun: 0.04000000033008555
    nfev: 50
     nit: 45
 success: True
       x: 0.040000000330085564

Or if you know what kind of accuracy you need (original secret 0.7):
res = optimize.minimize_scalar(wrapper, bracket=(0,1), method='golden',
                            options={'xtol': 1e-2})

Output:
     fun: 0.7000733152965655
    nfev: 16                 !!!!!
     nit: 11
 success: True
       x: 0.7000733152965655

Remark:
It might be better to write a customized binary-search based solution here (not 100% sure). But one needs to be careful then given the assumptions like missing unimodality.
Edit:
Okay... i finally managed to transform this minimization-problem to a root-finding problem, which can be solved more efficiently!
Warning:
It's clear, that wrapper is never returning the value of 0.0 (no exact root to find)!
But the bisection-method is about a zero crossing within the new interval wiki.
So here it finds two points a, b, where the signs of the function are changing and is interpreting this as a root (given some tolerance!).
This analysis is not as rigorous as the one compared to the former method (not much analysis given, but easier to do in the pure minimization-approach given scipy's documentation).
def wrapper_bisect(x):
    return 1 - 2*black_box(x)

res = optimize.bisect(wrapper_bisect, 0, 1, xtol=1e-2, full_output=True)
print(res)

Output:
(0.6953125,       converged: True
           flag: 'converged'
 function_calls: 9
     iterations: 7
           root: 0.6953125)

Given the assumptions above (and only these), this should be the theoretically optimal algorithm (we reduced the number of function-evaluations from 16 to 9; the optimization-objective is worse, but within the bounds)!
One last test:
secret: 0.9813; xtol: 1e-4:
Golden:
    fun: 0.9813254238281632
    nfev: 25
     nit: 20
 success: True
       x: 0.9813254238291631

Bisection:
(0.98126220703125,       converged: True
           flag: 'converged'
 function_calls: 16
     iterations: 14
           root: 0.98126220703125)


text:
Q: How do I find running Traces in SQL Server? Is there an easy way to determine what traces have been set up by sp_trace_create on SQL Server 2000? How about for SQL Server 2005, 2008, 2012, or 2014?

A: SQL Server 2005 (onwards):
    SELECT * FROM sys.traces

SQL Server 2000 :
    USE msdb
    SELECT * FROM fn_trace_getinfo(default);

Ref: fn_trace_getinfo
Column descriptions for sys.traces DMV can be found here: sys.traces

A: Old question, but a precisation. On a SQL 2000 server you must use msdb database. Es:
USE msdb
SELECT * FROM :: fn_trace_getinfo(default)


text:
Q: Why has SELECT different height if only one empty option exists? In this sample http://jsfiddle.net/2SuN8/1/
<select>
    <option value="0"></option>
</select>
<select>
    <option value="0"></option>
    <option value="1">A</option>
</select>

there is a 1px height difference between those two drop-downs.
I assume this happens when one select contains only one empty option.
Should I avoid empty default options or do You know any way to work around this?
I've seen this issue in FF 27.0.1 (Ubuntu 13.10 and Windows Server 2008) and with IE 10 (Windows Server 2008).
Thanks
Hannes

A: This is happening because you aren't specifying a height for the select element, so by default its height is determined by its content. In the case of your select element with only one empty option, as there is no content, there is no height.
CSS Solution
The CSS solution would be to simply add a default height  to your select element:
select {
    height: 20px;
}

JSFiddle demo.
HTML Solution
The HTML solution, as mentioned by others here, is to populate your empty option with some content:
<select>
    <option value="0"> </option>
</select>

JSFiddle demo.
In this case,   is the non-breaking space entity.
Personally I'd go with the CSS option.

A: now there is no different height :D
change
<option value="0"></option>
to
<option value="0"> </option>
http://jsfiddle.net/2SuN8/2/

A: Yes, you should avoid empty select options. Instead you can set empty value for first option.:
<select>

    <option value=""> - - select - -</option>
    <option value="a"> A </option>
     <option value="b"> B </option>

</select>

A: Set the width and/or the height and they will be the same size.
<select style="width:100px; height:20px;">
    <option value="0"></option>
</select>

<select style="width:100px; height:20px;">
    <option value="0"></option>
    <option value="1">A</option>
    <option value="2">B</option>
</select>

Edit:  My version is the quick and dirty version, if you want the right way to do it, use a separate CSS file or a space substitute as others have described.

A: The reason that it happens is that in some browsers (for example Firexox) the select element for some reason will grow to accomodate its largest option value, eventhough the value may not be shown in the select in the same way as in the option.
For example:
<select>
    <option value="0"></option>
</select>

<select>
    <option value="0"></option>
    <option value="1">A</option>
    <option value="2" style="font-size:20px">B</option>
</select>

Demo: http://jsfiddle.net/Guffa/2SuN8/3/
In firefox the select element will be tall enough to accomodate a 20px text, but if you choose the option B it will not be shown with the font size specified for the option, but with the font size specified for the select.
One workaround would be to set a specific height to the select. A workaround for the specific case of the empty option could be to use a space inside it, like Sharky showed.


text:
Q: Hide Header Section After Last Record I have a crystal report, whenever I reach the last record, it will print another extra page together with the header.
see the attachment below:
this is extra page, always appear together with the header section after last record
I applied formula to the Detail Section and Header Section at the supress.
Detail Section:
WhilePrintingRecords;
Global BooleanVar finished;
finished :=  OnLastRecord
Header Section:
Global BooleanVar finished

It seems working for the layout, but when the extra page is not printed,
1) my last record is not appear (let say i have 51 records,
only 50 records is printed)
First Problem after applying formula
2) If I have only one record, the next page still appear
Is there any correction can be apply on my formula, or im applying a wrong formula for it?


text:
Q: How can one app provide data to another without swiching apps? Scenario:

*

*I "control" two different apps, App A and App B, both which the user has installed

*App A is running

*App A needs to obtain a string that was set by App B when App B last ran.

*After obtaining the string, App A will still be running

*User should not receive any feedback this communication is happening.  E.g. no  "switching animations" between A or B, no pop-ups, etc.

Constraints:

*

*Apps are released under different vendors

*Apps are already in the app store; updated versions will have this communication ability.

*It is acceptable for the data stored in App B to be accessible to other apps on the device.

*It is not acceptable for the data stored in App B to be visible to general third parties (e.g. if an external server is used, there needs to be some sort of secured scheme)

*The data read should be able to occur immediately upon App A being opened after install. For instance, I cannot require the user of App A to enter log in credentials for an external communication service.

*Must work on non-jailbroken devices.

This is seeming rather difficult to pull off in iOS7. Help is appreciated.

A: Tricky work around. Not recommended, but it will get the job done if you can't afford servers.
On the first app create a contact in the user's contacts book. Give it a generic name like "000 - NameOfAppB Data - Don't Delete" (I start with "000" so it goes to the bottom of the users contact book so they never see it, I also add "don't delete" so if the user does somehow find it they don't delete it hahaha) (who looks at contact books anyways). In the contact info under notes add your NSData in string format.
Then when app A is opened search for that contact, read the data, then delete the contact.
Apple does allow you to create and delete users contacts without their permission. (At least in 2011 they did, this may have changed).

A: This might serve your purpose
https://developer.apple.com/library/ios/documentation/Security/Reference/keychainservices/Reference/reference.html
I am not sure of its limitations though, i have seen implementations where credentials have been shared between apps.


text:
Q: Inexplicable query times for small PostgreSql database I have a simple table that we use to record debug logs.
There are only 1000 rows in the table.
There are a handful of columns - id (primary), date (indexed), level, a few other small fields and message which could be a large string.
if I query:
select id from public.log

the query completes very quickly (less than 1 second)

if I query:
select id,date from public.log

or
select * from public.log

it takes 1 minute and 28 seconds to complete!
90 Seconds to read 1000 records from a database!

however if I query:
select *
from public.log
where id in (select id from public.log)

it completes in about 1 second.

And here is the CREATE - I just had pgAdmin generate them for me
-- Table: public.inettklog

-- DROP TABLE public.inettklog;

CREATE TABLE public.inettklog
(
    id integer NOT NULL DEFAULT nextval('inettklog_id_seq'::regclass),
    date timestamp without time zone NOT NULL,
    thread character varying(255) COLLATE pg_catalog."default" NOT NULL,
    level character varying(20) COLLATE pg_catalog."default" NOT NULL,
    logger character varying(255) COLLATE pg_catalog."default" NOT NULL,
    customlevel integer,
    source character varying(64) COLLATE pg_catalog."default",
    logentry json,
    CONSTRAINT inettklog_pkey PRIMARY KEY (id)
)
WITH (
    OIDS = FALSE
)
TABLESPACE pg_default;

ALTER TABLE public.inettklog
    OWNER to postgres;

-- Index: inettklog_ix_logdate

-- DROP INDEX public.inettklog_ix_logdate;

CREATE INDEX inettklog_ix_logdate
    ON public.inettklog USING btree
    (date)
    TABLESPACE pg_default;

A: Your table is extremely bloated.  Given your other question, this extreme bloat is not surprising.
You can fix this with a VACUUM FULL.
Going forward, you should avoid getting into this situation in the first place, by deleting records as they become obsolete rather than waiting until 99.998% of them are obsolete before acting.


text:
Q: How to implement transaction in knex? How to implement transaction in knex if functions are used? util.insert calls knex on table2 and similarly util.mark.
 knex('tab1').where({ col1: 'val1' }).update({ col2: 'val2'}).returning('col3').then(function(result1) {
                    if (result1 != 0) {
                        var data2 = {
                            "key": "value"
                        };
                      util.insert(data1, function(err1, data2) {
                            if (err1) {
                                cb(err1);
                                return;
                            }
                            util.mark(data2, function(err2, data3) {
                                if (err2) {
                                    cb(err2);
                                    return;
                                }
                                cb(null, true);
                                return;
                            });
                        });
                    } else {
                        cb(null, false);
                    }
                })

A: knex.transaction((trx) => {
  return knex('tab1')
  .update({ col2: 'val2' })
  .where({ col1: 'val1' })
  .transacting(trx)
  .then((result) => {
    let promise;
    if (result1 != 0) {
      promise = util.insert(data1);
    } else {
      promise = util.mark(data2);
    }
    return promise
    .transacting(trx);
  })
  .then(trx.commit)
  .catch(trx.rollback)
})
.then(() => {
  // blabla
})
.catch((err) => {
  // handle your error together
});

and if util.insert or util.mark take io operation, they better accept the trx as arguments.


text:
Q: Socle of submodule relative to the module
in these notes i am reading i am told that the socle of $K$ (where $K \subset M$ , and $M$ is a module) is = $K \cap$ Soc $ M$
But why is this? i see the intuition but cannot formalize a proof
any help would be great
thanks

A: There are two ways to see this.
First, one characterization of the socle of a module $N$ is that it is the sum of the simple submodules of $N$.  The simple submodules of $K$ are exactly the simple submodules of $M$ that lie in $K$.
Second, using the theorem you stated in the comments let $f\colon K \to M$ be the inclusion map.  Then that theorem gives $\mathrm{soc} \ K \subseteq \mathrm{soc} \ M$ and clearly it's in $K$ so $\mathrm{soc} \ K \subseteq K \cap \mathrm{soc} \ M$.  But $K \cap \mathrm{soc} \ M$ is semisimple and a submodule of $K$ so $K \cap \mathrm{soc} \ M \subseteq \mathrm{soc} \ K$.  Hence they are equal.


text:
Q: flutter bloc - dispatch event to hosting widget without changing the state I got this situation:

*

*screen1 (widget) navigates to screen2 (widget) and passes it a function (callback)

*screen2 has its own bloc (bloc2)

*screen2 add event to bloc2

*bloc2 performs a long async operation

*when operation completes, bloc2 should notify screen2 (The problem is here)

*screen2 should invoke the passed function

*screen1 in a réponse should close screen2

How should bloc2 notify screen2 without changing a state.
Changing the state seems a redundant operation in this case, as I don't see a point in build function to run again (and returning a redundant widget)

A: Assuming you are using a BlocBuilder to build screen2, then you could use the buildWhen property to determine on which conditions to rebuild, maybe never on state-change?
You can get the blocs public properties and methods using the previous and current parameters. Those parameters are of type BlocAState.
BlocBuilder<BlocA, BlocAState>(
  buildWhen: (previous, current) {
    // return true/false to determine whether or not
    // to rebuild the widget with state
  },
  builder: (context, state) {
    // return widget here based on BlocA's state
  }
)

Furthermore, this step:

screen2 should invoke the passed function

Should, probably, be done in a BlocListener or BlocConsumer. Maybe that is already how you do it, if not. Look into it..
So to solve your problem I would imagine that you should switch your BlocBuilder to a BlocConsumer, actually change the state, because your "long async operation" does change the state of screen2 from "not done the long thing", to "has done the long thing". Then your BlocListener can invoke the passed function, and the buildWhen property can make sure to not rebuild your screen2.
The BlocConsumer looks like this:
BlocConsumer<BlocA, BlocAState>(
  listenWhen: (previous, current) {
    // return true/false to determine whether or not
    // to invoke listener with state
  },
  listener: (context, state) {
    // do stuff here based on BlocA's state

    // I.e. invoke the passed function
  },
  buildWhen: (previous, current) {
    // return true/false to determine whether or not
    // to rebuild the widget with state
  },
  builder: (context, state) {
    // return widget here based on BlocA's state
  }
)


text:
Q: Android activity border that can not be removed? So I have this
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/mainParent"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@drawable/bgdark"
    android:orientation="vertical"
>
    <ImageView
        android:id="@+id/imageView1"
        android:layout_width="match_parent"
        android:layout_height="76dp"
        android:src="@drawable/myheader_250x60"
    />
    <ListView
        android:id="@+id/mainListview"
        android:layout_width="match_parent"
        android:layout_height="match_parent" >
    </ListView>
</LinearLayout>

Note I have now edited this post. I was using a grey background image, so I thought that was what was visible to right/left of header image.See below for an image showing the problem.
However, moving the background to the listview did not solve the problem. Hence it would seem it is the imageview that somehow has a left/right border in grey. As i have set width to "match_parent" it should have taken he maximum width.

The problem is that to the top/right of header there's a grey pixel border? which I would like to remove if possible.

A: Try scaleType attribute for your ImageView.
Anothrer way - replace
android:src="@drawable/myheader_250x60"

for
android:background="@drawable/myheader_250x60"

A: Try using fill_parent instead of match_parent except in listView height . Use wrap_content in listView height

A: set this scletype property
android:scaleType=fitXY

and set image to imageview like this
android:background="@drawable/myheader_250x60"


text:
Q: CSS of the child element not working but parent's css is working fine I am creating a small quiz app. And After answering question in quiz I am showing the progress bar.
But I have styled the progress bar using two div elements, One div parent element and another is child. But when I am applying css on parent div(id = "progressBar") it is working well but child div's (id= "progressBarFull")css is not working.
Please tell me why?

.choice-container{
    display: flex;
    margin-bottom: 0.5rem;
    width: 90%;
    font-size: 1.8rem;
    border: 0.1rem solid rgb(86, 165, 235,0.25);
    background-color: white;

}

.choice-prefix{
    background-color: #56a5eb;
    padding: 1.5rem 2.5rem;
    color: white;

}

.choice-text{
    padding: 1.5rem;
    width: 100%;
}

.choice-container:hover{
    cursor:pointer;
    box-shadow: 0.4rem 0.6rem rgba(86, 185, 235, 0.5);
    transform: translate(-0.1rem);
    transition: transform 150ms;
}

.correct{
    background-color: #28a745;
}

.incorrect{
    background-color: #dc3545;
}
/* HUD DISPLAY */

#hud{
    display: flex;
    justify-content: space-between;
}

.hud-prefix{
    text-align: center;
    font-size: 2rem;
}

.hud-main-text{
    text-align: center;
}

#progressBar{
    width : 20rem;
    height: 3.1rem;
    border: 0.3rem solid #56a5eb;
};

#progressBarFull{
    height: 2.5rem;
    background-color: #56a5eb;

};
<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Quick Quiz - Play</title>
    <link rel="stylesheet"  href="app.css" />
    <link rel="stylesheet"  href="game.css" />

                        Score

What is the answer to this question?

A

Choice 1

B

Choice 2

C

Choice 3

D

Choice 4

Click here for the output

A: you need to take the semicolons out after the closing braces:
#progressBar{
    width : 20rem;
    height: 3.1rem;
    border: 0.3rem solid #56a5eb;
} /* no semicolon here */

#progressBarFull{
    height: 2.5rem;
    background-color: #56a5eb;

} /* no semicolon here */

For reference check out MDN article on css syntax. Basically, an unnecessary semicolon after the the terminating curly brace will hamper user agent's parsing of css and the css code following that won't be parsed.

A: You have a badly placed semicolon after progress Bar. And I would recommend setting height as a percentage.

.choice-container{
    display: flex;
    margin-bottom: 0.5rem;
    width: 90%;
    font-size: 1.8rem;
    border: 0.1rem solid rgb(86, 165, 235,0.25);
    background-color: white;

}

.choice-prefix{
    background-color: #56a5eb;
    padding: 1.5rem 2.5rem;
    color: white;

}

.choice-text{
    padding: 1.5rem;
    width: 100%;
}

.choice-container:hover{
    cursor:pointer;
    box-shadow: 0.4rem 0.6rem rgba(86, 185, 235, 0.5);
    transform: translate(-0.1rem);
    transition: transform 150ms;
}

.correct{
    background-color: #28a745;
}

.incorrect{
    background-color: #dc3545;
}
/* HUD DISPLAY */

#hud{
    display: flex;
    justify-content: space-between;
}

.hud-prefix{
    text-align: center;
    font-size: 2rem;
}

.hud-main-text{
    text-align: center;
}

#progressBar{
    width : 20rem;
    height: 3.1rem;
    border: 0.3rem solid #56a5eb;
}

#progressBarFull{
    height: 100%;
    background-color: #56a5eb;

};
<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Quick Quiz - Play</title>
    <link rel="stylesheet"  href="app.css" />
    <link rel="stylesheet"  href="game.css" />

                        Score

What is the answer to this question?

A

Choice 1

B

Choice 2

C

Choice 3

D

Choice 4


text:
Q: Android растягивающийся widget в центре экрана вопрос в том как сделать виджет на экране который будет сам подстраиваться под размеры экрана. Например вверху есть элемент с заданой высотой, снизу тоже. По центру должен быть элемент который займет все оставшееся место.
Вот мой код, не могу понять как растянуть правильно этот грид <GridView android:id="@+id/TransitionTable">
 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/LinearLayout1"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".MainActivity"
    android:background="@color/black"
    >
<GridView
    android:id="@+id/gridview"
    android:layout_width="fill_parent"
    android:layout_height="60dp"
    android:columnWidth="50dp"
    android:gravity="center"
    android:background="@color/white"
    android:horizontalSpacing="0dp"
    android:numColumns="7"
    android:stretchMode="columnWidth"
    android:verticalSpacing="0dp"
    android:layout_margin="5dp">

</GridView>

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="70dp"
    android:layout_gravity="center"
    android:gravity="center" >

    <Button
        android:id="@+id/button_prev"
        android:background="@drawable/greenbutton"
        style="@style/ButtonText"
        android:text="@string/ButtonBack" />

    <Button
        android:id="@+id/button_next"
        android:background="@drawable/greenbutton"
        style="@style/ButtonText"
        android:text="@string/ButtonForward" />

</LinearLayout>

    <GridView
        android:id="@+id/TransitionTable"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_margin="5dp"
        android:numColumns="7"
        android:padding="0dp" >

</GridView>

<LinearLayout
    android:layout_width="fill_parent"
    android:layout_height="60dp"
    android:layout_gravity="center"
    android:gravity="center" >

    <Button
        android:id="@+id/buttonStartPause"
        android:background="@drawable/greenbutton"
        style="@style/ButtonText"
        android:text="@string/ButtonStart" />

    <Button
        android:id="@+id/buttonStop"
        android:background="@drawable/greenbutton"
        style="@style/ButtonText"
        android:text="@string/ButtonStop" />

</LinearLayout>

</LinearLayout>
A: *

*Откажитесь от вложенных LinearLayout. Забудьте про эту идею навсегда!

*Используйте RelativeLayout для вложенных элементов(в ДАННОМ случае), которые будут зависеть от верхнего и нижнего(layout_above, layout_below-атрибуты) или в качестве корневого в любом другом макете.

*GridView задайте со следующими параметрами в ширину - match_parent, в высоту - wrap_content или match_parent, экспериментируйте.

*Подумайте как можно упростить верстку и идею.


text:
Q: text input further use All I want to do is get the variable newtext back to just below main section so that I can continue to use it, but whatever I try I can't. I'm very new to c# and unity, I'm trying to do a old school adventure like the ones in the 80's I've written a script under this to break the input newtext into verb and noun (which works), just can't get the string newtext back to allow me to do this, any help with this would be greatly appreciated.
using UnityEngine;
using System.Collections;
using UnityEngine.UI;

public class Textinput : MonoBehaviour {
    // declare variables below

    InputField input;
    InputField.SubmitEvent se;
    public Text output;

    // declare variables above
    void Start () {

        input = gameObject.GetComponent<InputField>();
        se = new InputField.SubmitEvent();
        se .AddListener(SubmitInput);
        input.onEndEdit = se;

        //want varable script to come back here to use ie "newtext" to use after this point

                 // **split word script here **

    }

    // my voids below
    private void SubmitInput(string arg0)

    {
        string currentText = output.text;
        string newText =  arg0;
        output.text = newText;
        input.text = "";
        input.ActivateInputField();
    }

}

A: If you want to call a function with the text of the inputField when the user submits the input you can use onEndEdit
void Start () {
  input = gameObject.GetComponent<InputField>();
  input.onEndEdit.AddListener(SubmitInput);
}

private void SubmitInput(string arg0)
{
  string currentText = output.text;
  string newText =  arg0;
  output.text = newText;
  input.text = "";
  input.ActivateInputField();
}


text:
Q: Dynamically incresing the size of 2d array row elements I have a 2d array of integers. Initially, the rows are empty as I am trying to not allocate any additional memory to them if it's not required.
int** resultIndexArr = malloc(sizeof(int*) * n + 8);
int arrayItemsLastIndex[] = {0,0};
int lastAnswer = 0;

for (int i = 0; i < queries_rows; i++) {
    int type = *(*(queries + i));
    int x = *(*(queries + i) + 1);
    int y = *(*(queries + i) + 2);

    if(type == 1 ) {
        int idx = ((x ^ lastAnswer) % n);
        resultIndexArr[idx] = realloc(resultIndexArr[idx], sizeof(int) * (arrayItemsLastIndex[idx] + 1));
        resultIndexArr[idx][arrayItemsLastIndex[idx]] = y;
        printf("%d \n", idx); //output: 0
        print("%d \n", arrayItemsLastIndex[idx]); //output: 0
        printf("%d \n", resultIndexArr[idx][arrayItemsLastIndex[idx]]); //output: y
        arrayItemsLastIndex[idx]++;

    }
    printf("%d \n", resultIndexArr[0][0]); // garbage value }

Note: I am new to c
I am trying to allocate new memory while keeping the values of the row using realloc.
You can say it's like pushing to an array in simple words.
What I am trying to do is just increase the size of a row in a 2d array without losing its values.


text:
Q: syncing a file to the web, and accessing through a "custom" url Are there any websites out there that allows file syncing to a folder and the files in the folder can be accessed through the folder via http?
  i.e.  My folder to be synced could be called "share." And a file can be "file.txt".
   I want to access it through...http://whicheverDomain.com/IDontCareWhatThisIs/share/file.txt
Also I want the file itself to be able to be accessed directly, so that I can send it to google doc viewer. i.e (http://docs.google.com/viewer?url=http%3A%2F%2FwhicheverDomain.com%2FIDontCareWhatThisIs%2Fshare%2Ffile.txt).  If that doesn't work, then if the website displays it in a decent manner, that would be fine.
I've been looking for a while. Box seems to be able to do that, but it requires a business account.

A: I have found the solution. Dropbox doesn't have a "custom url." However, it does have what I was looking for.  Adding their old Public folder does the trick.  You can get it here towards the bottom of the page. https://www.dropbox.com/help/16/en


text:
Q: How to fetch this JSON values in Java? I am confused how to fetch this JSON values, I have tried but I am not sure about it :
This is my JSON url :
http://api.openweathermap.org/data/2.5/weatherq=London,uk&appid=d7b900681c37193223281142bd919019

This is how i am just trying to fetch json values.
JSONObject ishu=new JSONObject(String url);//URL OF MY JSON!!
JSONObject COORD=ishu.getJSONObject("coord");
String LON=1.getString("lon");
String LAT=1.getString("lat");

JSONObject ishu1=ishu.getJSONObject("weather");
JSONArray jsonarray=new JSONArray(jsonStr);

for(int i=0;i<jsonarray.length();i++)
{
  JSONObject jsonobject=jsonarray.getJSONObject(i);
  String id=jsonobject.getString("id");
  String main=jsonobject.getString("main");
  Stirng description=jsonobject.getString("description");
  String icon=jsonobject.getString("icon");
}

JSONObject ishu2=ishu.getJSONObject("base");
String MAIN=ishu.getString("main");
String TEMP=MAIN.getString("temp");
String PRESSURE=MAIN.getString("pressure");
String HUMIDITY=MAIN.getString("humidity");
String TEMP_MIN=MAIN.getString("temp_min");
String TEMP_MAX=MAIN.getString("temp_max");

JSONObject WIND=ishu.getJSONObject("wind");
String SPEED=WIND.getString("speed");
String DEG=WIND.getString("deg");
String GUST=ishu.getString("gust");

JSONObject ishu4=ishu.getJSONObject("rain");
JSONObject 1H=ishu4.getJSONObject("1h");

JSONObject ishu5=ishu.getJSONObject("clouds");
String ALL =ishu5.getString("all");

JSONObject ishu6=ishu.getJSONObject("dt");
String SYS=ishu.getString("sys");
String TYPE=SYS.getString("type");
String ID=SYS.getString("id");
String MESSAGE=SYS.getString("message");
String COUNTRY=SYS.getString("country");
String SUNRISE=SYS.getString("sunrise");
String SUNSET=SYS.getString("sunset");

JSONObject ishu7=ishu.getJSONObject("id");
JSONObject ishu8=ishu.getJSONObject("name");
JSONObject ishu9=ishu.getJSONObject("cod");

A: Download your JSon file using RestFul service (Default HttpUrlConnection / Volly Library) and give the downloaded String to above you code.
Its better use any parsing tool then doing it manually.
http://blog.takipi.com/the-ultimate-json-library-json-simple-vs-gson-vs-jackson-vs-json/
GSon is simple to use and it is from Google.
As simple as below
ModelClass object = new Gson().fromJson(JsonString, ModelClass.class);

A: It seems that you firstly need to get the response from the api.openweathermap.com.
 URL url= new URL("<your url here>");
 HttpURLConnection connnection = (HttpURLConnection) url.openConnection();
 connnection.setRequestMethod("GET");
 InputStream is = connnection.getInputStream();

read from is your JSON, and after that you can do JSONObject obj = new JSONObject(<your string here>);


text:
Q: Substituting matched characters with a value from object I have a string as follows:
{hours}/DP1/{facilityId}/CP23/{minutes}

and have an object which is:
{
  hours: 4,
  facilityId: "abd-rtyo-99e",
  minutes: 43
}

I want to get the output string as :
4/DP1/abd-rtyo-99e/CP23/43

thus replacing any token inside {} with a value from object. So hours inside {} gets replaced with 4 from the object, minutes by 43 and so on. How could I do this?
I could detect characters inside {} using a regular expression like {\w+} but don't know how to proceed with it.

A: You can loop through all the keys of object using for..in and then replace() the key in original string with the value of key

let str = '{hours}/DP1/{facilityId}/CP23/{minutes}'

const obj = {
  hours: 4,
  facilityId: "abd-rtyo-99e",
  minutes: 43
}
let result = str;
for(let k in obj){
  result = result.replace(`{${k}}`,obj[k]);
}
console.log(result)

A: One option is to match word characters, and use a replacer function which checks to see if the key exists on the object - if so, return the associated value:

const input = '{hours}/DP1/{facilityId}/CP23/{minutes}';
const obj = {
  hours: 4,
  facilityId: "abd-rtyo-99e",
  minutes: 43
};
const output = input.replace(
  /{(\w+)}/g,
  (match, possibleKey) => obj[possibleKey] ? obj[possibleKey] : match
);
console.log(output);
// 4/DP1/abd-rtyo-99e/CP23/43

A: Another option could be to use Object.entries and use the key and value in the replacement:

let obj = {
  hours: 4,
  facilityId: "abd-rtyo-99e",
  minutes: 43
};
let str = '{hours}/DP1/{facilityId}/CP23/{minutes}';
Object.entries(obj).forEach(([key, value]) => {
  str = str.replace(`{${key}}`, value);
});

console.log(str);


text:
Q: ListLinePlot x-axis units label If I want to label the $x$-axis of a ListLinePlot , how do I do that?
There are two types of label:

*

*a units label which would go to the right of the axis,

and then potentially you could have an

*

*axis label below it.

What would be the way to enter both types of text?

A: Labeled is quite short solution:
Labeled[ListLinePlot[RandomReal[1, 6], AxesLabel -> {"x", "y"}],
        {"x label", "y label"},
        {Bottom, Left}, RotateLabel -> True]

A: Try this:
   Row[{
  Rotate[Style["Second label Y", 16, Bold], 90 Degree],
  Spacer[10],
  Column[{
    ListLinePlot[RandomReal[1, 6],
     AxesLabel -> {Style["x", 16, Italic], Style["y", 16, Italic]},
     ImageSize -> 350],
    Style["Second label X", 16, Bold]
    }, Alignment -> Center]
  }]

You should obtain something of this sort:

A: It's probably late to mention, but I always add frame in my plot
`ListPlot[t1b9, PlotRange -> {{0, 0.5}, {0.045, 0.05}}, Frame -> True, FrameLabel -> {"t_1","Energy (kJ/mol)"}]`

which produces the following graph, t1b9 is just the data collection I used for my plot

Hope this helps!