text:
Q: NSManagedObject save only the latest object and not the whole objects I've a json response I'm trying to save to Core Data using NSManagedObject with the following code:
- (void)breakTrapsToSave:(NSDictionary*)trapsDict
{
    tempA = [trapsDict objectForKey:@"Envelope"];
    tempB = [tempA objectForKey:@"Body"];
    tempC = [tempB objectForKey:@"getTrapsResponse"];
    tempD = [tempC objectForKey:@"getTrapsResult"];
    tempE = [tempD objectForKey:@"TRAPS"];

    self.lastUpdate = [tempE objectForKey:@"lastUpdate"];
    [self.sharedPrefs setObject:self.lastUpdate forKey:@"last_update"];
    [self.sharedPrefs synchronize];
    NSLog(@"Traps latest updated at: %@", self.lastUpdate);

    tempF = [tempE objectForKey:@"TRAP"];

    [tempF enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
        tempA = [tempF objectAtIndex:idx];
        NSString *finalResult;
        NSString *key;

        for (int i=0; i < node.count; i++) {
            tempB = [tempA objectForKey:[node objectAtIndex:i]];
            finalResult = (NSString*)tempB;
            key = [node objectAtIndex:i];

            [self addToCoreData_value:finalResult key:key]; // Core Data
        }
        counter = idx;
    }];

    NSLog(@"Total Traps: %d", counter);
}

#pragma mark - Core Data Methods

- (void)initCoreData
{
    IDANAppDelegate *appDelegate = [[UIApplication sharedApplication] delegate];
    context = appDelegate.managedObjectContext;
    entityDesc = [NSEntityDescription entityForName:@"Trap" inManagedObjectContext:context];
    managedObject = [[NSManagedObject alloc] initWithEntity:entityDesc insertIntoManagedObjectContext:context];
}

- (void)addToCoreData_value:(NSString*)value key:(NSString*)key
{
    if ([key isEqualToString:@"alarmDistance"] ||
        [key isEqualToString:@"degrees"] ||
        [key isEqualToString:@"id"] ||
        [key isEqualToString:@"polys"] ||
        [key isEqualToString:@"roadNumber"] ||
        [key isEqualToString:@"type"]) {

        [managedObject setValue:[NSNumber numberWithInt:[value intValue]] forKey:key];
    }
    else if ([key isEqualToString:@"lat"] ||
               [key isEqualToString:@"lon"]) {
        [managedObject setValue:[NSNumber numberWithFloat:[value floatValue]] forKey:key];
    }
    else  if ([key isEqualToString:@"isActive"]) {
        BOOL toSet = false;

        if ([value isEqualToString:@"True"]) {
            toSet = YES;
        }
        else {
            toSet = NO;
        }

        [managedObject setValue:[NSNumber numberWithBool:toSet] forKey:key];
    }
    else {
        [managedObject setValue:value forKey:key];
    }

    NSError *error;
    [context save:&error];
}

The thing is, I did log and I saw I get the correct values and keys thru the entire enumerateObjectsUsingBlock loop.
Also, in:
 - (void)addToCoreData_value:(NSString*)value key:(NSString*)key

I did a log and I saw I get all the keys and values as well.
But when I open the sqlite I see only one row in the table, the last object.
NSLog(@"Total Traps: %d", counter); - also print the correct amount of objects (116 as for now).
What I'm doing wrong?

A: It looks like you only have one managed object. All you are doing is successively changing the properties of it.
What you should be doing is creating a new managed object for each item you are saving.


text:
Q: Turn Enterprise Keyword column into clickable links I've created an Enterprise Keyword column and have begun tagging documents. My conception was that terms in the column would automatically be clickable links and allow users to see all files tagged with a term by clicking on it.
But that is not the case.
So, how can I achieve this?

redpajama_set_name: RedPajamaStackExchange


text:
Q: Change colours of different shapes using javascript How to apply the following conditions to generate random colour for ALL 9 blocks shown in Figure 1.

a) Randomly apply 4 blocks of the SAME colour from the colour code information
table provided. The colour MUST be different from the rest of the 5 blocks.
b) Randomly apply 3 blocks of the SAME colour from the colour code information
table provided. The colour MUST be different from the rest of the 6 blocks.
c) Randomly apply 2 blocks of the SAME colour from the colour code information
table provided. The colour MUST be different from the rest of the 7 blocks.
Color Code Information Table:
#800000,
#A36386,
#FFD4D8,
#223CFF,
#F5FF5A,
#FF5555,
#A7EBFF

var abcArray = ["#800000", "#A36386", "#FFD4D8", "#223CFF", "#F5FF5A", "#FF5555", "#A7EBFF"];

function run() {
  var abcArray = ["#800000", "#A36386", "#FFD4D8", "#223CFF", "#F5FF5A", "#FF5555", "#A7EBFF"];

  var table = document.getElementsByClassName("spanrows2")[0];
  var tr = document.createElement("tr");
  var td = document.createElement("td");
  var txt = document.createTextNode("Question 1 number: 1");

  table.appendChild(tr);
  td.appendChild(txt);
  tr.appendChild(td);
}

window.addEventListener("load", run, false);
body {
  font-size: 30px;
  font-family: "Arial", "sans-serif";
}

table {
  margin-top: 50px;
  background-color: white;
  border: 1px solid black;
  margin-left: auto;
  margin-right: auto;
  width: 50%
}

td {
  width: 700px;
  padding: 5px;
  border: 1px solid black;
}

.spanrows1,
.spanrows2 {
  text-align: center;
}

.spanrows1 {
  width: 400px;
}

.spanrows2 {
  width: 600px;
}

.span2rows {
  text-align: left;
}

.squareDivs {
  width: 100px;
  height: 100px;
  background-color: #000000;
  margin: 10px;
  border-radius: 10px;
  display: inline-block;
}

.squareTxt {
  line-height: 100px;
  vertical-align: middle;
}

.alignTxt {
  text-align: center;
}

A: I believe you are looking for document.getElementsByClassName.
This method can get all elements with a particular class name. Here is the documention.
With that you will be able to get your elements.
In order to make things random, you will have to make the computer randomly generate some sort of true/false value. In order to accomplish this, Math.Random should work fine. Here is the documentation.
I am intentionally excluding code examples, as this is an assignment. I have mentioned some particularly useful functions and provided links to the documentation on these functions. My intention in doing this, is to have you read about the functions and try to implement them yourself.
If you are having trouble getting things to work with those 2 functions, don't be afraid to ask for more help here. :)


text:
Q: Build a sequence $x_n$ such that $PL\{x_n\}=[0,1]$. Build a sequence $x_n$ such that $PL\{x_n\}=[0,1]$. $PL$ of a sequence is the set of partial limits...
I tried using the harmonic series but it wouldn't work. Any suggestion?

A: Try $  \mathbb{Q} \cap [0,1]$.

A: This answer assumes that a "partial limit" is the limit of a subsequence, each $x_n$ is a real number, and $PL\{x_n\}$ is the set of partial limits of the sequence.
One possible sequence is
$$1,$$
$$\frac 12,1,$$
$$\frac 14,\frac 12,\frac 34,1,$$
$$\frac 18,\frac 14,\frac 38,\frac 12,\frac 58,\frac 34,\frac 78,1,$$
$$\ldots,$$
$$\frac 1{2^k},\frac 2{2^k},\frac 3{2^k},\ldots,\frac {2^k-1}{2^k},1,$$
$$\ldots$$
It's not very hard to come up with a formula for $x_n$: I'll leave it to you.
There are many variations on this, of course. One is to use powers of ten rather than powers of two:
$$1,$$
$$0.1,0.2,0.3,0.4,0.5,0.6,0.7,0.8,0.9,1.0,$$
$$0.01,0.02.0.03,\ldots,0.99,1.00,\ldots$$
It should be clear why every real number between zero and one is a limit of a subsequence of either of these sequences.
Let me know if you need more detail, or if you need a sequence where all the $x_n$ are distinct.


text:
Q: Android Application java lang exception I have created an android application using Android Studio IDE while clicking the button in my app it does'nt navigate it to the another activity instead its throwing up the exception
Here is My Logcat:
        02-10 11:33:56.030    7404-7404/com.example.mcs.oodoeg E/AndroidRuntime﹕ FATAL EXCEPTION: main
            java.lang.ExceptionInInitializerError
                    at org.apache.xmlrpc.common.XmlRpcController.<init>(XmlRpcController.java:31)
                    at org.apache.xmlrpc.client.XmlRpcClient.<init>(XmlRpcClient.java:51)
                    at com.example.mcs.oodoeg.MainActivity.getXmlRpcClient(MainActivity.java:138)
                    at com.example.mcs.oodoeg.MainActivity.registerUser(MainActivity.java:103)
                    at com.example.mcs.oodoeg.MainActivity$1.onClick(MainActivity.java:45)
                    at android.view.View.performClick(View.java:4275)
                    at android.view.View$PerformClick.run(View.java:17434)
                    at android.os.Handler.handleCallback(Handler.java:615)
                    at android.os.Handler.dispatchMessage(Handler.java:92)
                    at android.os.Looper.loop(Looper.java:177)
                    at android.app.ActivityThread.main(ActivityThread.java:4947)
                    at java.lang.reflect.Method.invokeNative(Native Method)
                    at java.lang.reflect.Method.invoke(Method.java:511)
                    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1038)
                    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:805)
                    at dalvik.system.NativeStart.main(Native Method)
             Caused by: java.lang.ExceptionInInitializerError
                    at org.apache.xmlrpc.common.TypeFactoryImpl.<clinit>(TypeFactoryImpl.java:88)
                    at org.apache.xmlrpc.common.XmlRpcController.<init>(XmlRpcController.java:31)
                    at org.apache.xmlrpc.client.XmlRpcClient.<init>(XmlRpcClient.java:51)
                    at com.example.mcs.oodoeg.MainActivity.getXmlRpcClient(MainActivity.java:138)
                    at com.example.mcs.oodoeg.MainActivity.registerUser(MainActivity.java:103)
                    at com.example.mcs.oodoeg.MainActivity$1.onClick(MainActivity.java:45)
                    at android.view.View.performClick(View.java:4275)
                    at android.view.View$PerformClick.run(View.java:17434)
                    at android.os.Handler.handleCallback(Handler.java:615)
                    at android.os.Handler.dispatchMessage(Handler.java:92)
                    at android.os.Looper.loop(Looper.java:177)
                    at android.app.ActivityThread.main(ActivityThread.java:4947)
                    at java.lang.reflect.Method.invokeNative(Native Method)
                    at java.lang.reflect.Method.invoke(Method.java:511)
                    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1038)
                    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:805)
                    at dalvik.system.NativeStart.main(Native Method)
             Caused by: java.lang.NoClassDefFoundError: org.apache.ws.commons.serialize.DOMSerializer
                    at org.apache.xmlrpc.serializer.NodeSerializer.<clinit>(NodeSerializer.java:30)
                    at org.apache.xmlrpc.common.TypeFactoryImpl.<clinit>(TypeFactoryImpl.java:88)
                    at org.apache.xmlrpc.common.XmlRpcController.<init>(XmlRpcController.java:31)
                    at org.apache.xmlrpc.client.XmlRpcClient.<init>(XmlRpcClient.java:51)
                    at com.example.mcs.oodoeg.MainActivity.getXmlRpcClient(MainActivity.java:138)
                    at com.example.mcs.oodoeg.MainActivity.registerUser(MainActivity.java:103)
                    at com.example.mcs.oodoeg.MainActivity$1.onClick(MainActivity.java:45)
                    at android.view.View.performClick(View.java:4275)
                    at android.view.View$PerformClick.run(View.java:17434)
                    at android.os.Handler.handleCallback(Handler.java:615)
                    at android.os.Handler.dispatchMessage(Handler.java:92)
                    at android.os.Looper.loop(Looper.java:177)
                    at android.app.ActivityThread.main(ActivityThread.java:4947)
                    at java.lang.reflect.Method.invokeNative(Native Method)
                    at java.lang.reflect.Method.invoke(Method.java:511)
                    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1038)
                    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:805)
                    at dalvik.system.NativeStart.main(Native Method)

This is my  Main Activity class i have created two buttons here called register and signin:
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    Button btn;

    btn = (Button) findViewById(R.id.button);
    btn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Intent intObj = new Intent(MainActivity.this,MainActivity2.class);
            startActivity(intObj);

        }
    });
    Button btn2;
    btn2=(Button) findViewById(R.id.button2);
    btn2.setOnClickListener(new View.OnClickListener() {
        public void onClick(View view) {
            Intent intent= new Intent(MainActivity.this,Sigin.class);
            startActivity(intent);
        }
    } );
}

When the register button is clicked this  Main Activity2 should be called:
public class MainActivity2 extends Activity{
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.next);
    }

When sigin button is clicked this sigin class should be called:
public class Sigin extends Activity {
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.sigin);
    }
}

A: I think you are  missing ws-commons-util-1.0.2.jar from $EXIST_HOME/lib/core.
You have to make sure you have included at least all of the libraries from $EXIST_HOME/lib/core.


text:
Q: Occured HibernateException in JPA @Entity
public class ZipCode extends GenericModel {

public String zipCode;
public String townCode;
@ManyToOne(targetEntity=Town.class,fetch=LAZY)
@JoinColumn(referencedColumnName="townCode",name="townCode",nullable=true,insertable=false,updatable=false)
public Town town;
}

@Entity
public class Town extends GenericModel {
public String townCode;
public String townName;
public String cityCode;
@ManyToOne(targetEntity=City.class,fetch=LAZY)
@JoinColumn(referencedColumnName="cityCode",name="cityCode",nullable=true,columnDefinition="city",insertable=false,updatable=false)
public City city;
}

@Entity
public class City extends GenericModel {
public String cityCode;
public String cityName;
public String prefectureCode;
@ManyToOne(targetEntity=Prefecture.class,fetch=LAZY)
@JoinColumn(referencedColumnName="prefectureCode",name="prefectureCode",nullable=true,columnDefinition="prefecture",insertable=false,updatable=false)
public Prefecture prefecture;
}

@Entity
public class Prefecture extends GenericModel {
public String prefectureCode;
public String prefectureName;
}

DataBase is ,

ZipCode

zipcode | towncode

111     | 123

222     | 456

Town

towncode | townname | citycode
123      | AAA      | 12345

456      | BBB      | 67890

789      | CCC      | 12345

City

citycode | cityname | prefecturecode

12345    | XXX      | 12

67890    | YYY      | 34

Prefecture

prefecturecode | prefecturename

12             | MMM

34             | NNN

and execute this,
List<ZipCode> zipCodes = ZipCode.find("zipcode = 111").<ZipCode>fetch();

and this error occured,

org.hibernate.HibernateException: More than one row with the given identifier was found: Town[null], for class: models.Town

I try to change the DataBase value ,
Town
towncode | townname | citycode
123      | AAA      | 12345
456      | BBB      | 67890
789      | CCC      | 12321
then, teh error has not occured...
but, I want not to change this value.
does anyone know the solution of this ?

A: May be you can try this.
@Entity
public class Town extends GenericModel {

    public String townCode;

    public String townName;

    public String cityCode;

}

@Entity
public class City extends GenericModel {

    public String cityCode;

    public String cityName;

    public String prefectureCode;

    @ManyToOne(targetEntity=Prefecture.class,fetch=LAZY)
    @JoinColumn(referencedColumnName="prefectureCode",name="prefectureCode",nullable=true,columnDefinition="prefecture",insertable=false,updatable=false)

public Prefecture prefecture;

    @OneToMany(targetEntity=Town.class,fetch=LAZY)
    @JoinColumn(referencedColumnName="townCode",name="townCode",nullable=true,columnDefinition="city",insertable=false,updatable=false)

public List<Town> towns;

}


text:
Q: NextNProgress remove spinner I use nextjs-progressbar. But I can't hide spinner.  I'm trying to remove the spinner like this but it doesn't work:
#nprogress .spinner {
   display: none;
}

A: There is a nice parameter showSpinner inside options:
<NextNProgress options={{ showSpinner: false }} />


text:
Q: Why do inductors in motherboard VRMs have high-voltage build-up without diodes? I just watched Bullzoid/Actually Hardcore Overclocking's video on how VRMs actually work, and I have a question.

First, in my understanding, the diodes in the VRMs are included to stop the inductor from having a massive voltage build-up. Normally this could cause destruction of the CPU, so the diodes prevents an open circuit in case the two transistors are opened at the same time.
From physics EM, I know the current in the inductors tries to stay constant because changes in the induced magnetic flux are resisted due to Lenz's law.
However, I'm not sure why in an open-circuit configuration with both transistors off at the same time, the charged inductor's voltage would continue to rise to an extremally high voltage. The video says that it is due to the inductor's stored current being suddenly dumped out because of the rapidly collapsing magnetic field, but could someone clarify intuitively why the inductor's voltage only spikes with an open circuit, as opposed to the "clean" and safe discharging in a closed-circuit configuration with the diode?

A: The diode in the diagram prevents the voltage from rising.
If you don't have a diode, such as with just battery and a coil, if you connect the battery to coil, current starts flowing, and when you disconnect battery, the circuit is open but the inductor would stil need to pass current, which is impossible. Thus inductor voltage rises in theory up to infinity to keep the current flowing. And that's why e.g. relay coils need diodes so switching transistors don't burn out or mechanical switches degrade from the arcing.

A: Let me walk you through it.
Assume the high side switch is on and current is flowing from PSU through choke to CPU.
Then, the high side switch is turned off, because, well it has to turn on and off to maintain the correct voltage at the CPU.
So a very short time AFTER the high side switch is turned off, the low side switch is turned on.
During that brief dead time when both transistors are off, the voltage at A will spike in the negative direction. Without the diode, it would shoot far below ground and probably destroy the high side switch.
But with the diode, the voltage at A is constrained to one diode drop below ground which is no problem for the high-side mosfet. The current through the diode will be approximately the same as the load current.
You might wonder why we have to turn the low-side on after the high side is turned off. Well, that dead time is needed because we can't risk having high and low side on at the same time (that would be a short circuit of the PSU). The dead time might be something like 100 to 300 nanoseconds. It is not much but it is very important.

A: More of a couple side notes than a complete answer.  Or, something of a "that's a bad question, here's what you meant to ask", but not so rudely!  Explaining why.  Which, in the course of explanation, should ultimately answer the question, or lead on the path to it (or, hopefully).

The CPU isn't in any danger, anyway.
At least not from switch-off.  The switching node would experience a higher voltage, if unclamped: the CPU end is solidly anchored by the capacitor, so doesn't see any more than normal switching ripple during the event.  Indeed on a cycle-to-cycle basis, we can consider it an ideal voltage source (the ripple voltage is small enough to ignore).
This is almost circular reasoning, but note carefully how it isn't: we're permitting the approximation of a voltage source, because we've established that the voltage change is small.  Because the voltage change is small, we can also conclude the CPU is fine, at least on a cycle-to-cycle basis.
So, putting the diode there, simply protects the switch.  Or switching both switches perfectly in sync (or perhaps even slightly overlapped, if we have some way to deal with momentarily shorting out the supply).
Leaving the switch on (high) for several cycles, would most certainly damage the CPU, but that's another matter -- that would violate the no-voltage-change assumption!
On the underlying assumption that charging and discharging an inductor somehow necessarily creates dangerous voltages.
This is a nonlinearity.  It's a situation that shows up often enough it seems familiar, normal even.  For example, anyone who's held onto the leads of a solenoid or transformer or what have you, while charging it from a battery then letting go, will know this shocking fact.  But this is in fact a particular case, and actually a rather extreme one, but you will only learn this much later into an EE curriculum (if indeed this exact point is made at all -- or inferred from available information).
The problem is the impedance connected across the inductor.
While it's charging, it's supplied from a battery, a voltage source.  Its DC resistance limits current flow, which gradually rises up to I = V/R (at a time constant of τ = L/R).  When disconnected, the circuit is broken, impedance is very high, and the inductance can discharge very quickly -- there's no consequential here, it's simply equivalent to say that the terminal voltage is large and the rate-of-change of current (dI/dt) is large.  The equivalence is the equation of inductance:
$$ V = L \frac{dI}{dt} $$
If we connect a large impedance (meaning Z = V/I has a large value), then V will be relatively large, during that brief moment when dI/dt is also large.
If we instead keep the impedance constant, as in the use of an LC signal filter for example, there's no meaningful flyback action, it simply does, well, whatever a filter does.  Certain frequencies are attenuated, others are passed; the peak voltage or current isn't anything special.
The impedance of a switching converter isn't exactly straightforward, by itself, but the fact that we're always driving the inductor with one switch or another (or equivalently, a diode -- still a low impedance, if not an ideal switch), and so there's no flyback, it's just doing what it does.  We apply a voltage to one end, the inductor (and output filter capacitor) constitute a signal filter, and the switching ripple is filtered down to a level suitable for the CPU.
This remains true even in the so-called flyback converter, where the output voltage is defined by supplied current (through the converter), and load resistance.  Here, if the energy balance goes off -- if the converter keeps going while the load resistance goes super high -- the output voltage would indeed shoot up very high.  This situation is solved by the control: we simply don't run the converter's "throttle" any higher than is needed by the load.  After all, the same is true in this situation -- if we could safely apply 12 V to the CPU, we damn well would save the trouble of the converter!  So, here too, we can't have the control going 100% throttle, that would destroy the poor thing.  Control is critical in either case, so as to keep output voltage, or current, or whatever it is we're controlling, within the expected range.
Related
You often see language like:

The magnetic field collapses and a high voltage results.

Magnetic field is... not a structure subject to gravity, of course it doesn't fall over like a stack of bricks, but language like this still floats around regardless.  (I don't know its exact history, but it's been in just about every textbook I've seen, so, the better part of a century anyway.)  I feel like repeating this phrase is more harmful than helpful.
A physicist would note that the field stores energy, so, it takes some sort of "force" to keep it there (much as the weight in the beams supporting a building), and it "wants" to get out -- that energy will easily transfer into whatever circuit it's connected to.  But it's up to the circuit, how fast that transfer happens.  Again, because of the inductor equation: if the voltage is constrained, so too the rate-of-change of current, and thus how fast it discharges.  Or vice versa: if the rate is low, so too will be the voltage.  Again, equivalent parameters here.
Point being, flyback isn't something we just have to, like, resign ourselves to dealing with; that's like resigning ourselves to the wrath of Zeus because we didn't want to install lightning rods!  But worse, even, because it's such a trivial case (a perfectly predictable inductor) and assigning that to ignorance would be incredibly silly.  In fact, flyback (or the lack thereof) is something we have done, by setting up the circuit around the inductor.  It is wholly of our own consequence, and entirely predictable.


text:
Q: Reuse hashmaps in array I am holding an array of hashmaps, I want to gain maximum performance and memory usage so I would like to resue the hashmaps inside an array.
So when there is a hashmap in the array that is not needed any more and I want to add new hashmap to the array I just clear the hashmap and use put() to add new values.
I also need to copy back values when I retireve hashmap from array.
I am not sure if this is better than creating new HashMap() every time.
What is better?
UPDATE
need to cycle about 50 milions of hashmaps, each hash map has about 10 key-value pairs. If size of the array 20,000 I need just 20,000 hashmaps instead of 50 milions new hashmaps()

A: Be very careful with this approach. Although it may be better performance-wise to recycle objects, you may get into trouble by modifying the same reference several times, as illustrated in the following example:
public class A {
    public int counter = 0;

    public static void main(String[] args) {

         A a = new A();
         a.counter = 5;
         A b = a; // I want to save a into b and then recycle a for other purposes
         a.counter = 10; // now b.counter is also 10
    }
}

I'm sure you got the point, however if you are not copying around references to HashMaps from the array, then it should be ok.

A: Doesn't matter. Premature optimization. Come back when you have profiler results telling you where you're actually spending most memory or CPU cycles

A: It is entirely unclear why re-using maps in this manner would improve performance and/or memory usage. For all we know, it might make no difference, or might have the opposite effect.
You should do whatever results in the most readable code, then profile, and finally optimize the parts of the code that the profiler highlights as bottlenecks.

A: In most cases you will not feel any difference.
Typically number of map entries is MUCH higher than number of map objects. When you populate map you create instance of Map.Entry per entry. This is relatively light-weight object but anyway you invoke new. The map itself without data is lightweight too, so you will not get any benefits with these tricks unless your map is supposed to hold 1-2 entries.
Bottom line.
Forget about pre-mature optimization. Implement your application. If you have performance problems profile the application, find bottle necks and fix them. I can 99% guarantee you that the bottleneck will never be in new HashMap() call.

A: I think what you want is an Object pool kind of thing, where you get an object(in your case, its HashMap) from the object pool, perform your operations, and if that Object is no longer needed you put it back in the pool.
check for Object pool design pattern, for further reference check this link :
http://sourcemaking.com/design_patterns/object_pool

A: The problem you have is that most of the objects are Map.Entry objects in the HashMap. While you can recycle the HashMap itself (and its array) these are only a small portion of the objects.  One way around this is to use FastMap from javolution which recycles everything and has support for managing the lifecycle (its designed to minimise garbage this way)
I suspect the most efficient way is to use an EnumMap is possible (if you have known key attributes) or POJOs even if most fields are not used.

A: There's a few problems with reusing HashMaps.

*

*Even if the key and value data were to take no memory (shared from other places), the Map.Entry objects would dominate memory usage but not be reused (unless you did something a bit special).

*Because of generational GC, generally having old objects point to new is expensive (and relatively difficult to see what's going on). Might not be an issue if you are keeping millions of these.

*More complicated code is more difficult to optimise. So keep it simple, and then do the big optimisations, which probably involve changing the data structures.


text:
Q: SOQL query minimum Date in WHERE clause trying to get field with the earliest date from custom object. Here is my current query
BomaGroups =    [SELECT Name, Location__c FROM Group__c WHERE Location__c =:id]; // Selects the Group I want from Location Master object
MeetingsList2 = [SELECT Name, Group__c, Business_Value__c, Meeting_Date__c, GPS_Meeting_Location__Latitude__s, GPS_Meeting_Location__Longitude__s,
Group__r.Name FROM Meeting__c WHERE Group__c =:BomaGroups
ORDER BY Meeting_Date__c DESC LIMIT 1]; // Selects Meetings I want with the Groups SOQL  as the where clause

I have 3 custom objects, Location(master), Groups(child), meeting(grand child). The above query works fine for getting 1 record but its supposed to return only the earliest date values for all the records matching the where clause. I was thinking of inserting an SOQL statement in the where clause for minimum date, any clues?
Tried the following subquery to combine the 2 statements, generated Error: Didn't understand relationship 'Group__r'
BomaGroupsList = [select Name, Location__c, (SELECT Name, Group__c, Business_Value__c,       Meeting_Date__c, GPS_Meeting_Location__Latitude__s,GPS_Meeting_Location__Longitude__s FROM Group__r ORDER BY Meeting_Date__c DESC LIMIT 1) FROM Group__c WHERE Location__c =:id];

A: Try this:
list<Group> groups = [select id, name, (SELECT Name, Group__c, Business_Value__c, Meeting_Date__c, GPS_Meeting_Location__Latitude__s, GPS_Meeting_Location__Longitude__s FROM Meetings__r ORDER BY Meeting_Date__c DESC LIMIT 1
 ) from Group where Id =:BomaGroups];

Your limit 1 in the original query applied to the whole of the result set and therefore only returned 1 record. By using a sub-query you can get the records that relate to the groupIds you need. I have guessed at the lookup relationship api name being Meetings__r - this may need adjusting.


text:
Q: How to create additional TaskExecutor beside TaskExecutionAutoConfiguration? I want spring to load the default ThreadPoolTaskExecutor from TaskExecutionAutoConfiguration. Though I want to provide may own additional executor for some explicit side-tasks:
@Bean
public ThreadPoolExecutor myRequestPool() {
    return (ThreadPoolExecutor) Executors.newFixedThreadPool(10);
}

Problem: adding the bean above, the TaskExecutionAutoConfiguration will not be executed anymore, and the spring-default executor will not be initialized, because @ConditionalOnMissingBean(Executor.class) does not match anymore:
package org.springframework.boot.autoconfigure.task;

public class TaskExecutionAutoConfiguration {

    @Lazy
    @Bean(name = APPLICATION_TASK_EXECUTOR_BEAN_NAME)
    @ConditionalOnMissingBean(Executor.class)
    public ThreadPoolTaskExecutor applicationTaskExecutor(TaskExecutorBuilder builder) {
        return builder.build();
    }

Question: how can I still let spring create both beans?

A: The executor bean in TaskExecutionAutoConfiguration will only be created if no other executor beans exist (due to @ConditionalOnMissingBean(Executor.class)) at the moment when processing that auto-configuration . So , in order to create both of our executor and the one defined in TaskExecutionAutoConfiguration , we need to make sure our bean is processed after TaskExecutionAutoConfiguration
According to docs , if we make our bean to be the auto-configuration candidates (which requires adding the @Configuration class in META-INF/spring.factories),  we can then use @AutoConfigureAfter to configure it to be processed after TaskExecutionAutoConfiguration :
package foo.bar.baz.qux;

@Configuration
@AutoConfigureAfter(TaskExecutionAutoConfiguration.class)
public class Config {
    @Bean
    public ThreadPoolExecutor myRequestPool() {
        return (ThreadPoolExecutor) Executors.newFixedThreadPool(10);
    }
}

Then create META-INF/spring.factories which contains :
org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
  foo.bar.baz.qux.Config

A: Important: Without the following "hack", Springs default behavior here is to simply hard replace the default executor with your custom one. And as a result, also execute any normal @Async methods with your custom executor. This may mostly have undesired results.
The solution is to provide the default applicationTaskExecutor explicit, like in TaskExecutionAutoConfiguration. But without the @ConditionalOnMissingBean annotation, as follows:
@Configuration
public class AppConfig {
    @Lazy
    @Bean(name = { TaskExecutionAutoConfiguration.APPLICATION_TASK_EXECUTOR_BEAN_NAME,
            AsyncAnnotationBeanPostProcessor.DEFAULT_TASK_EXECUTOR_BEAN_NAME })
    public ThreadPoolTaskExecutor applicationTaskExecutor(TaskExecutorBuilder builder) {
        return builder.build();
    }
}

This way, the default executor is always loaded, and additional custom executors can be added to the application without replacing it (which is the default behavior).
As a result, all @Async methods will still execute with the default applicationTaskExecutor, and all @Async("customExecutor") will use your custom one.


text:
Q: What way can someone color this image to illustrate the Four Color Theorem? I've seen similar questions like this and highly doubt this is a disproof or anything, but I still find solutions to these types of problems very satisfying. Here is the map I developed with my attempt and a black and white one beside it. https://drive.google.com/file/d/1UKUHvCh1EyXS9vh1j2mFC6ljbwSZ0K4b/view?usp=sharing

I would like someone to color this image to align with the Four Color Theorem, which states that on any map that contains only contiguous shapes, only four colors are required to color the shapes such that no shape bordering one another shares a color. Corners do not count as borders.

A: If you change the green piece to blue, and change the blue piece in the lower right to white you get the picture below which requires only four colours.


text:
Q: Derivative of Summation How to handle summations with an additional factor in derivation?
Let's say I have a function
$$f(x)=\alpha*\sum_{i=0}g(x,i)$$
and I want to build the derivative $f'(x)$ of it. I know that the the derivative of a sum is equal to the sum of derivatives but what happens to $\alpha$?


text:
Q: Cant start IReport 3.0 after uninstalling Java 8 I have 3 jdks installed in my machine, 1.6, 1.7, and 1.8. IReport 3.0 was working fine before removing jdk 8. But after removing jdk 8, IReport 3.0 wont start.
Any idea on how to resolve this?
Error:
'javaw' is not recognized as an internal or external command,
operable program or batch file.

A: When you uninstalled jdk8, it removed [java location]/bin from your Path environment variable.  You need to add the bin path of whichever jdk installation you want to use to Path.


text:
Q: kotlin 'onCreate' overrides nothing I am using component development, in my common module BaseActivity.kt and BaseFragment.kt. The following problems occur when other modules inherit them
> D:\Android\OneDaily\module_main\src\main\java\com\boco\main\MainActivity.kt
> Error:(7, 24) Unresolved reference: base
> Error:(9, 22) Unresolved reference: BaseActivity
> Error:(21, 5) 'onCreate' overrides nothing
> Error:(17, 5) 'getLayoutRes' overrides nothing
> Error:(22, 15) Unresolved reference: onCreate
> Error:(27, 22) Unresolved reference: findViewById
> Error:(42, 34) Unresolved reference: supportFragmentManager
> D:\Android\OneDaily\module_main\src\main\java\com\boco\main\TimelineFragment.kt
> Error:(7, 24) Unresolved reference: base
> Error:(10, 5) 'getLayoutRes' overrides nothing
> Error:(9, 26) Unresolved reference: BaseFragment
> Error:(14, 5) 'onCreateView' overrides nothing
> Error:(15, 22) Unresolved reference: onCreateView

BaseActivity.kt:
abstract class BaseActivity : AppCompatActivity() {
    init {
        AppCompatDelegate.setCompatVectorFromResourcesEnabled(true)
    }
    abstract fun getLayoutRes(): Int
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(getLayoutRes())
    }
}

MainActivity.kt
class MainActivity : BaseActivity() {

    private lateinit var mBottomNav: BottomNavigationView

    private var mFragment1 = TimelineFragment() as Fragment
    private var mFragment2 = TimelineFragment() as Fragment
    private var mFragment3 = TimelineFragment() as Fragment

    override fun getLayoutRes(): Int {
        return R.layout.activity_main
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

    }
}

A: It can happen also in a Fragment class: I found the same issue for the method onCreateView; to avoid that, just remove the ? from the LayoutInflater parameter,
Like this:
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View?

A: It seems some functions have changed in the last update,
just remove the '?' from the Bundle
Like this:
override fun onCreate(savedInstanceState: Bundle) {
    super.onCreate(savedInstanceState)
}

A: I have to add "?" when using appcompat-v7:27.1.1
implementation "com.android.support:appcompat-v7:27.1.1

and
override fun onCreate(savedInstanceState : Bundle?){
    super.onCreate(savedInstanceState)
}

A: Update function signatures or revert to compileSdk from 27 to 26

A: i have fixed this problem. The because of it is you don't config you common module. Please add two lines code at your common module's build.gradle top:

apply plugin: 'kotlin-android'
apply plugin: 'kotlin-android-extensions'

hope this can help you.


text:
Q: Rewriting URL's based on Parameters I have searched for this question but couldn't find the exact answer as what I learned is not working.
I have a website that utilizes a script and causes a mess for me, as far as SEO goes. The site has multilingual support so each page (index.php, about.php, etc) has an English version (default) and various other languages that were translated.
So the URL's look like this: example.com/index.php?code=DE (German)
Now if they switch languages on that page is automatically adds that parameter, which means if they were on about.php it would turn into about.php?code=HU
My goal is to rewrite these URL's into subdirectories, like so:
example.com/index.php?code=HR turns into:
example.com/hr/
Or, if I was at example.com/about.php?code=IT turns into:
example.com/it/about
Originally I started out with trying:
    RewriteEngine On
RewriteRule ^([^/]+)$ index.php?ccode=$1 [QSA]

I couldn't get this to work correctly and I realize this is much simpler than the idea stated above. I was just trying to get something started and go from there. This wouldn't even work to rewrite to /us (Example)
Any help or ideas would be appreciated.


text:
Q: How does changing the allocation ratio affect the required sample size in a medical trial? When finding the sample size for a medical trial with a $1:1$ allocation ratio between treatment and placebo groups where the standard deviation is 10, $\tau = 5$, with a significance level of $5\%$ and a power of $80\%$, the calculation goes (I believe) as follows:
Given $\alpha = 0.05$, $\beta = 0.2$, $\tau = 5$, and $\sigma = 10$.
Where $n$ is the sample size
$$
n=2(z_{\alpha/2}+z_\beta)^2\ast\sigma^2/\tau^2\
$$
$$
n=2(z_{0.025}+z_{0.2})^2\ast10^2/5^2\
$$
$$
n=2(1.96+0.85)^2\ast4=63.2
$$
Therefore the required sample size for a 1:1 ratio would be 64 patients.
How does this calculation change with a 2:1 ratio or 3:1 ratio where the larger group is the placebo?

A: First, your sample size computation for a two-sample z test comparing two unknown population means, variances known. is correct. The sample size $n = 64$ is for each group, so
you would need $2n = 128$ subjects total for the
scenario you computed.
If you want an unbalanced z test, you need to go back to the derivation of the formula you used in your question and set $n_2 = 2n_1$ from the start. You will find that unbalanced designs are less
efficient than balanced ones, so you will need more than
$n_1 = 43, n_2 = 86, n_1 + n_2 = 129$ subjects to get the same power.
A similar computation for finding the sample size for given
effect $\tau,$ standard deviations $\sigma = \sigma_1=\sigma_2$ and power for a pooled t test requires use of noncentral t distributions. You can find a derivation and explanation in intermediate level
applied statistics and mathematical statistics texts, or online.
Many statistical software programs have 'power and sample size' procedures. Also, there are online 'power and sample size' calculators (of varying degrees of clarity and accuracy). Most software procedures treat only the balanced case with $n_1 = n_2$ and so will not help you with your current Question.
However, it is easy to find the power for various scenarios
by simulation. I will start with a simulation for a pooled t test (variances unknown but equal) similar to the computation you show in your question (except for a t test). For sample sizes as large as here.
there is not much difference between the power of a t test
and the power of a z test, so the result is to use $n_1 = n_2 = 64.$ as in your computation, to get power 80%.

Notes on R code: With 100,000 iterations power
probabilities should be accurate to two places. At the end
of the run, the vector pv has 100,000 P-values of t tests.
The logical vector pv <= 0.05 has 100,000 TRUEs and FALSEs. The mean of a logical vector is the proportion
of its TRUEs.

set.seed(2021)
n = 64;  sg = 10;  t = 5
pv = replicate(10^5, t.test(rnorm(n,0,sg),
                            rnorm(n,t,sg), var.eq=T)$p.val)
mean(pv <= 0.05)  # power
[1] 0.79896

It takes a little trial and error to get sample sizes in the
ratio 1:2 or 1:3 that will give 80% power. During trial and
error one can speed up the simulations without catastrophic
loss of accuracy by using 10,000 iterations instead of 100,000.
Here are some good approximations to unbalanced sample
sizes that give close to 80% power. For a 2:1 ratio, you need a total of $100 + 50 = 150$ subjects and for a 3:1 ratio,
you need a total of $126 + 42 = 168$ subjects.
# 2:1 ratio
set.seed(605)
n1 = 100;  n2 = 50;  sg = 10;  t = 5
pv = replicate(10^5, t.test(rnorm(n1,0,sg),
                            rnorm(n2,5,sg), var.eq=T)$p.val )
mean(pv <= .05)
[1] 0.81801

# 3:1
set.seed(621)
n1 = 126;  n2 = 42; t = 5;  sg = 10
pv = replicate(10^5, t.test(rnorm(n1,0,sg),
                             rnorm(n2,t,sg), var.eq=T)$p.val)
mean(pv <= .05)
[1] 0.79586


text:
Q: ¿Por que no puedo ejecutar mi app despues de un flutter upgrade? recibí la notificación sobre una actualización de Flutter, por lo tanto ejecute flutter upgrade.
por lo que intente ejecutar ahora mi app con Visual studio code.
Me manda los siguientes mensaje de error que no se como solucionar.
/C:/src/flutter/.pub-cache/hosted/pub.dartlang.org/flutter_image-2.0.0/lib/network.dart:73:24: Error: The method 'NetworkImageWithRetry.load' has fewer positional arguments than those of overridden method 'ImageProvider.load'.   ImageStreamCompleter load(NetworkImageWithRetry key) {
                       ^ /C:/src/flutter/packages/flutter/lib/src/painting/image_provider.dart:403:24: Context: This is the overridden method ('load').   ImageStreamCompleter load(T key, DecoderCallback decode);
                       ^ /C:/src/flutter/.pub-cache/hosted/pub.dartlang.org/cached_network_image-1.1.3/lib/src/cached_network_image_provider.dart:42:24: Error: The method 'CachedNetworkImageProvider.load' has fewer positional arguments than those of overridden method 'ImageProvider.load'.   ImageStreamCompleter load(CachedNetworkImageProvider key) {
                       ^ /C:/src/flutter/packages/flutter/lib/src/painting/image_provider.dart:403:24: Context: This is the overridden method ('load').   ImageStreamCompleter load(T key, DecoderCallback decode);

/C:/src/flutter/.pub-cache/hosted/pub.dartlang.org/flutter_map-0.7.3/lib/src/layer/tile_provider/mbtiles_image_provider.dart:90:24: Error: The method 'MBTileImage.load' has fewer positional arguments than those of overridden method 'ImageProvider.load'.   ImageStreamCompleter load(MBTileImage key) {
                       ^ /C:/src/flutter/packages/flutter/lib/src/painting/image_provider.dart:403:24: Context: This is the overridden method ('load').   ImageStreamCompleter load(T key, DecoderCallback decode);
                       ^ Target kernel_snapshot failed: Exception: Errors during snapshot creation: null build failed.

FAILURE: Build failed with an exception.

* Where: Script 'C:\src\flutter\packages\flutter_tools\gradle\flutter.gradle' line: 780

* What went wrong: Execution failed for task ':app:compileFlutterBuildDebug'.
> Process 'command 'C:\src\flutter\bin\flutter.bat'' finished with non-zero exit value 1

* Try: Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.

* Get more help at https://help.gradle.org

BUILD FAILED in 13s Gradle task assembleDebug failed with exit code 1

A: Esto debido a que hubo breaking changes en el sdk de Flutter, por lo tanto esas dependencias tienen que actualizarse, veo que tienes 2 dependencias que te marca error, solo actualizas:
Para flutter_image debes usar 3.0.0 y para flutter_map aún no publican la nueva versión pero puedes apuntar directamente al repositorio:
  flutter_map:
    git:
      url: https://github.com/avioli/flutter_map.git
      ref: 0.8.0

No te olvides de flutter clean


text:
Q: Angular Share Cookies Between Subdomains I'm using tokens for auth and want to save them as cookies so it can be used between multiple subdomains.
I use ngx-cookie-service for managing cookies and cookies are only accessible on the subdomain they were saved on.
login(username: string, password: string) {
  const token = await this.http.post(loginUrl, { username, password });

  this.cookieService.set("token", token, 1, "/", "*.localhost"); // doesn't work
  this.cookieService.set("token", token, 1, "/", "localhost"); // doesn't work
  this.cookieService.set("token", token, 1, "/", null); // doesn't work
  this.cookieService.set("token", token, 1, "/", "account.localhost"); // even this doesn't work
}

How do I save cookies and use them on multiple subdomains?


text:
Q: Rewriting Ruby Inject Here is a brain bender.
I am trying to rewrite the Ruby Inject method. I have got as far as below.
class Array

  def injector(input = nil)

    if input == nil
      num = self.first
    else
      num = input
    end
    self[0..-1].each do |x|
      num = yield(num, x)
    end
    return num
  end
end

It is passing some tests, but it is not fully accurate, for example;
[1,2,3,4,5].injector(0) {|x,y| x + y} #=> 14

As opposed to the expected output 15, is it a rounding error? I cannot seem to figure this one out

Additional example (above updated [0..-1]):

[9,8,7,6,5].injector {|x,y| x * y} #=> 136080

Ruby .inject outputs 15120

A: The starting index is important as it depends on your input.
class Array

  def injector(input = nil)
    if input.nil?
      start = 1
      num = self.first
    else
      start = 0
      num = input
    end
    self[start..-1].each do |x|
      num = yield(num, x)
    end

    return num
  end

end

A: Using nil as the default is probably wrong, I should be able to pass nil in as the default memo.
class Array
  def injector(memo = (i=1; first))
    (i||0).upto(length-1) { |i| memo = yield memo, self[i] }
    memo
  end
end

[1,2,3,4,5].injector(1) { |sum, n| sum + n }
[1,2,3,4,5].injector(0) { |sum, n| sum + n }
[1,2,3,4,5].injector    { |sum, n| sum + n }

[1,2,3].injector(2) { |product, n| product * n }
[1,2,3].injector(1) { |product, n| product * n }
[1,2,3].injector    { |product, n| product * n }

['b', 'c', 'd'].injector('a') { |str, char| str + char } # => "abcd"
['b', 'c', 'd'].injector      { |str, char| str + char } # => "bcd"

seen = []
[1].injector(nil) { |prev, crnt| seen << prev << crnt }
seen # => [nil, 1]


text:
Q: Build a Login / register / forgot password form / page Im wanting to build a a Login / register / forgot password form / page using ATK4. Can you point me to any documentation or a tutorial on this.
Thank You

A: Documentation
You can see the steps to allow a login using basicauth with agiletoolkit on another question i answered on stackoverflow and on agiletoolkit and there is some documentation on the agiletoolkit tutorial pages
The documentation for sending emails using Tmail.php is also on the agiletoolkit blog
Manual Way
The login form itself doesnt exist as a page but is defined inside /atk4/lib/BasicAuth.php
To change this to use the database, you can use SqlAuth instead of BasicAuth which then stores the users information and passwords in the database.
In versions before 4.0.3 there was another class called atk4/lib/DBAuth.php which had the following in the header comment

*

*Improved version of BasicAuth.

*Login/password retrieved from DB table

*Functionality of password recovery and new user registration is included.

and there was an lib/Auth directory containing the following php files
Form.php
PasswordRecovery.php
SignupProcessor.php
The Form.php seems to just create a login page the same as the one in BasicAuth and the passwordRecovery has logic to send an email / provide a link for the user with a timeout to reset their password.
I also need to build registration/forgot password functionality including emailing the user with a one time key to confirm the email address but not at that point yet so cant provide the code to do it.
My approach will be to copy BasicAuth to my webhome/lib directory, modify the login page that is created in BasicAuth to add links for forgot password and register ( I did wonder is there a reason why login is not a real page but is generated on the fly @romans ?). Then create a separte registration page containing an MVCForm of table "user" to store the details and create a couple of templates to send using atk4/lib/TMail.php.


text:
Q: Projects to undertake Using Lasers I need an economically feasible physics project that would use lasers in any manner preferably with respect to optics for a school projects class XII . Any suggestions are welcome no matter how crazy it sounds !

A: There are loads of things you can do with lasers. However, maybe this one might be of interest?

It's called "Laser Audio Interferometer" I tried this and it's simple.
  The mirror reflects the laser beam back down the bore of the HeNe
  laser tube, forming a second optical cavity external to the laser. Or
  use a laser pointer instead; I've been told that most will work. A
  small photovoltaic cell (solar cell or photodiode) collects some of
  the spill-light from the beam, and the PV cell output is sent to an
  audio amp and loudspeaker. If you move the wall (or the laser) a tiny
  bit, then as the "cavity" changes length, it sweeps across hundreds of
  resonant lengths located every 1/2 wavelength of the light. The light
  intensity sequentially grows dimmer and brighter, generating a
  sinewave signal. The frequency is proportional to the velocity of the
  wall. Connect the PV cell to the microphone input of an audio system,
  and when the wall is pushed, you hear moans and squeals.

Check out the site above for more ideas

A: What about a double-slit experiment? If your laser's spatial coherence is long enough, you should be able to place the screen far enough away to get a nice image.
Or go a step further and use a ballpen spring instead of a double slit, and reproduce the diffraction image of a helix (similar to what one sees with DNA)!


text: Q: Netbook w/ Fedora 17 and USB Numpad at Boot Disables Internal Keyboard I have a netbook with F17 installed.  No X, just text console. The system boots fine and the internal keyboard works.  I can plugin a USB numpad after boot and it functions reliably.  However, if the system is booted with the USB numpad attached the entire internal keyboard is frozen until the USB numpad's numlock key is pressed.  I've tried using usbreset and setleds to reset the numlock programatically - unsuccessfully.  The only thing that works is to press numlock on the USB numpad or unplugging and replugging.


text:
Q: Why my radio buttons are not taking if else statement in javascript file?     <input id="text1" placeholder="Enter Anything">
    <input id="rd1" name="grp1" type="radio" value="gurukul">Gurukul</input>
    <input id="rd2" name="grp1" type="radio" value="NEET">NEET</input>
     <br>
    <button onclick="fn1()"  id="btn1">Click Me</button>

Code for Js file is
function fn1()
    {
        var str = document.getElementById("text1").value;
        var rd1 = document.getElementById("rd1").value;
        var rd2 = document.getElementById("rd2").value;

        if(rd1.checked){
            alert("Value inside the text box is"+ str + "Welcome to"+rd1.value);
        }
        else if(rd2.checked){
            alert("Value inside the text box is"+ str + "Welcome to"+rd2.value);
        }
        else {
            alert("Value inside the text box is"+ str +  "No channel selected");
        }
    }

But any radio button i select , No channel selected option come out. Why is it so ?

A: If rd1 is an element.value, then it's a string and does not have a .checked property (it's undefined => false).
Remove .value from the assignment:

var rd1 = document.getElementById("rd1").value;

var rd1 = document.getElementById("rd1");

A: Change the if condition like this if(rd1.checked = true)


text:
Q: Is it possible to create an 'average' volume from an mp3 file using JavaScript? I have been unable to find any kind of library that is capable of creating an average volume of an mp3 file that supports JavaScript on a web client, not in NodeJS.
I need it on a web client as it is a part of a Chrome Extension.

A: There are a lot of libraries useful when working with sound. "Volume" is not a sound property, "Volume" is the term used for loudness in consumer electronics, sound has "Amplitude".
In digital sounds, it is far more useful to use RMS, that is the average of amplitudes in a sample.
What you want is an average of RMS in a span of time.
Take a look at libraries as p5.js or vanilla JS examples like this


text:
Q: Is there a way to make nested Visual States? Perhaps by inheriting from other visual states? I'm making a nested/hierarchical menu using Visual States as my way of navigating. This works very nicely when going left to right in the menu. If I click Main Menu 3, it turns blue and the attached Sub Menu pops up, same thing if I click Sub Menu 2. The problem now is if I click Main Menu 1, Sub Menu 2 and SubSubMenu4 will remain "selected" (read: blue), although they will be removed from the screen.

My idea here is that I want a better structure for my Visual States. I think I need the following:

*

*One Base State with everything unselected

Idea here being that whenever I hit a button, it will deselect everything, and remove all submenus. (Then repopulate if called by from an element further in).

*5 Main Menu States

These should ideally automagically inherit the base state so that I can't select them all at once, and only keep one sub menu open.

*5 * x Sub Menu States

For each Menu item, I need States for each of the Sub Menus within every Menu item, ideally these would go through the cycle again. Deselect everything, select the chosen Main Menu item then select the sub menu item, as well as open the respective subsubmenu.

*5 * x * x SubSub Menu States

You get the drift now, these should also deselect everything then reselected my previous choices.
So, has anyone a better idea how to solve this, as I am guessing this could potentially turn into a 100 States? Is there at least an easy way of making each Visual State inherit from its "parent"?
<TextBlock x:Name="MainMenu3" Text="MainMenu3" Foreground="Black">
  <i:Interaction.Triggers>
   <interactivity:RoutedEventTrigger RoutedEvent="interactivity:InteractionControl.TouchPress">
     <ei:GoToStateAction StateName="MainMenu3"/>
    </interactivity:RoutedEventTrigger>
   </i:Interaction.Triggers>
  </TextBlock>


text:
Q: 421 Misdirected Request using HTTP/2 and SAN SSL I'm running Apache 2.4.20 on Ubuntu and I have SSL configured. I have a SAN SSL Certificate and www.example.com and www2.example.com are sharing the same certificate.
I'm getting a 421 Misdirected Request error when I include the following:
Protocols h2 h2c http/1.1
H2Upgrade on
H2Direct
H2WindowSize 128000

Websites run normally if I remove them.
I'm getting the error if ON THE SAME BROWSER, www.example.com and www2.example.com are opened. If I go to www.example.com first then it will load properly. I get the error when I load a second site from that SAN SSL Certificate, like www2.example.com. It does not matter what site I go to first. It always responds with the 421 Misdirected Request on the second site.
What is wrong with my use of the HTTP/2 directives? (They are in the VirtualHost by the way)
Or is there an issue with HTTP/2 and SAN SSL implementations?
And if it matters, both www.example.com and www2.example.com are on the same server hosted in AWS.
Thanks.
EDIT:
I also tried the settings below with the same results.
Protocols h2 http/1.1
H2Direct
H2WindowSize 128000

In the SSL Config
<IfModule mod_ssl.c>

    SSLRandomSeed startup builtin
    SSLRandomSeed startup file:/dev/urandom 512
    SSLRandomSeed connect builtin
    SSLRandomSeed connect file:/dev/urandom 512

    AddType application/x-x509-ca-cert .crt
    AddType application/x-pkcs7-crl .crl

    SSLPassPhraseDialog  exec:/usr/share/apache2/ask-for-passphrase

    SSLSessionCache     shmcb:${APACHE_RUN_DIR}/ssl_scache(512000)
    SSLSessionCacheTimeout  300

    SSLOpenSSLConfCmd DHParameters "/path/dhparams.pem"

    SSLCipherSuite ECDHE-ECDSA-CHACHA20-POLY1305:ECDHE-RSA-CHACHA20-POLY1305:ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384:DHE-RSA-AES128-GCM-SHA256:DHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-AES128-SHA256:ECDHE-RSA-AES128-SHA256:ECDHE-ECDSA-AES128-SHA:ECDHE-RSA-AES256-SHA384:ECDHE-RSA-AES128-SHA:ECDHE-ECDSA-AES256-SHA384:ECDHE-ECDSA-AES256-SHA:ECDHE-RSA-AES256-SHA:DHE-RSA-AES128-SHA256:DHE-RSA-AES128-SHA:DHE-RSA-AES256-SHA256:DHE-RSA-AES256-SHA:ECDHE-ECDSA-DES-CBC3-SHA:ECDHE-RSA-DES-CBC3-SHA:EDH-RSA-DES-CBC3-SHA:AES128-GCM-SHA256:AES256-GCM-SHA384:AES128-SHA256:AES256-SHA256:AES128-SHA:AES256-SHA:DES-CBC3-SHA:!DSS

    SSLHonorCipherOrder on

    SSLCompression Off
    SSLSessionTickets Off

    SSLUseStapling On
    SSLStaplingResponderTimeout 5
    SSLStaplingReturnResponderErrors off
    SSLStaplingCache shmcb:${APACHE_RUN_DIR}/ssl_stapling(32768)

    SSLProtocol all -SSLv3

    SSLInsecureRenegotiation Off
    SSLStrictSNIVHostCheck Off

</IfModule>

In the VirtualHost
<IfModule mod_ssl.c>
  <VirtualHost *:443>
    ServerAdmin mail@example.com
    ServerName www.example.com
    DocumentRoot /path/path

    Protocols h2 http/1.1
    H2Direct on
    H2WindowSize 128000

    SSLEngine on
    SSLCACertificateFile /path/cert.crt
    SSLCertificateFile /path/cert.crt
    SSLCertificateKeyFile /path/key.key

    SSLProtocol all -SSLv3 -TLSv1 -TLSv1.1
    Header always set Strict-Transport-Security "max-age=15768000; includeSubDomains; preload"

    <Directory /path/path>
        AllowOverride None
        Require all granted
    </Directory>

 </VirtualHost>
</IfModule>

A: This was a real issue for me. But I found the answer here.
Multiple Hosts and Misdirected Requests

Many sites use the same TLS certificate for multiple virtual hosts. The certificate either has a
wildcard name, such as '*.example.org' or carries several alternate
names. Browsers using HTTP/2 will recognize that and reuse an already
opened connection for such hosts.
While this is great for performance, it comes at a price: such vhosts
need more care in their configuration. The problem is that you will
have multiple requests for multiple hosts on the same TLS connection.
And that makes renegotiation impossible, in face the HTTP/2 standard
forbids it.
So, if you have several virtual hosts using the same certificate and
want to use HTTP/2 for them, you need to make sure that all vhosts
have exactly the same SSL configuration. You need the same protocol,
ciphers and settings for client verification.
If you mix things, Apache httpd will detect it and return a special
response code, 421 Misdirected Request, to the client.

I have 3 VirtualHosts sharing the same certificate. Both of them are configured using my "default" SSL setup. The last one had special configuration since I did not need the last one to be compatible with a lot of browsers so I used more modern ciphers and only the latest SSL Protocol. That particular "special" VirtualHost was getting the 421.
If I disable Protocol h2 http/1.1 that would fix the problem but I did not want to disable that.
After using the same configuration on all VirtualHost sharing the same certificate, the problem was fixed.

A: I encountered this problem today and was a bit puzzled at first, because I didnt use any different ciphers etc. so I could not understand what the "if you mix things" note from the answer above was really all about. Well, it turned out, that it isnt sufficient if SSLCertificateFile and SSLCertificateKeyFile has the same content and if the files are even identical copies from each other. Those configuration settings have to point to the very same file! I suspect this is, because it isnt the browser who actually sees a problem (as I initially thought to be the case) but rather Apache is already detecting that the configuration isnt the same and blocks any HTTP2 requests pre-emptively because it expects the browser's gonna have a problem if it really delivered the page (which probably might very well happen indeed). Apache is also writing a corresponding error to its log file ("Hostname www.example.com provided via SNI and hostname www2.example.com provided via HTTP have no compatible SSL setup"). This setup compatibility test seems to be rather simple and doesnt care about the fact that the certificate is in fact the same. It probably only notices the different filenames/paths and then balks.


text:
Q: What is the difference between private cloud and public cloud? What are the differences between private cloud and public cloud ?
Please define both and giving examples with usage.

A: The same as the difference between an intranet and the internet. A private cloud is one set up for a specific group or organisation and usually isolated from the big bad world (behind firewalls and such).
A public cloud is, well, public, out on the internet proper.
For example, a certain big company I know does cloud computing but only using servers they control. It gives them the same benefits as public cloud computing but with more control and less security worries.
They also do public cloud computing but they wouldn't be comfortable to allow control or access to their more precious data to be at the whim of anyone else.

A: The answers above were fine for 2010, however standards have since emerged and NIST has come out with actual definitions of public and private clouds (see NIST Cloud Computing Definitions) NIST definitions are belowm, the italics are mine:

*

*Private cloud. The cloud infrastructure is provisioned for exclusive use by a single organization comprising multiple consumers
(e.g., business units). It may be owned, managed, and operated by the
organization, a third party, or some combination of them, and it may
exist on or off premises.  A private cloud may be provisioned any way an organization may like, with internal networks or a DMZ with some machines available to the public. Private clouds can resolve the noisy neighbor issues of public clouds - however depending on how the infrastructure is set up, you might end up becoming your own noisy neighbor.

*Public cloud. The cloud infrastructure is provisioned for open use by the general public. It may be owned, managed, and operated by
a business, academic, or government organization, or some combination
of them. It exists on the premises of the cloud provider. Quite possibly this is what everyone thinks of when they hear of Cloud, and make it almost synonymous with Amazon, although they are only 1 of the ever growing list of public cloud providers.

*Community cloud. The cloud infrastructure is provisioned for
exclusive use by a specific community of consumers from organizations
that have shared concerns (e.g., mission, security requirements,
policy, and compliance considerations). It may be owned, managed, and
operated by one or more of the organizations in the community, a
third party, or some combination of them, and it may exist on or off
premises. These are probably the next boom in clouds, but suffer a marketing problem. Recently I've seen them marketed as private clouds, but they share certain benefits, eg. HIPPA compliant clouds can be provisioned in a HIPPA compliant data center.

*Hybrid cloud. The cloud infrastructure is a composition of two or
more distinct cloud infrastructures (private, community, or public)
that remain unique entities, but are bound together by standardized
or proprietary technology that enables data and application
portability (e.g., cloud bursting for load balancing between clouds)

A: A public cloud is offered as a service via web applications/web services( usually over an Internet connection). Private cloud and internal cloud are deployed inside the firewall and managed by the user organization.
There is another type of cloud, hybrid cloud. A hybrid cloud environment consisting of multiple internal and/or external providers will be typical for most enterprises.

You will get more understanding here.

A: If you are talking about the IaaS ? (Infrastructure as a Service )
Public Cloud : Example : AWS,RackSpace,SkyTap and Many more
All of these provides computation,storage,networking as a Infrastructure with varied options and use cases, served for public with a standard fee. Somebody else home for Infrastructure, you rent it based on your need.
Private Cloud : Hardware Servers, Racks, Hypervisors,Router,Core Switch and Cloud Management Software.
All of the above provides you to manage the computation,storage,networking the way best fits to your need. Its all Private Its only you have built this Private Cloud for your own needs. Your own home the way you want, No rental.

A: Adding to the discussion, Public Clouds are built by organization for selling the computation as as service to the public where as Private Clouds are built for computation purposes of the organization itself(for their own need)
For example, Amazon EC2 or Rackspace DataCenters can be catagorized into Public Cloud systems and Google or Facebook DataCenters can be catagorized into Private Clouds, the difference being the purpose for which they are built

A: It all comes down to who has responsibility for the equipment.

In the public cloud, the organization has no local hardware to manage
or maintain. All the resources and services run on the cloud computing
provider's hardware.

A private cloud is an organization's on-premise datacenter that runs cloud
management software. This cloud management software can make your
on-premise datacenter like the public cloud but it's only for your
organization. The cloud management software apply virtualization to all your physical hardware and you can enable access to these virtual machines by internet


text:
Q: text binding through angularjs directive I need to get a string value into a directive's view, and while that should be straightforward, it's not working.
in the view calling the directive:
<hc-component-blocker animation="/images/spinner_black_16.gif"></hc-component-blocker>
the directive:
angular.module('xnuapp')
    .directive('hcComponentBlocker', function () {
        return {
            templateUrl: 'views/hccomponentblocker.html',
            priority: 1005,
            restrict: 'E',
            replace: true,
            scope: {
                animation: '@'
            },
            controller: 'ComponentBlockerCtrl',
            controllerAs: 'ComponentBlocker',
            bindToController: true
       };
});

directive's template:

ComponentBlockerCtrl:
angular.module('xnuapp')
    .controller('ComponentBlockerCtrl', function ($scope, HC_EVENTS) {
        console.log(this.animation);
});

I get the expected string value in the console when I run this ("/images/spinner_black_16.gif").
but the image doesn't display. What gets rendered in the HTML is

What should I look for? I thought this was the model for getting that string value for animation into the controller and view. Why doesn't the view get the value of that property passed to it?

A: this was fixed by changing replace to false. I'm not entirely sure why that worked, but it did.


text:
Q: How to order dates in descending order when there are multiple years in data set I have an Integromat app pulling weather data with date-time and adding them to my sheet and then I use that data to make some graphs.
The sheet in question can be found here. The weather data is the Data sheet
The issues are in GraphData!A18, GraphData!A31, and GraphData!A130. If I use
=SORT(QUERY(Data!A:D,"order by A desc limit 366"),1,1)
in GraphData!A130, it excludes data from the year 2022 as my date-time is in the format 12.31.2021 01:36. I can't change how Integromat outputs data. I tried to use Format>Number>Custom date and time but it didn't change anything. So, how do I go about changing the formula to also include 2022 data?

A: your dates are not valid dates but text strings. to convert them try:
=INDEX(QUERY({Data!A:D, SUBSTITUTE(Data!A:A, ".", "/")*1},
 "select Col1,Col2,Col3,Col4 order by Col5 desc", 1))


text:
Q: Twilio video JavaScript, calling track.disable() from Safari reloads the page I have developed a video calling feature using twilio video javascript, everything works fine but when user mutes the video from Safari browser on mac OS, the page reloads automatically showing an error This web page was reloaded because a problem occured.
Below is the function called when audio / video is muted/unmuted:
toggleMedia("video");
function toggleMedia(mediaType) {
            try {
                console.log("toggleMedia");
                if (!window.room) return;
                var localMedia = window.room.localParticipant;
                localMedia.tracks.forEach(function (publication) {
                    if (publication.kind === mediaType) {
                        if (publication.isTrackEnabled) {
                            publication.track.disable();
                        } else {
                            publication.track.enable();
                        }
                    }
                });
            } catch (e) {
                console.log(e);
            }
        }

I am trying to avoid publish, unpublish track approach. What is wrong with track.disable() on Safari?

A: Yesterday I also faced this problem! This error is already listed in the list of Common Issues.
The error only appears when using the H264 codec, so you can use the VP8 codec as a temporary solution:
import TwilioVideo from 'twilio-video';

await TwilioVideo.connect(token, {
  name,
  preferredVideoCodecs: [ 'VP8' ]
});

In my case, the code looks like this:
connect(authHelper.getUserVideoChatToken()?.token, {
        name:'testRoom',
        audio: true,
        video: { facingMode: { exact: (isUsingFrontCamera ? 'environment' : 'user') } },
        preferredVideoCodecs: ['VP8']
}).then(...)


text:
Q: PHP multidimensional array, each number as an array in an array I have a database with the following information:
    | ID | Name | Number |
    +----+------+--------+
    | 1  |  aaa |   1    |
    | 2  |  bbb |   1    |
    | 3  |  ccc |   2    |
    | 4  |  ddd |   2    |

and so on.....
What I want is to make an array like this:
    $array[1] = array ('aaa','bbb');
    $array[2] = array ('ccc','ddd');

And so on......
How do I achieve that, with a loop?
This is what I got so far:
while ($array = $query_res->fetch_assoc()) {
     $final_array[$array['Number']] = array ($array['Name']);
}
print_r($final_array);

This isn't working. I think I should use array_merge but can't figure out how to

A: What about:
while ($array = $query_res->fetch_assoc()) {
     $final_array[$array['Number']][] = $array['Name'];
}

A: If $array is really an array an contains the keys ID,Number and Name
   $final_array = array();
   while ($array = $query_res->fetch_assoc()) {
       $final_array[$array['Number']][] = array ($array['Name']);
   }

and then print_r ....

A: You need to check if an element with the key exists, if yes, push the new value into the array, if not create a new array:
while ($array = $query_res->fetch_assoc()) {
     if(isset($final_array[$array['Number']]){
         $final_array[$array['Number']][] = $array['Name'];
     }else{
         $final_array[$array['Number']] = array ($array['Name']);
     }
}
print_r($final_array);

A: Change your query to
SELECT `Number`, GROUP_CONCAT(DISTINCT(`Name`)) as `Name` FROM `table`

You will get a response like:
Number=1, Name=aaa,bbb
   Number=2, Name=ccc,ddd
Then do something like
while ($array = $query_res->fetch_assoc()) {
     $final_array[$array['Number']] = explode(',' $array['Name']);
}
print_r($final_array);


text:
Q: Can I say "I was born in a place but bred in another place" instead of using "born and bred" in pair? I am wondering If I tell people that I was born in Melbourne but bred in Sydney,  will the people think that I am married and have many children in Sydney?
Because when someone "breeds" then it implies that "they have babies", and then people mistakenly think that I have many babies. (But I am a student. I have no sex experience, I am not married either)
My original idea is to tell them that I grew up and received my education in Sydney since after I had moved from Melbourne to Sydney.
But, because I think it is cumbersome to say "I grew up and received my education in Sydney since after I had moved from Melbourne to Sydney", I want to use a few words which will help me express the same idea, but my English is not good enough, so I could only come up with this sentence:
"I was born in Melbourne but bred in Sydney"

A: I agree with the other commenters that it's a set expression.  The point of the phrase is that you are completely and thoroughly of a certain place.  If you split it up, people will recognize what you mean, but it's not normally done.  They may think you're trying to be funny.
Also, bred in this sense is being used as the past participle; you're saying you were bred (by your parents), not that you bred children of your own, so no one is likely to think you are saying you have kids.

A: If the original poster wants to say that her ancestors lived in Sydney, or that she was conceived in Sydney, she should not say she was "bred in Sydney".
Unless you are using the phrase "born and bred" as a stock phrase,saying that she was "bred in Sydney" is a very coarse way of saying that she had sex in Sydney, and someone hoped that sex would result in her giving birth about nine months later.

A:
I was born in Melbourne but bred in Sydney

No. "Born and bred" is a set phrase, and when used separately its meaning changes. As a standalone word, "bred" is more suitable for use in regards to cattle or other animals. "Born and bred" is tied together so tightly that you can use it as an attributive adjective:

She was a born and bred Melbourner.

What to pick instead?
If by "education" you mean your basic education, including that given by your mother, father or other caregiver, you might say

I was born in Melbourne but brought up in Sydney.
  I was born in Melbourne but raised in Sydney.

You can also try

I was born in Melbourne but grew up in Sydney. (Thank you, Kevin, for your comment!)

Instead of "received my education", you can pick shorter versions, such as "(was) educated, tutored" or "graduated", or "went to school/college/university":

I was born in Melbourne but educated in Sydney.
  I was born in Melbourne but went to school in Sydney.

P.S. "Born and bred" does remind me of the so-called "legal doublets", but in such combinations the meanings of the words are synonymous, and one of the words usually derives from Latin. I'm not sure that that is the case with "born and bred".
According to Wiktionary, one of the meanigns of breed, most likely an archaic one, is "to take care of in infancy and through childhood; to bring up". Judging by the quotations used for this sense, it must be archaic:

"Ah, wretched me! by fates averse decreed
   To bring thee forth with pain, with care to breed"
  (by Dryden, a poet who lived in the 17 century)

It's probably due to this "human-related" sense fading away and only the "animal-related" sense retained that we cannot separate born from bred.

A: Yes. Birth is an event but breeding is a process. They do not have to be conjoined. The phrase "born and bred" implies a history and a connection to an area but to say one was born here and bred there would be more along the lines of conveying factual information. The two would be said with different intentions, in different circumstances and would convey different meanings.

A: "Born and bred" is one of the many English phrases formed from pairs of words that are almost complete synonyms:

safe and sound
  aid and abet
  meek and mild
  far and wide
  null and void
  flotsam and jetsam

These are set phrases or even idioms - "aid and abet" doesn't mean you helped someone twice, but that you assisted someone in a probably-criminal enterprise. In many cases, they also use words that are otherwise obsolete (does anyone ever use "jetsam" on its own?), or use meanings of words that are obsolete/rarely used (e.g. the "sound" in "safe and sound" or the "mild" in "meek and mild"). What all this boils down to is that in most cases, you can't really separate the pairs of words.
In the specific case of "born and bred", "bred" on its own sounds like something you do with dogs or horses, so "...but bred in Sydney" just sounds... wrong. I would use a different word there, perhaps "raised" or "grew up":

I was born in Melbourne, but raised in Sydney.
  I was born in Melbourne, but [my family moved when I was very young, so] I grew up in Sydney.


text:
Q: Play framework and ionic for mobile I need Security without cookies but token I have an issue with using mobile app that I created in Ionic and back-end APIs that I coded in play framework, my issue simply is I need way to handle security matter for calling APIs that need to be secured, mean user must be logged in to do actions, as example guest can view group but can join only if logged in.
My issue that I believe that cookies is not supported for Mobile, i have code checking session that stored in cookies, its working for website, but it will not work for mobile, right?
Currently I'm trying to send a token that generated in back-end and returned with login response and stored in localStorage in Ionic, but my issue is that I can't sent token to be validated with request.
Front End:
I have the following http interceptor :
  angular
    .module('app.core')
    .factory('sessionInjector', sessionInjector);

  /** @ngInject */
  function sessionInjector($q, sessionService, $rootScope) {
    return {
      request: function (config) {
        $rootScope.$broadcast('loading:show');
        if (!sessionService.isAnonymous())
          config.headers['x-session-token'] = sessionService.getToken();
        }
        return config;
      }
  }

Back-End:
Controller:
    @Security.Authenticated(Secure.class)
    public Result joinOrganization() {

       // Do some business

    }

Secure.java :
@Override
public String getUsername(Http.Context ctx) {
    // Is this correct way? I get null here
    String str = ctx.request().getHeader("x-session-token");

    String userId = ctx.session().get("usedId");

    if (userId == null) {
        return null;
    }

    User user = Play.application().injector().instanceOf(UserService.class).findUserById(Integer.parseInt(userId));

    if (user != null && user.isActive) {
        return user.id;
    } else {
        return null;
    }
}

@Override
public Result onUnauthorized(Http.Context ctx) {
    return unauthorized(results);
}

Note: Tokens stored in database:
Entity:
@Entity
@Table(name = "AUTHTOKEN")
public class AuthToken extends BaseModel {

    @OneToOne(targetEntity = User.class, cascade = CascadeType.REFRESH, optional = false)
    public User user;

    @Column(nullable = false)
    public String token;

    @Column
    public long expiration;

    public AuthToken() {
    }

}

For cookies working, but need to remove cookies and use tokens, or use them together cookies for website, tokens for mobile .

A: Mobile is no different to otherwise in regards of cookies. There are restrictions if AJAX, or cross-domain requests are used, and specially with Apple stuff, but they apply to non-mobile too. If your cookies work on a PC/Mac, they should do on a mobile device just as well. It's more of a form factor than anything else...

A: I found solution and it was complicated because there are many issues starting from that ngResource does not apply request interceptor its an issue opened from long time.
Second issue was how to send the token with ngResource, its simply with adding headers, the another issue here is getting dynamically the token, this "dynamically" means because the localStorage in memory getting lost when refresh so you need to get back it, this can be done with service, and function call for getting the token, something like this :
$resource('/user/:userId/card/:cardId', {userId:123, cardId:'@id'}, {
  charge: {method:'POST', params:{charge:true}, headers = {
        'x-session-token': function () {
          return sessionService.getToken()
        }}
 });

Inside sessionService :
// this to recreate the cache in memory once the user refresh, it will keep the data if exisit but will point to it again in memory
if (CacheFactory.get('profileCache') == undefined) {
  //if there is no cache already then create new one and assign it to profileCache
  CacheFactory.createCache('profileCache');
}

function getCurrentSession() {
  var profileCache = CacheFactory.get('profileCache');
  if (profileCache !== undefined && profileCache.get('Token') !== undefined) {
    return profileCache.get('Token');
  }
  return null;
}

function getToken() {
  var currentSession = getCurrentSession();
  if (currentSession != null && currentSession != '') {
    return currentSession.token;
  }
  return null;
}

And then this method will work inside Secure.java
protected User getUser(Http.Context ctx) {
    String token = ctx.request().getHeader("x-session-token");

    if (token != null) {
        return securityService.validateToken(token);
    }
    return null;
}


text:
Q: What kind of connection is the directional derivative? Given a scalar function $f(X)$ as a function of coordinates I can write it's directional derivative in direction $\hat{u}$ as:
$$ D_{\hat{u} } f = \nabla f \cdot \hat{u}$$
This is pretty easy to think about and understand. I recently learned about the concept of connections which is supposed to 'abstract' the idea of directional derivatives from $(0,0)$ tensor fields (scalar fields to a general $(p,q)$ tensor field. Here's the definition I learned:

A connection $\nabla$ on a smooth manifold $(M,\theta,A)$ is a map that takes a pair consisting of a vector field and a $(p,q)$ tensor field $T $and sends that to a $(p,q)$ tensor field $\nabla_x T$ From 20:15

From what I understand, there are actually many possible connections which we could define but the Levi civita connection with the torsion free and metric compatibility is the often used.
In the abstract case , I learned we have to put more constraints to specify how to take a connection then this would mean we would have taken those same assumption in taking the directional derivatives. My question is what is the connection we take to get the directioncal derivative? [Eg: Is it levi civita, or boring connection or something else?]
[I got that the connection is determined by the further constraints in at 16:35 ]

A: $\newcommand{\R}{\mathbb{R}}$ The directional derivative of a function is well-defined on a manifold without any additional assumptions. In particular, given a smooth function $f: M \rightarrow \R$, $p \in M$, and tangent vector $v \in T_pM$, we can define the directional derivative to be
$$ D_vf(p)= \left.\frac{d}{dt}\right|_{t=0}f(c(t)) = \lim_{t\rightarrow 0}\frac{f(c(t))-f(c(0))}{t},$$
where $c$ is a smooth parameterized curve such that $c(0) = p$ and $c'(0) = v$.
It is straightforward, using local coordinates and the chain rule, to show that this is well-defined, independent of the curve $c$ and the local coordinates.
If we tryto define the directional derivative of a vector field $X$ the same way, we get something like
$$ D_vX(p)= \left.\frac{d}{dt}\right|_{t=0}X(c(t)) = \lim_{t\rightarrow 0}\frac{X(c(t))-X(c(0))}{t}.$$
This, however, doesn't work, because $X(c(t)) \in T_{c(t)}M$ and $X(c(0)) \in T_{c(0)}M$ lie in different vector spaces, so it is not possible to subtract one from the other. You have to "transport" one of them to be in the same tangent space as the other. The process of doing this is a long story. In short, there is not a unique way to do it, and involves setting up a so-called connection on the tangent bundle of the manifold.


text:
Q: Output in stdout differs in cmd and Python console I'm new to Python and working on a little program that copies all files of given extension from a folder and it's subfolders to an another directory. Recently I added a simple progress bar and a counter of remaining files.
The problem is that when I run it from cmd and counter comes from say 1000 to 999 cmd adds a zero in the place of a last digit instead of space. Moreover, when the program is finished remaining files counter should be substituted by the word "Done." and it also doesn't work well.
I tried to replace sys.stdout.write with print and tried not to use f-strings, the result is the same.
def show_progress_bar(total, counter=0, length=80):
    percent = round(100 * (counter / total))
    filled_length = int(length * counter // total)
    bar = '=' * filled_length + '-' * (length - filled_length)
    if counter < total:
        suffix = f'Files left: {total - counter}'
    else:
        suffix = 'Done.'
    sys.stdout.write(f'\rProgress: |{bar}| {percent}% {suffix}')
    sys.stdout.flush()

def selective_copy(source, destination, extension):
    global counter
    show_progress_bar(total)
    for foldername, subfolders, filenames in os.walk(source):
        for filename in filenames:
            if filename.endswith(extension):
                if not os.path.exists(os.path.join(destination, filename)):
                    shutil.copy(os.path.join(foldername, filename), os.path.join(destination, filename))
                else:
                    new_filename = f'{os.path.basename(foldername)}_{filename}'
                    shutil.copy(os.path.join(foldername, filename), os.path.join(destination, new_filename))
                counter += 1
                show_progress_bar(total, counter)

I expected that the output in cmd will be the same as in the console, which is this:
Program running:
Progress: |=========-----------------------------------------------------------------------| 12% Files left: 976

Program finished:
Progress: |================================================================================| 100% Done.

But in the cmd I got this:
Program running:
Progress: |=========-----------------------------------------------------------------------| 12% Files left: 9760

Program finished:
Progress: |================================================================================| 100% Done. left: 100

A: Typically, printing "\r" will return the cursor to the beginning of the line, but it won't erase anything already written. So if you write "1000" followed by "\r" followed by "999", the last 0 of "1000" will still be visible.
(I'm not sure why this isn't happening in your Python console. Maybe it interprets "\r" in a different way. Hard to say without knowing exactly what software you're running.)
One solution is to print a couple of spaces after your output to ensure that slightly longer old messages get overwritten. You can probably get away with just one space for your "Files left:" suffix, since that only decreases by one character at most, but the "done" suffix will need more.
if counter < total:
    suffix = f'Files left: {total - counter} '
else:
    suffix = 'Done.               '


text:
Q: Access Global Variables Within Fragments I just created an app that's using a lot of fragments to work with. I created Viewpager with more than 10 fragments in it. Now what I wanna try is set the variables from a fragment so it can be accessed on another fragment.
What have I tried so far. I create global variable to store the value
public class DataSite extends Application {

private String someVar;

public String getSomeVar(){
    return someVar;
}

public void setSomeVar(String someVar){
    this.someVar = someVar;
}

}
In fragment A. I set the value like below
((DataSite) getActivity().getApplicationContext()).setSomeVar("Tes");

And from other fragment I tried to get the value like this
((DataSite)getActivity().getApplication()).getSomeVar();

But as soon as I click the button in fragment A, which the app is trying to set var to global class....The app suddenly crashed and no error logcat showed in Android Studio.
Maybe anyone can explain why this happen

A: you need to add your customise application class in manifest as
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
          package="com.some.somemore">

    <application
        android:name=".DataSite"
      ....> </application>

A: ((DataSite)getActivity().getApplication()).getSomeVar(); //this is correct
((DataSite) getActivity().getApplicationContext()).setSomeVar("Tes"); //this is wrong
.getApplication() is correct way


text:
Q: Convert from binary to XML serialization without needing the type I have a project with a few types that I binary-serialize (BinaryFormatter) to files. I'd now like to create a second project which allows admins to temporarily decode those files into a more readable XML format (e.g., using XmlSerializer).
I could deserialize them into an object of the original type, then reserialize them, but is it at all possible to

*

*skip the deserialization (at least in my own code), and

*better yet, not have to reference the type at all in my decoder tool?

A: If you are referring to .NET's native binary serialization (BinaryFormatter), the problem is that it saves your object (along with all the necessary metadata for deserialization) using an undocumented format (AFAIK).
If you really want to try doing it without deserialization, you can check this article, which appears to have analyzed its format (but the author himself states that it might be incomplete). But my opinion is that it's far too much trouble.

A: There's no way that you can deserialize to your type without specifying that type, at least with standard XML serialization, however, as long as the object was serialized using xml, you could use one of many XML reader classes to traverse the object without needing to deserialize it.  Alternatively, if you happen to be serializing to JSON, there are some libraries out there that will deserialize to anonymous types that you can use.
If the type of conversion you are looking for is purely cosmetic (e.g. to make it more human readable), you could write some RegEx to replace the element tags.


text:
Q: Python: Msgpack-Numpy cannot handle my data? I am trying to use msgpack and msgpack-numpy to serialize some data. My code is as follows:
import msgpack
import msgpack_numpy
msgpack_numpy.patch()
print(products[0]['data']['AMAZON_time'])

def decode_datetime(obj):
    if b'__datetime__' in obj:
        obj = datetime.datetime.strptime(obj[b'as_str'].decode(), "%Y%m%dT%H:%M:%S.%f")
    return obj

def encode_datetime(obj):
    if isinstance(obj, datetime.datetime):
        obj = {'__datetime__': True, 'as_str':obj.strftime("%Y%m%dT%H:%M:%S.%f").encode()}
    return obj

with open('bookData.msgpack','wb') as outfile:
    msgpack.pack(products[0]['data']['AMAZON_time'],outfile,default=encode_datetime)

with open('bookData.msgpack','rb') as infile:
    data = msgpack.unpack(infile,object_hook=decode_datetime)

This throws the following error:
  ValueError: cannot create an OBJECT array from memory buffer

When printed, the object I am trying to store looks as follows:
[datetime.datetime(2017, 3, 23, 12, 44) datetime.datetime(2018, 6, 8, 6, 0)
 datetime.datetime(2018, 6, 8, 8, 28) datetime.datetime(2018, 6, 8, 10, 8)
 datetime.datetime(2018, 6, 8, 14, 56) datetime.datetime(2018, 6, 8, 21, 8)
 datetime.datetime(2018, 6, 8, 21, 56)
 datetime.datetime(2018, 6, 8, 23, 44) datetime.datetime(2018, 6, 9, 0, 36)]

However, if I print products[0]['data'] I get sth containing the words dtype=Object (not sure if this is relevant, but I thought I'd mention it given the phrasing of the error).
Any idea what I am doing wrong?
EDIT: I don't know whether it is relevant, but I can save and load the same data with pickle.

A: I have solved this issue by hand-coding a translation function that saves a timestamp (as an integer) instead of a numpy array of datetime objects. I believe MSGPACK (even with the MSGPACK-NUMPY addition) is just not able to handle arrays of datetime objects, even with hand-coded decoders and encoders for datetime objects (the problem is with the numpy array of object types, not really with the datetime objects).


text:
Q: Firebase 3 - javascript - get facebook accessToken after login In Firebase 2 I was able to get facebook accessToken from anywhere after login by this way, just using the firebase reference, eg:
firebase.getAuth().facebook.accessToken

Now, how can I get that in version 3 (web)?
Note, I need it outside of the Promise signInWithPopup
Thanks

A: I just found this on documentation... Why? :(

Since Firebase Authentication no longer persists the access token,
  your application will have to do so itself, if needed.

A: Try this:
firebase.auth().signInWithPopup(provider).then(function(result) {

    // This gives you a Facebook Access Token. You can use it to access the Facebook API.
    var token = result.credential.accessToken;
})

A: Possible answer is to unlink "auth.currentUser.unlink(provider)" the provider and re link "auth.currentUser.linkWithPopup(provider)" each time you need to get the access token.

A: The easiest way to get the user access token is to use the FB API itself.
Simply follow this guide on how to include it and then get the token the following way:
FB.getLoginStatus(function(response) {
  if (response.status === 'connected') {
    var accessToken = response.authResponse.accessToken;
  }
} );


text:
Q: Removing special character from dataframe In the data frame as below, I find special characters ''(,) inside it
when given df.head()
| SYSTEM_NAME | IP_ADDRESS      |
|-------------|-----------------|
| AAAA        | (xx.xx.xx.xx,) |

when viewed as dataframe inside IDE (pycharm)
| SYSTEM_NAME | IP_ADDRESS         |
|-------------|--------------------|
| AAAA        | ('xx.xx.xx.xx',)  |

My trials
df['IP_ADDRESS'] = df['IP_ADDRESS'].str[:-2]
this makes the column value '0'

df['IP_ADDRESS'] = df['IP_ADDRESS'].str.replace(r"\(.*\)","")
this makes the column value 'nan'

I tried some other methods also to remove the special char
Required Output
| SYSTEM_NAME | IP_ADDRESS   |
|-------------|--------------|
| AAAA        | xx.xx.xx.xx |

A: That looks like a tuple to me, so give .str[0] a shot:
df['IP_ADDRESS'] = df['IP_ADDRESS'].str[0]


text:
Q: MTM - Error saving the test run :There is not enough space on the disk When I start to run the automated test case in Test Agent through Test Manager, Run Log shows below error. Test Agent has the enough memory space on the disk. What could be the issue? Please help.

A: Actually test controller was runs out of space because of the files being stored in localappdata%\VSEQT\QTController\TestRunStorage which never get deleted. So to resolve the issue, we have to remove the all files from TestRunStorage folder or turn off job spooling in QTController.exe.config file. Please refer following reference links for more details.
Reference Links:
http://www.anujchaudhary.com/2011/06/tfs-2010-test-controller-disk-runs-out.html
https://blogs.msdn.microsoft.com/shivash/2011/01/20/using-visual-studio-test-controller-with-mtm-and-disk-out-of-space-issues/