text:
Q: Password-less SSH not working with Mac OS X 10.9.5 Mavericks I cannot get password-less logins working on my Mac OS X 10.9.5 Mavericks machine. I can login to a remote Ubuntu box after setting up the authorized_keys file properly. However, I cannot do there reverse.
So I tried to troubleshoot the Mac setup by figuring out if I can do this without a password:
ssh localhost

Doing that on my Ubuntu box works well, but the Mac keeps asking for passwords. Yes I checked the authorized_keys file as well as the known_hosts file and made sure the id_rsa.pub key was present in both of them for my Mac. But I cannot SSH to localhost without a password.
I read the other posts such as this one.
And even enabled the following two settings(by deleting the hashtag in front of them) in the sshd_config file:
RSAAuthentication yes
PubKeyAuthentication yes

Still getting asked for the password.
Put copies of the authorized_key and known_hosts files in the etc directory.
Still getting asked for the password.

A: I provided an answer on Stack Overflow that explains the step-by-step process needed to set up password-less access via SSH. Here are those instructions adapted for your specific needs.
First, set the SSH connection into verbose mode by using the -v flag like this:
ssh -v localhost

As explained in the ssh man page; accessible via man ssh:
 -v      Verbose mode.  Causes ssh to print debugging messages about its
         progress.  This is helpful in debugging connection, authentica-
         tion, and configuration problems.  Multiple -v options increase
         the verbosity.  The maximum is 3.

This has saved me a lot of headaches in the past by showing me exactly how the login process is flowing & what exactly is clogging it up. For example, here is the output of me running that command on my local Mac OS X 10.9.5 machine:
ssh -v localhost

OpenSSH_6.2p2, OSSLShim 0.9.8r 8 Dec 2011
debug1: Reading configuration data /etc/ssh_config
debug1: /etc/ssh_config line 20: Applying options for *
debug1: /etc/ssh_config line 53: Applying options for *
debug1: Connecting to localhost [::1] port 22.
debug1: Connection established.
debug1: identity file /Users/Giacomo1968/.ssh/id_rsa type 1
debug1: identity file /Users/Giacomo1968/.ssh/id_rsa-cert type -1
debug1: identity file /Users/Giacomo1968/.ssh/id_dsa type -1
debug1: identity file /Users/Giacomo1968/.ssh/id_dsa-cert type -1
debug1: Enabling compatibility mode for protocol 2.0
debug1: Local version string SSH-2.0-OpenSSH_6.2
debug1: Remote protocol version 2.0, remote software version OpenSSH_6.2
debug1: match: OpenSSH_6.2 pat OpenSSH*
debug1: SSH2_MSG_KEXINIT sent
debug1: SSH2_MSG_KEXINIT received
debug1: kex: server->client aes128-ctr hmac-md5-etm@openssh.com none
debug1: kex: client->server aes128-ctr hmac-md5-etm@openssh.com none
debug1: SSH2_MSG_KEX_DH_GEX_REQUEST(1024<1024<8192) sent
debug1: expecting SSH2_MSG_KEX_DH_GEX_GROUP
debug1: SSH2_MSG_KEX_DH_GEX_INIT sent
debug1: expecting SSH2_MSG_KEX_DH_GEX_REPLY
debug1: Server host key: RSA 01:aa:8e:8e:b9:e1:4b:e8:bd:c5:a2:20:a3:c7:f1:18
debug1: Host 'localhost' is known and matches the RSA host key.
debug1: Found key in /Users/Giacomo1968/.ssh/known_hosts:43
debug1: ssh_rsa_verify: signature correct
debug1: SSH2_MSG_NEWKEYS sent
debug1: expecting SSH2_MSG_NEWKEYS
debug1: SSH2_MSG_NEWKEYS received
debug1: Roaming not allowed by server
debug1: SSH2_MSG_SERVICE_REQUEST sent
debug1: SSH2_MSG_SERVICE_ACCEPT received
debug1: Authentications that can continue: publickey,keyboard-interactive
debug1: Next authentication method: publickey
debug1: Offering RSA public key: /Users/Giacomo1968/.ssh/id_rsa
debug1: Authentications that can continue: publickey,keyboard-interactive
debug1: Trying private key: /Users/Giacomo1968/.ssh/id_dsa
debug1: Next authentication method: keyboard-interactive
Password:

As you can see, it gets up the password prompt. But prior to that it is clearly checking for my RSA public key. And since I don't have one, it just rolls over to the next authentication method. Pay attention to the output of ssh -v when you run it on your set to see where things get choked.
Also be sure the SSH files on the destination machine have permissions that match the following & are owned by the account trying to access like this example shows:
-rw------- [username] [usergroup] authorized_keys
-rw------- [username] [usergroup] id_rsa
-rw-r--r-- [username] [usergroup] id_rsa.pub
-rw-r--r-- [username] [usergroup] known_hosts

So run this command to chmod the authorized_keys file:
sudo chmod 600 ~/.ssh/authorized_keys

And run this command to chmod the id_rsa file:
sudo chmod 600 ~/.ssh/id_rsa

A: I found the problem. The remote host logs the origin of each RSA or DSA key. This is seen in plain text at the end of each line in the authorized keys list (which you usually cannot see because nano does not text wrap).
I was ssh'ing first to the remote host, then copying the key and merging it with authorized_keys. Bad.
From the client machine,the key has to be copied to the remote host with that special copy command, scp, or ssh-copy-id (OS X does not have this one unless installed with brew or port).
Then the merge to authorized_keys can be performed. Careless human error on my part.

A: For me, I had a secondary key to connect to a host.
In order to connect using that, you need to add that to identity using:
ssh-add yourPrivateKey

A: I was at my wits end... I was under the mistaken impression ssh-copy-id was a Linux-only utility. Finally I just swallowed my pride and typed the command is the macOS Terminal and it worked!
ssh-copy-id me@sshd-server

I don't know what magic ssh-copy-id does, but it just worked. I was able to log in without a password successfully with the simple command:
ssh me@sshd-server

I had zero luck with cat id_rsa.pub >> ~/.ssh/authorized_hosts. Every time I tried ssh'ing to the server it just kept asking me for the passphrase. This is with the correct 600 permission on authorized_hosts and 700 on ~/.ssh.


text:
Q: Javascript - getPropertyValue gives wrong height

let a = document.getElementsByClassName("d1");
let b = window.getComputedStyle(a[0]);
let c = b.getPropertyValue("height");
alert(c);
.d1 {
  background-color: red;
  padding: 20px;
}

Test test test

The above code alerts 18px but the height of the div element is actually 48px. It looks like that it doesn't take in consideration its padding. How can I alert its real height?

A: The CSS height property does not include padding. Try using .clientHeight instead, which does include padding. Here's from the docs:

clientHeight can be calculated as: CSS height + CSS padding - height of horizontal scrollbar (if present).

let a = document.getElementsByClassName("d1");
let c = a[0].clientHeight;
alert(c);
.d1 {
  background-color: red;
  padding: 20px;
}

Test test test

redpajama_set_name: RedPajamaStackExchange


text:
Q: Save Markdown as interactive HTML Is it possible to convert this interactive markdown report into an html and save it to as specific folder (the goal is to to keep this report alive outside R)? If yes, how?
---
runtime: shiny
output: html_document
---

```{r echo=FALSE}
N<-c('A','B','C'); V<-c(60,50,80); mydf<-data.frame(N,V)
selectInput("sel","Select:",choices = as.character(mydf$N))
renderText({
     paste("The result is:",mydf[mydf$N==input$sel,2])
})
```

Thanks&kind regards

A: From the settings in Rstudio (next to run document), choose Preview in Viewer Panel.  This will use your browser instead of the built-in browser of Rstudio.
Then you will see that the html file is saved on your hard disk:
processing file: testing_interactive.Rmd

"C:/Program Files/RStudio/bin/pandoc/pandoc" +RTS -K512m -RTS "C:/Users/TB/AppData/Local/Temp/RtmpKYheKO/testing_interactive.utf8.md" --to html --from markdown+autolink_bare_uris+ascii_identifiers+tex_math_single_backslash --output pandoc83c74213d5c.html --smart --email-obfuscation none --standalone --section-divs --template "C:\Rlibs\rmarkdown\rmd\h\default.html" --no-highlight --variable highlightjs=1 --variable "theme:bootstrap" --mathjax --variable "mathjax-url:https://cdn.mathjax.org/mathjax/latest/MathJax.js?config=TeX-AMS-MML_HTMLorMML" --id-prefix section-
output file: C:/Users/TB/AppData/Local/Temp/RtmpKYheKO/testing_interactive.knit.md

Output created: C:/Users/TB/AppData/Local/Temp/RtmpKYheKO/file83c15d05b9c.html


text:
Q: Getting Users name from federated login I am using the federated login on Google App Engine for letting users log in.
Using the information about the federated login;
 https://developers.google.com/appengine/articles/openid
and the reference on the user object;
https://developers.google.com/appengine/docs/python/users/
I can get users to log in and authenticate them. I can get their email addresses and nickname.
The only problem is that I don't know how to get their actual names.
When I log in using this service the user name is provided, and stackoverflow gets the users name from the openid login (at least using Google and Yahoo).

A: It should depend on the OpenID provider, and what they return as the OpenID identifier. What OpenID provider are you using?
In regards to User.nickname():

Returns the "nickname" of the user, a displayable name. For Google Accounts users, the nickname is either the "name" portion of the user's email address if the address is in the same domain as the application, or the user's full email address otherwise. For OpenID users, the nickname is the OpenID identifier.

So by default, it's just whatever their OpenID identifier is. Whether or not you can retrieve the username they have with their OpenID provider (if it's not the identifier) likely just depends on the provider.


text:
Q: System.MissingMethodException: Cannot create an abstract class ExtendedCommandManager.cs
var assembly = AppDomain.CurrentDomain.GetAssemblies();
var types = assembly.SelectMany(s => s.GetTypes()).Where(p => typeof(ICommand).IsAssignableFrom(p));
foreach (var type in types)
{
   source.Commands.Add((ICommand) Activator.CreateInstance(type));
}

return source;

type inherited ICcommand But why is there an error?
Error
Unhandled exception. System.MissingMethodException: Cannot create an abstract class.
   at System.RuntimeTypeHandle.CreateInstance(RuntimeType type, Boolean publicOnly, Boolean wrapExceptions, Boolean& canBeCached, RuntimeMethodHandleInternal& ctor, Boolean& hasNoDefaultCtor)
   at System.RuntimeType.CreateInstanceDefaultCtorSlow(Boolean publicOnly, Boolean wrapExceptions, Boolean fillCache)
   at System.RuntimeType.CreateInstanceDefaultCtor(Boolean publicOnly, Boolean skipCheckThis, Boolean fillCache, Boolean wrapExceptions)
   at System.Activator.CreateInstance(Type type, Boolean nonPublic, Boolean wrapExceptions)
   at System.Activator.CreateInstance(Type type)
   at BASE.CommandControllers.ExtendedCommandManager.Load[T](T source) in D:\CLang\DicordProject\Discord\BASE\CommandControllers\ExtendedCommandManager.cs:line 16

A:
But why is there an error?

Because you're trying to create an instance of an abstract class (rather than a concrete class derived from that abstract class). You can't do that with reflection, just like you can't do it with regular code. If you were to try writing code of var command = new FooCommand(); (where FooComand is the type that it's failing on) that code would fail to compile.
Your code for checking which types to instantiate should include !p.IsAbstract to filter out abstract classes that implement ICommand.

A: The error tells you exactly what is wrong. You can't create an instance of an abstract class.
You need to filter your types so that they don't include abstract types. like this:
var types = assembly.SelectMany(s => s.GetTypes()).Where(p => !p.IsAbstract && typeof(ICommand).IsAssignableFrom(p));

A: You cannot create a instance of both abstract class and interface. Because it does not contain complete implementation.
So, first implement it.

A: See this Microsoft Doc For Reference
Like most abstract class implementation in most languages, you can't create an object of that specifically. It's used as a building block, typically for common code shared amongst other classes.
The Execption is correct. When you loaded your classes / objects by reflection using the interface as it's identifier, one of the classes that implemented that interface is abstract and can't be instanciated with Activator.CreateInstance, but your code doesn't know that until runtime as it can do type checking on stuff created dynamically at runtime.


text:
Q: Masking part of event data in socketio room Im working on a socket server built on socketio. My setup uses rooms in which all clients can perform actions that update a central state. The central state hold the data of all clients, i.e.
const state = [
   { "id": 1, "name": "John", "secret": "foo" },
   { "id": 2, "name": "Jane", "secret": "bar" }
]

When a user updates the state, the socket will then broadcast the updated state to all connected clients. I.e.
socket.to(room).broadcast("update", state)

My goal is to mask certain values of the state, i.e. the secret values, per response per client. For client with id 1 I would ideally want to mask the secret value of client with id 1 and vice versa.
Is there a way to achieve this with socket.io? And if so, how could I achieve this? I have tried to find an answer but was unable to find any relevant information or documentation.


text:
Q: Cant use --pipe for redis bulk insert I am using Redis for storing large sets of data.   I am trying to use the bulk insert as described in the official documentation.  However, when I run the command,
cat data.txt | redis-cli --pipe

Redis tells me that command --pipe has not been found.   I am using version 2.4.13.
Can anyone tell me what Im doing wrong?
Thanks in advance
Dan

A: Pipe mode has been introduced with redis 2.4.14.
Try to upgrade your version of Redis.
Changelog for Redis 2.4:
https://raw.github.com/antirez/redis/2.4/00-RELEASENOTES
Changelog for Redis 2.6:
https://raw.github.com/antirez/redis/2.6/00-RELEASENOTES
Be sure to read http://redis.io/topics/mass-insert before using this feature.


text:
Q: Getting java.lang.IllegalArgumentException: requirement failed while calling Sparks MLLIB StreamingKMeans from java application I am new to Spark and MLlib and I'm trying to call StreamingKMeans from my java application and I get an exception that I don't seem to understand. Here is my code for transforming my training data:
JavaDStream<Vector> trainingData = sjsc.textFileStream("/training")
            .map(new Function<String, Vector>() {
                public DenseVector call(String line) throws Exception {
                    String[] lineSplit = line.split(",");

                    double[] doubleValues = new double[lineSplit.length];
                    for (int i = 0; i < lineSplit.length; i++) {
                        doubleValues[i] = Double.parseDouble(lineSplit[i] != null ? !""
                                .equals(lineSplit[i]) ? lineSplit[i] : "0" : "0");
                    }
                    DenseVector denseV = new DenseVector(doubleValues);
                    if (denseV.size() != 16) {
                        throw new Exception("All vectors are not the same size!");
                    }
                    System.out.println("Vector length is:" + denseV.size());
                    return denseV;
                }
            });

Here the code where I call the trainOn method:
int numDimensions = 18;
int numClusters = 2;
StreamingKMeans model = new StreamingKMeans();
model.setK(numClusters);
model.setDecayFactor(.5);
model.setRandomCenters(numDimensions, 0.0, Utils.random().nextLong());

model.trainOn(trainingData.dstream());

And here is the exception I receive:
java.lang.IllegalArgumentException: requirement failed
    at scala.Predef$.require(Predef.scala:221)
    at org.apache.spark.mllib.util.MLUtils$.fastSquaredDistance(MLUtils.scala:292)
    at org.apache.spark.mllib.clustering.KMeans$.fastSquaredDistance(KMeans.scala:485)
    at org.apache.spark.mllib.clustering.KMeans$$anonfun$findClosest$1.apply(KMeans.scala:459)
    at org.apache.spark.mllib.clustering.KMeans$$anonfun$findClosest$1.apply(KMeans.scala:453)
    at scala.collection.mutable.ArraySeq.foreach(ArraySeq.scala:73)
    at org.apache.spark.mllib.clustering.KMeans$.findClosest(KMeans.scala:453)
    at org.apache.spark.mllib.clustering.KMeansModel.predict(KMeansModel.scala:35)
    at org.apache.spark.mllib.clustering.StreamingKMeans$$anonfun$predictOnValues$1.apply(StreamingKMeans.scala:258)
    at org.apache.spark.mllib.clustering.StreamingKMeans$$anonfun$predictOnValues$1.apply(StreamingKMeans.scala:258)
    at org.apache.spark.rdd.PairRDDFunctions$$anonfun$mapValues$1$$anonfun$apply$15.apply(PairRDDFunctions.scala:674)
    at org.apache.spark.rdd.PairRDDFunctions$$anonfun$mapValues$1$$anonfun$apply$15.apply(PairRDDFunctions.scala:674)
    at scala.collection.Iterator$$anon$11.next(Iterator.scala:328)
    at scala.collection.Iterator$$anon$10.next(Iterator.scala:312)
    at scala.collection.Iterator$class.foreach(Iterator.scala:727)
    at scala.collection.AbstractIterator.foreach(Iterator.scala:1157)
    at scala.collection.generic.Growable$class.$plus$plus$eq(Growable.scala:48)
    at scala.collection.mutable.ArrayBuffer.$plus$plus$eq(ArrayBuffer.scala:103)
    at scala.collection.mutable.ArrayBuffer.$plus$plus$eq(ArrayBuffer.scala:47)
    at scala.collection.TraversableOnce$class.to(TraversableOnce.scala:273)
    at scala.collection.AbstractIterator.to(Iterator.scala:1157)
    at scala.collection.TraversableOnce$class.toBuffer(TraversableOnce.scala:265)
    at scala.collection.AbstractIterator.toBuffer(Iterator.scala:1157)
    at scala.collection.TraversableOnce$class.toArray(TraversableOnce.scala:252)
    at scala.collection.AbstractIterator.toArray(Iterator.scala:1157)
    at org.apache.spark.rdd.RDD$$anonfun$33.apply(RDD.scala:1177)
    at org.apache.spark.rdd.RDD$$anonfun$33.apply(RDD.scala:1177)
    at org.apache.spark.SparkContext$$anonfun$runJob$5.apply(SparkContext.scala:1498)
    at org.apache.spark.SparkContext$$anonfun$runJob$5.apply(SparkContext.scala:1498)
    at org.apache.spark.scheduler.ResultTask.runTask(ResultTask.scala:61)
    at org.apache.spark.scheduler.Task.run(Task.scala:64)
    at org.apache.spark.executor.Executor$TaskRunner.run(Executor.scala:203)
    at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:895)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:918)
    at java.lang.Thread.run(Thread.java:662)

As you can see in the above code I am checking to make sure my vectors are all the same size and they appear to be, even though the error is suggesting they are not. Any help would be greatly appreciated!

A: All the vectors are not of the same dimension could cause this exception.
In my experience, another possible reason is Vector which contains the value of NaN.
All values in the vector can not contain NaN.


text:
Q: Searching in mysql table on email(unique) column I have several questions in mind,
1) Is searching on int key is faster than searching on string key?
Relevance of my second question depends totally on answer of first,
If yes,
2) I have a table which have a [1-5]billion records, having a unique email column. I am planning to have one more column that will store hashcode(int) of email(string). Whenever I want a record with given email, I will search records with the hashcode of the email and then match the exact email.
How effective will be second? Please suggest if there is any better alternative available.

A: A CPU can compare an integer faster than a string.  Strings are represented as ASCII encoded integers in memory, so to compare a string the program must first convert and compare each character before a conclusion is returned.  In MYSQL, if you have a UNIQUE column combined with a fixed length VARCHAR, the search time will be very fast because the mysql engine will build a tree and use that to search for the key.  Without those two, the mysql engine must compare each email row to the search criteria.  MySQL has advanced through the years and there are lots of build in mechanisms that can be leveraged to make database management extremely fast.


text:
Q: Failing test class I'm working on the solution posted here: http://mysalesforcecode.blogspot.com/2012/09/how-to-copy-record-owner-from-cloning.html
The button and trigger work just as hoped, but I keep getting a test failure due to the second system assert in my test (testing if the opportunity owner was retained per the original owner field. I'm an apex novice, so I could be doing something obviously wrong... hope so - Thanks!
Button:
{!URLFOR( $Action.Opportunity.Clone,Opportunity.Id,
[cloneli=1,opp11='Prospecting',opp12='10',opp9=
TEXT(MONTH(Opportunity.CloseDate))+"/"
+TEXT(DAY(Opportunity.CloseDate))+"/"
+TEXT(YEAR(Opportunity.CloseDate)+1)
])}&00NZ0000000kfYf={!Opportunity.OwnerId}&retURL={!Opportunity.Id}

Trigger (updated per answer below):
trigger OwnerIdChange on Opportunity (before insert)
{
 for(Opportunity o : Trigger.new)
 {
  if(o.OriginalOwner__c != null)
     o.OwnerId = o.OriginalOwner__c;
 }
}

Test Class:
@istest
private class Opportunities_Test {

    static testMethod void Opportunities_Test1() {
    test.starttest();

      Profile p = [SELECT Id FROM Profile WHERE Name='Standard User'];
      User u = new User(Alias = 'standt', Email='standarduser@testorg.com',
      EmailEncodingKey='UTF-8', LastName='Testing', LanguageLocaleKey='en_US',
      LocaleSidKey='en_US', ProfileId = p.Id,
      TimeZoneSidKey='America/Los_Angeles', UserName='standarduser@testorg.com');
      insert u;

      Profile s = [SELECT Id FROM Profile WHERE Name='System Administrator'];
      User u2 = new User(Alias = 'admin', Email='admin@testorg.com',
      EmailEncodingKey='UTF-8', LastName='Testing2', LanguageLocaleKey='en_US',
      LocaleSidKey='en_US', ProfileId = s.Id,
      TimeZoneSidKey='America/Los_Angeles', UserName='admin@testorg.com');
      insert u2;

     Account a = new account(Name = 'Test1');
     insert a;

     List <Opportunity> Opportunity;
            Opportunity O1 = new Opportunity();
            O1.ownerid = u.id;
            O1.accountid = a.id;
            O1.Amount= 1;
            O1.CloseDate = Date.today();
            O1.Name = 'Testing';
            O1.StageName= 'Prospecting';
            insert O1;

 Account b = new account(Name = 'Test2');
 insert b;

      List <Opportunity> Opportunity2;
        Opportunity O2 = new Opportunity();
        O2.accountid = b.id;
        O2.ownerid = u.id;
        O2.Amount= 1;
        O2.CloseDate = Date.today();
        O2.Name = 'Testing2';
        O2.StageName= 'Prospecting';
        O2.OriginalOwner__c= u2.id;
        insert O2;

List<Opportunity> z = [SELECT Id, Ownerid, Name FROM Opportunity WHERE id= :O2.id];

 system.assertEquals(O1.ownerid, u.id);
 system.assertEquals(O2.OwnerID, u2.id);

     test.stoptest();
    }
}

A: Your trigger logic is a bit crazy, try changing it to the following and see if you get different results.
trigger OwnerIdChange on Opportunity (before insert)
{
   for(Opportunity o : Trigger.new)
   {
      if(o.OriginalOwner__c != null)
         o.OwnerId = o.OriginalOwner__c;
   }
}

EDIT: Per the comments below it should also be pointed out that he is not getting the updated value of the record after he inserts and updates them. Re-query the opportunity records and assert based off those returned values.


text:
Q: Using Reflections to dynamically load all classes in a package I have a package called "func_commands" that has a bunch of classes that each have the functions "cmd" and "man". I want to be able to load them without specifically stating their names, since I'm using an interface right now, and I want my program to be modular, so that classes can be added or removed by the user, and loaded/unloaded accordingly on the program's next restart.
I've heard that Reflections can do this, but I can't find a working tutorial on how to do it, and I'm an idiot when it comes to documentation. Does anyone know how to do this?
I've been able to use it to find the classes that extend my interface, but I can't figure out how to make it load said classes.
    Reflections reflections = new Reflections("func_commands"); //init reflections and point it to the package (I think thats what the string does, I forgot)

    Set<Class<? extends Command>> allClasses =
            reflections.getSubTypesOf(Command.class); //get the classes from it that extend Commnd

How I'm currently loading the classes:
for(Command command:CommandArray.commands) {
        command.cmd(e);
        command.man(e);
    };

//meanwhile in CommandArray...
public static Command[] commands = {
        new ClassA(),
        new ClassB(),
        new ClassC()
};

A: I want to be able to load them without specifically stating their names, since I'm using an interface right now, and I want my program to be modular, so that classes can be added or removed by the user, and loaded/unloaded accordingly on the program's next restart.
What you probably mean by this is that you want to be able to instantiate classes and only access their public API via interfaces. This is very good practice.
There are multiple ways to achieve this and you are quite right in noting that reflection is one of them. However, this is quite costly and it involves having to cast the instantiated class. This removes any compile time checks from your program.
Another common practice is to provide a static factory class with methods to instantiate objects. A very good example of this is present in the JDK. EnumSet does not have any constructors and only has a static factory. Under the hood, two different classes, namely, RegularEnumSet and JumboEnumSet are instantiated based on the size of the underlying Enum. You use a similar approach an define classes within the static factory and swap out implementations for different needs.
More information about static factories can be found at: https://dzone.com/articles/constructors-or-static-factory-methods
EDITED: Added a link for reflective class instantiation as well: http://tutorials.jenkov.com/java-reflection/dynamic-class-loading-reloading.html


text:
Q: Close rdpcap function - Scapy I have a script that loops through a lot of pcap files. For each pcap file I need to read it and then write some information to a txt file. I'm using the rdcap function from Scapy. Is there anyway to close the pcap file once I'm done reading it? My script has a memory leak and I'm worried this may be the culprit (via leaving many pcap files essentially open)

A: Inspecting Scapy's source code reveals that the rdpcap function neglects to close the pcap file:
@conf.commands.register
def rdpcap(filename, count=-1):
    """Read a pcap file and return a packet list
count: read only <count> packets"""
    return PcapReader(filename).read_all(count=count)

I suggest you implement your own version of this function as follows:
def rdpcap_and_close(filename, count=-1):
    """Read a pcap file, return a packet list and close the file
count: read only <count> packets"""
    pcap_reader = PcapReader(filename)
    packets = pcap_reader.read_all(count=count)
    pcap_reader.close()
    return packets

I've created an issue for this problem here.
EDIT: The issue has been resolved in this changeset.


text:
Q: python tuple remove the first match appearance using only higher order functions I want to write a Rem(a, b) which return a new tuple that is like a, with the first appearance of element b is removed. For example
Rem((0, 1, 9, 1, 4), 1) which will return (0, 9, 1, 4).
I am only allowed to use higher order functions such as lambda, filter, map, and reduce.
I am thinking about to use filter but this will delete all of the match elements
def myRem(T, E):
    return tuple(filter(lambda  x: (x!=E), T))

myRem((0, 1, 9, 1, 4), 1) I will have (0,9,4)

A: The following works (Warning: hacky code):
tuple(map(lambda y: y[1], filter(lambda  x: (x[0]!=T.index(E)), enumerate(T))))

But I would never recommend doing this unless the requirements are rigid

A: Trick with temporary list:
def removeFirst(t, v):
    tmp_lst = [v]
    return tuple(filter(lambda  x: (x != v or (not tmp_lst or v != tmp_lst.pop(0))), t))

print(removeFirst((0, 1, 9, 1, 4), 1))

*

*tmp_lst.pop(0) - will be called only once (thus, excluding the 1st occurrence of the crucial value v)

*not tmp_lst - all remaining/potential occurrences will be included due to this condition

The output:
(0, 9, 1, 4)

A: For fun, using itertools, you can sorta use mostly higher-order functions...
>>> from itertools import *
>>> data = (0, 1, 9, 1, 4)
>>> not1 = (1).__ne__
>>> tuple(chain(takewhile(not1, data), islice(dropwhile(not1, data), 1, None)))
(0, 9, 1, 4)

BTW, here's some timings comparing different approaches for dropping a particular index in a tuple:
>>> timeit.timeit("t[:i] + t[i+1:]", "t = tuple(range(100000)); i=50000", number=10000)
10.42419078599778
>>> timeit.timeit("(*t[:i], *t[i+1:])", "t = tuple(range(100000)); i=50000", number=10000)
20.06185237201862
>>> timeit.timeit("(*islice(t,None, i), *islice(t, i+1, None))", "t = tuple(range(100000)); i=50000; from itertools import islice", number=10000)
>>> timeit.timeit("tuple(chain(islice(t,None, i), islice(t, i+1, None)))", "t = tuple(range(100000)); i=50000; from itertools import islice, chain", number=10000)
19.71128663700074
>>> timeit.timeit("it = iter(t); tuple(chain(islice(it,None, i), islice(it, 1, None)))", "t = tuple(range(100000)); i=50000; from itertools import islice, chain", number=10000)
17.6895881179953

Looks like it is hard to beat the straightforward: t[:i] + t[i+1:], which is not surprising.
Note, this one is shockingly less performant:
>>> timeit.timeit("tuple(j for i, j in enumerate(t) if i != idx)", "t = tuple(range(100000)); idx=50000", number=10000)
111.66658291200292

Which makes me thing all these solutions using takewhile, filter and lambda will all suffer pretty bad...
Although:
>>> timeit.timeit("not1 = (i).__ne__; tuple(chain(takewhile(not1, t), islice(dropwhile(not1, t), 1, None)))", "t = tuple(range(100000)); i=50000; from itertools import chain, takewhile,dropwhile, islice", number=10000)
62.22159145199112

Almost twice as fast as the generator expression, which goes to show, generator overhead can be quite large. However, takewhile and dropwhile are implemented in C, albeit this implementation has redundancy (take-while and dropwhile will pass the dropwhile areas twice).
Another interesting observation, if we simply wrap the substitute a list-comp for the generator expression, it is significantly faster despite the fact that the list-comprehension + tuple call iterates over the result twice compared to only once with the generator expression:
>>> timeit.timeit("tuple([j for i, j in enumerate(t) if i != idx])", "t = tuple(range(100000)); idx=50000", number=10000)
82.59887028901721

Goes to show how steep the generator-expression price can be...

A: Here is a solution that only uses lambda, filter(), map(), reduce() and tuple().
def myRem(T, E):
    # map the tuple into a list of tuples (value, indicator)
    M = map(lambda x: [(x, 1)] if x == E else [(x,0)], T)

    # make the indicator 0 once the first instance of E is found
    # think of this as a boolean mask of items to remove
    # here the second reduce can be changed to the sum function
    R = reduce(
        lambda x, y: x + (y if reduce(lambda a, b: a+b, map(lambda z: z[1], x)) < 1
                          else [(y[0][0], 0)]),
        M
    )

    # filter the reduced output based on the indicator
    F = filter(lambda x: x[1]==0, R)

    # map the output back to the desired format
    O = map(lambda x: x[0], F)
    return tuple(O)

Explanation
A good way to understand what's going on is to print the outputs of the intermediate steps.
Step 1: First Map
For each value in the tuple, we return a tuple with the value and a flag to indicate if it's the value to remove. These tuples are encapsulated in a list because it makes combining easier in the next step.
# original example
T = (0, 1, 9, 1, 4)
E = 1
M = map(lambda x: [(x, 1)] if x == E else [(x,0)], T)
print(M)
#[[(0, 0)], [(1, 1)], [(9, 0)], [(1, 1)], [(4, 0)]]

Step 2: Reduce
This returns a list of tuples in a similar structure to the contents of M, but the flag variable is set to 1 for the first instance of E, and 0 for all subsequent instances. This is achieved by calculating the sum of the indicator up to that point (implemented as another reduce()).
R = reduce(
    lambda x, y: x + (y if reduce(lambda a, b: a+b, map(lambda z: z[1], x)) < 1
                      else [(y[0][0], 0)]),
    M
)
print(R)
#[(0, 0), (1, 1), (9, 0), (1, 0), (4, 0)]

Now the output is in the form of (value, to_be_removed).
Step 3: Filter
Filter out the value to be removed.
F = filter(lambda x: x[1]==0, R)
print(F)
#[(0, 0), (9, 0), (1, 0), (4, 0)]

Step 4: Second map and conversion to tuple
Extract the value from the filtered list, and convert it to a tuple.
O = map(lambda x: x[0], F)
print(tuple(O))
#(0, 9, 1, 4)

A: This violates your requirement for "only using higher order functions" - but since it's not clear why this is a requirement, I include the below solution.
def myRem(tup, n):
    idx = tup.index(n)
    return tuple(j for i, j in enumerate(tup) if i != idx)

myRem((0, 1, 9, 1, 4), 1)

# (0, 9, 1, 4)

Here is a numpy solution (still not using higher-order functions):
import numpy as np

def myRem(tup, n):
    tup_arr = np.array(tup)
    return tuple(np.delete(tup_arr, np.min(np.nonzero(tup_arr == n)[0])))

myRem((0, 1, 9, 1, 4), 1)

# (0, 9, 1, 4)


text:
Q: Detecting 'back key' press from within a leaderboard? (Android) I have a leaderboard set up in my Android game and it seems to work pretty well.
From the main menu the player can press the 'show scores' button to simply view the leaderboard and when the player's game is over (either through losing all their lives or completing the game), they are given the option of submitting their score.  If this is pressed, the score is submitted and the leaderboard displayed to show the new score.
I have my app set up so that it will return to it's current scene (menu, game etc.) if it is temporarily interrupted.
However, I can't work out how to 'know' if the leaderboard is currently being shown to the user. (Well, I do know how to set this, rather I don't know how to 'unset' it when the leaderboard is exited)
I have a variable set up which determines which action my app should take when 'onSignedInSucceded()' is called like so:
@Override
public void onSignInSucceeded() {

    //If the flag is set, then display the leaderboard
    if (signInAction==SHOW_LEADERBOARD){
        displayLeaderBoard();
    }

    //If the flag is set, then display the submit score
    else if (signInAction==SUBMITSCORE){
        submitScore();
    }

    //Otherwise, reset the flag and take no action
    else {signInAction=NO_ACTION;}
}

However, what happens is that, lets say the user pressed the 'show scores' button, we set the signInAction to SHOW_LEADERBOARD and then connect.  The leaderboard is displayed.
The user then presses the back key and returns to the app.  If the app is now interrupted, onSignInSucceded() is called and the leaderboard is displayed again. (but it wasn't being displayed when the app was interrupted therefore this diminishes the user experience).
It would be great it, when the user presses the 'back' key to exit from the leaderboard, I could set the signInAction back to 'No_Action' - how can I do this?
Just for additional information, my app is a single activity and utilises a custom scene manager so in my Activity class, I can do things on back press like:
If (CurrentScene = mainMenu){
    //Do Something Here
}

However, the leaderboard is not a custom scene.  So I'm not sure how to go about this.
I guess this question could probably best be summed up as 'How can I detect a back key press from Google Play Leaderboard? (when the user exits it back into the app)' - any help would be appreciated.

A: You should be able to use onActivityResult() to clear signInAction. You'll need to check the request code and maybe the result codes depending on your application.
Some of the possible results will be:

*

*Activity.RESULT_CANCELED (this is the one you're interested in)

*GamesActivityResultCodes.RESULT_RECONNECT_REQUIRED
but you'll probably be best off handling them all the same way.
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
    {
    //just returned from displaying the leaderboard
    if(requestCode==REQUEST_LEADERBOARD)
        {
        signInAction=NO_ACTION;
        return;
        }

    super.onActivityResult(requestCode, resultCode, data);
    }


text:
Q: what is the use of "mux." in pipeline command This pipeline encodes a test audio and video stream and muxes both into an FLV file.
gst-launch-1.0 -v flvmux name=mux ! filesink location=test.flv  audiotestsrc samplesperbuffer=44100 num-buffers=10 ! faac ! mux.  videotestsrc num-buffers=250 ! video/x-raw,framerate=25/1 ! x264enc ! mux.

I am not able to figure out what mux. actually does and use of dot in pipeline command during muxing,Can someone please explain or any doc for reference

A: The dot . at the end of a string refers to named elements. In your case mux. means The element with the name "mux". In your pipeline you have flvmux name=mux - here the flvmux element instance gets the name mux assigned to it (via name=mux. The mux. then latter refers to that specific instance of flvmux (and not a new muxer instance for example).
https://gstreamer.freedesktop.org/documentation/tools/gst-launch.html?gi-language=c#pipeline-description


text:
Q: Android kotlin butterknife view visibility I was trying to set the visibility of a view in android using ButterKnife with Kotlin
I got the id in butterknife like:
@BindView(R.id.progress)
lateinit var progress: ProgressBar

The visibility can be set in Java like: (As we know)
progress.setVisibility(View.VISIBLE);
progress.setVisibility(View.GONE);

I tried: progress.visibility to .... ?
How will it be in kotlin with ButterKnife?

A: You can use the same setters in Kotlin:
progress.setVisibility(View.VISIBLE)

You can also use a property access syntax instead, which does the exact same thing:
progress.visibility = View.VISIBLE

As for the last part of your question, if you were trying to write this:
progress.visibility to View.VISIBLE

Then all that does is create a Pair which is never used and just thrown away - it's equivalent to this:
Pair(progress.visibility, View.VISIBLE)

A: Try with
progress.visibility= View.VISIBLE
progress.visibility= View.GONE

Note
You should use kotlinx.android.synthetic.

Every Android developer knows well the findViewById() function. It is,
  without a doubt, a source of potential bugs and nasty code which is
  hard to read and support. While there are several libraries available
  that provide solutions to this problem, those libraries require
  annotating fields for each exposed View.
The Kotlin Android Extensions plugin allows us to obtain the same
  experience we have with some of these libraries, without having to add
  any extra code.

Example
import kotlinx.android.synthetic.main.activity_main.*

    class MyActivity : Activity() {
        override fun onCreate(savedInstanceState: Bundle?) {
            super.onCreate(savedInstanceState)
            setContentView(R.layout.activity_main)

            // Instead of findViewById<ProgressBar>(R.id.progress)
             progress.visibility= View.GONE
        }
    }


text:
Q: Adding data to two different tables from one form using spring and JPA I am trying to add data to two different tables from one form using JPA and Spring. I was able to figure out how to do it by hard-coding the latitude and longitude data into the service class method for one of the tables; however, I am unsure how to enable the user to input the data himself for the latitude and longitude, which are in the second table from the same form.
The addBreweries.jsp form code is:
<form:form method="POST" action="/Assignment2/breweries/addBrewery" modelAttribute="brewerie">

            <form:label path="name">Name</form:label>
            <form:input path="name" />
            <form:errors path="name"/>

            <form:label path="address1">Address 1</form:label>
            <form:input path="address1" />
            <form:errors path="address1"/>

            <form:label path="address2">Address 2</form:label>
            <form:input path="address2"/>
            <form:errors path="address2"/>

            <form:label path="city">City</form:label>
            <form:input path="city"/>
            <form:errors path="city"/>

            <form:label path="state">State</form:label>
            <form:input path="state"/>
            <form:errors path="state"/>

            <form:label path="code">Code</form:label>
            <form:input path="code"/>
            <form:errors path="code"/>

            <form:label path="country">Country</form:label>
            <form:input path="country"/>
             <form:errors path="country"/>

            <form:label path="phone">Phone Number</form:label>
            <form:input path="phone"/>
             <form:errors path="phone"/>

            <form:label path="website">Website</form:label>
            <form:input path="website"/>
            <form:errors path="website"/>

            <form:label path="description">Description</form:label>
            <form:input path="description"/>
             <form:errors path="description"/>

            <form:label path="addUser">Add User</form:label>
            <form:input path="addUser"/>
             <form:errors path="addUser"/>

            <form:label path="creditLimit">Credit Limit</form:label>
            <form:input path="creditLimit"/>
             <form:errors path="creditLimit"/>

            <form:label path="email">Email</form:label>
            <form:input path="email"/>
             <form:errors path="email"/>

            <input type="submit" value="Submit"/>

The code for the controller is:
 @PostMapping("/addBrewery")
public ModelAndView addAnAgent(@ModelAttribute("brewerie") Breweries brewerie) {
Date date = new Date();
    brewerie.setLastMod(date);

    service.addAnBreweries(brewerie);
    return new ModelAndView("redirect:/breweries");

}

The service class method I'm using is:
 public void addAnBreweries(Breweries brewerie) {
    EntityManager em = DBUtil.getEMF().createEntityManager();
    EntityTransaction trans = em.getTransaction();
    Date date = new Date();
    brewerie.setLastMod(date);
    try {
        trans.begin();
        em.persist(brewerie);
        trans.commit();

        BreweriesGeocode bg = new BreweriesGeocode();
        bg.setBreweryId((Integer) brewerie.getId());
        bg.setLongitude(-97);
        bg.setLatitude(30);
         trans.begin();
        em.persist(bg);
        trans.commit();

    } catch (Exception ex) {
        System.out.println(ex);
    } finally {
        em.close();
    }
}

The Breweries.java class is:
package brewery.src.model;

import java.io.Serializable;
import java.util.Date;
import javax.persistence.Basic;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Lob;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.SecondaryTable;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
import javax.xml.bind.annotation.XmlRootElement;

/**
 *
 * @author k00203657
 */
@Entity
@Table(name = "breweries")

@XmlRootElement
@NamedQueries({
    @NamedQuery(name = "Breweries.findAll", query = "SELECT b FROM Breweries b"),
    @NamedQuery(name = "Breweries.findById", query = "SELECT b FROM Breweries b WHERE b.id = :id"),
    @NamedQuery(name = "Breweries.findByName", query = "SELECT b FROM Breweries b WHERE b.name = :name"),
    @NamedQuery(name = "Breweries.findByAddress1", query = "SELECT b FROM Breweries b WHERE b.address1 = :address1"),
    @NamedQuery(name = "Breweries.findByAddress2", query = "SELECT b FROM Breweries b WHERE b.address2 = :address2"),
    @NamedQuery(name = "Breweries.findByCity", query = "SELECT b FROM Breweries b WHERE b.city = :city"),
    @NamedQuery(name = "Breweries.findByState", query = "SELECT b FROM Breweries b WHERE b.state = :state"),
    @NamedQuery(name = "Breweries.findByCode", query = "SELECT b FROM Breweries b WHERE b.code = :code"),
    @NamedQuery(name = "Breweries.findByCountry", query = "SELECT b FROM Breweries b WHERE b.country = :country"),
    @NamedQuery(name = "Breweries.findByPhone", query = "SELECT b FROM Breweries b WHERE b.phone = :phone"),
    @NamedQuery(name = "Breweries.findByWebsite", query = "SELECT b FROM Breweries b WHERE b.website = :website"),
    @NamedQuery(name = "Breweries.findByImage", query = "SELECT b FROM Breweries b WHERE b.image = :image"),
    @NamedQuery(name = "Breweries.findByAddUser", query = "SELECT b FROM Breweries b WHERE b.addUser = :addUser"),
    @NamedQuery(name = "Breweries.findByLastMod", query = "SELECT b FROM Breweries b WHERE b.lastMod = :lastMod"),
    @NamedQuery(name = "Breweries.findByCreditLimit", query = "SELECT b FROM Breweries b WHERE b.creditLimit = :creditLimit"),
    @NamedQuery(name = "Breweries.findByEmail", query = "SELECT b FROM Breweries b WHERE b.email = :email")})
public class Breweries implements Serializable {

    private static final long serialVersionUID = 1L;

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Basic(optional = false)
@Column(name = "id")
private Integer id;
@Basic(optional = false)
@NotNull
@Size(min = 1, max = 255)
@Column(name = "name")
private String name;
@Basic(optional = false)
@NotNull
@Size(min = 1, max = 255)
@Column(name = "address1")
private String address1;
@Basic(optional = false)
@NotNull
@Size(min = 1, max = 255)
@Column(name = "address2")
private String address2;
@Basic(optional = false)
@NotNull
@Size(min = 1, max = 255)
@Column(name = "city")
private String city;
@Basic(optional = false)
@NotNull
@Size(min = 1, max = 255)
@Column(name = "state")
private String state;
@Basic(optional = false)
@NotNull
@Size(min = 1, max = 25)
@Column(name = "code")
private String code;
@Basic(optional = false)
@NotNull
@Size(min = 1, max = 255)
@Column(name = "country")
private String country;
// @Pattern(regexp="^\\(?(\\d{3})\\)?[- ]?(\\d{3})[- ]?(\\d{4})$", message="Invalid phone/fax format, should be as xxx-xxx-xxxx")//if the field contains phone or fax number consider using this annotation to enforce field validation
@Basic(optional = false)
@NotNull
@Size(min = 1, max = 50)
@Column(name = "phone")
private String phone;
@Basic(optional = false)
@NotNull
@Size(min = 1, max = 255)
@Column(name = "website")
private String website;
@Basic(optional = false)
@NotNull
@Size(min = 1, max = 255)
@Column(name = "image")
private String image;
@Basic(optional = false)
@NotNull
@Lob
@Size(min = 1, max = 65535)
@Column(name = "description")
private String description;
@Basic(optional = false)
@NotNull
@Column(name = "add_user")
private int addUser;
@Basic(optional = false)
@NotNull
@Column(name = "last_mod")
@Temporal(TemporalType.TIMESTAMP)
private Date lastMod;
@Basic(optional = false)
@NotNull
@Column(name = "credit_limit")
private double creditLimit;
// @Pattern(regexp="[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?", message="Invalid email")//if the field contains email address consider using this annotation to enforce field validation
@Basic(optional = false)
@NotNull
@Size(min = 1, max = 50)
@Column(name = "email")
private String email;

public Breweries() {
}

public Breweries(Integer id) {
    this.id = id;
}

public Breweries(Integer id, String name, String address1, String address2, String city, String state, String code, String country, String phone, String website, String image, String description, int addUser, Date lastMod, double creditLimit, String email) {
    this.id = id;
    this.name = name;
    this.address1 = address1;
    this.address2 = address2;
    this.city = city;
    this.state = state;
    this.code = code;
    this.country = country;
    this.phone = phone;
    this.website = website;
    this.image = image;
    this.description = description;
    this.addUser = addUser;
    this.lastMod = lastMod;
    this.creditLimit = creditLimit;
    this.email = email;
}

public Integer getId() {
    return id;
}

public void setId(Integer id) {
    this.id = id;
}

public String getName() {
    return name;
}

public void setName(String name) {
    this.name = name;
}

public String getAddress1() {
    return address1;
}

public void setAddress1(String address1) {
    this.address1 = address1;
}

public String getAddress2() {
    return address2;
}

public void setAddress2(String address2) {
    this.address2 = address2;
}

public String getCity() {
    return city;
}

public void setCity(String city) {
    this.city = city;
}

public String getState() {
    return state;
}

public void setState(String state) {
    this.state = state;
}

public String getCode() {
    return code;
}

public void setCode(String code) {
    this.code = code;
}

public String getCountry() {
    return country;
}

public void setCountry(String country) {
    this.country = country;
}

public String getPhone() {
    return phone;
}

public void setPhone(String phone) {
    this.phone = phone;
}

public String getWebsite() {
    return website;
}

public void setWebsite(String website) {
    this.website = website;
}

public String getImage() {
    return image;
}

public void setImage(String image) {
    this.image = image;
}

public String getDescription() {
    return description;
}

public void setDescription(String description) {
    this.description = description;
}

public int getAddUser() {
    return addUser;
}

public void setAddUser(int addUser) {
    this.addUser = addUser;
}

public Date getLastMod() {
    return lastMod;
}

public void setLastMod(Date lastMod) {
    this.lastMod = lastMod;
}

public double getCreditLimit() {
    return creditLimit;
}

public void setCreditLimit(double creditLimit) {
    this.creditLimit = creditLimit;
}

public String getEmail() {
    return email;
}

public void setEmail(String email) {
    this.email = email;
}

@Override
public int hashCode() {
    int hash = 0;
    hash += (id != null ? id.hashCode() : 0);
    return hash;
}

@Override
public boolean equals(Object object) {
    // TODO: Warning - this method won't work in the case the id fields are not set
    if (!(object instanceof Breweries)) {
        return false;
    }
    Breweries other = (Breweries) object;
    if ((this.id == null && other.id != null) || (this.id != null && !this.id.equals(other.id))) {
        return false;
    }
    return true;
}

@Override
public String toString() {
    return "lit.sd4.model.Breweries[ id=" + id + " ]";
}

The code for the BreweriesGeocode.java is:
package brewery.src.model;

import java.io.Serializable;
import javax.persistence.Basic;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.Table;
import javax.validation.constraints.NotNull;
import javax.xml.bind.annotation.XmlRootElement;

/**
 *
 * @author Brendan
 */
@Entity
@Table(name = "breweries_geocode")
@XmlRootElement
@NamedQueries({
    @NamedQuery(name = "BreweriesGeocode.findAll", query = "SELECT b FROM BreweriesGeocode b"),
    @NamedQuery(name = "BreweriesGeocode.findById", query = "SELECT b FROM BreweriesGeocode b WHERE b.id = :id"),
    @NamedQuery(name = "BreweriesGeocode.findByBreweryId", query = "SELECT b FROM BreweriesGeocode b WHERE b.breweryId = :breweryId"),
    @NamedQuery(name = "BreweriesGeocode.findByLatitude", query = "SELECT b FROM BreweriesGeocode b WHERE b.latitude = :latitude"),
    @NamedQuery(name = "BreweriesGeocode.findByLongitude", query = "SELECT b FROM BreweriesGeocode b WHERE b.longitude = :longitude")})
public class BreweriesGeocode implements Serializable {

    private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Basic(optional = false)
@Column(name = "id")
private Integer id;
@Basic(optional = false)
@NotNull
@Column(name = "brewery_id")
private int breweryId;
@Basic(optional = false)
@NotNull
@Column(name = "latitude")
private float latitude;
@Basic(optional = false)
@NotNull
@Column(name = "longitude")
private float longitude;

public BreweriesGeocode() {
}

public BreweriesGeocode(Integer id) {
    this.id = id;
}

public BreweriesGeocode(Integer id, int breweryId, float latitude, float longitude) {
    this.id = id;
    this.breweryId = breweryId;
    this.latitude = latitude;
    this.longitude = longitude;
}

public Integer getId() {
    return id;
}

public void setId(Integer id) {
    this.id = id;
}

public int getBreweryId() {
    return breweryId;
}

public void setBreweryId(int breweryId) {
    this.breweryId = breweryId;
}

public float getLatitude() {
    return latitude;
}

public void setLatitude(float latitude) {
    this.latitude = latitude;
}

public float getLongitude() {
    return longitude;
}

public void setLongitude(float longitude) {
    this.longitude = longitude;
}

@Override
public int hashCode() {
    int hash = 0;
    hash += (id != null ? id.hashCode() : 0);
    return hash;
}

@Override
public boolean equals(Object object) {
    // TODO: Warning - this method won't work in the case the id fields are not set
    if (!(object instanceof BreweriesGeocode)) {
        return false;
    }
    BreweriesGeocode other = (BreweriesGeocode) object;
    if ((this.id == null && other.id != null) || (this.id != null && !this.id.equals(other.id))) {
        return false;
    }
    return true;
}

@Override
public String toString() {
    return "brewery.src.model.BreweriesGeocode[ id=" + id + " ]";
}

A: *

*Add the latitude and longitude fields on the form.

*Create a DTO class, which contains old (Breweries) and new (BreweriesGeocode) fields

*Update the /addBrewery method by changing of an input param to that DTO.

*Map the DTO to Breweries and BreweriesGeocode entities and store them.


text:
Q: How minimally can I cut a cake sector-wise to fit it into a slightly undersized square tin? In geometrical terms, what is the smallest number $n$ such that a disc of unit radius can be cut into $n$ sectors that can be reassembled without overlapping to fit into a square of side $2-\varepsilon$, where $\varepsilon>0$ is as small as you like? The question could be set for arbitrary straight cuts; but I like to serve my guests with traditional sector-shaped pieces.

A: Here's a solution using three pieces:
$\hspace{1.5in}$
Two pieces have angle $\pi-\alpha$ and one has angle $2\,\alpha\,$ for some small $\alpha$ $\;$($\alpha =\frac{\pi}{12}$ in the diagram).
(I eventually got there after starting with a 10-piece solution!)

A: When posting this question, I only knew that it could be done for large $n$. Since then, I found a way to do it (I think!) for $n=3$: Cut the disc into sectors of $248^\circ$, $104^\circ$, and $8^\circ$ (slight variations on these numbers are possible). Place the big sector symmetrically in one corner of the square, with the cut-out toward the opposite corner, and put the medium sector symmetrically in the cut-out so that the circular part of its boundary touches the two straight radial edges of the big sector. There is just enough room left to slip the remaining sliver in between a straight edge of the medium sector and the neighbouring side of the square.
   I hope that this is right, but I may have miscalculated. Any refutation would be stoically welcome. Confirmation is naturally welcome too.
$\hspace{1.5in}$

A: With John's configuration, the maximum possible value of $\varepsilon$ is approximately $0.0291842223$:
$\hspace{1.5in}$
The pieces have angles approximately $228.8124035475^\circ$, $113.1341370910^\circ$ and $18.0534593614^\circ$.
Note that the large pieces are no longer positioned symmetrically.

A: Here's a third distinct three-piece configuration, with the centres of the sectors at the vertices of an equilateral triangle:
$\hspace{1.5in}$
All the pieces have an angle greater than $\frac{\pi}{2}$ (the angles in the diagram are $149.5^\circ$, $110^\circ$ and $100.5^\circ$).
A solution with three congruent pieces doesn't seem possible.


text:
Q: How to find and update item in array? i can't figure out how to update specific item in array of object by searching with ID. My code is working only when i hammer the update button for a few times. I want to work it with only one click.
This application is about interactive comments section, where you can add new comment, edit it and delete.
  const editCommentUpdate = () => {
    setData((prevData) => {
      return {
        ...prevData,
        comments: [
          ...prevData.comments.map((comment) => {
            if (comment.id === randomId) {
              return {
                ...comment,
                content: commentText,
              };
            } else {
              return {
                ...comment,
              };
            }
          }),
        ],
      };
    });
  };

And here's link to repository with this application: https://github.com/xflameyoke/interactive-comment-section-app/blob/main/src/components/commentList/commentList.tsx


text:
Q: Electronically switched decade resistance box design I'd like to design a decade resistance box that uses a microcontroller to control the resistance.
Would it be possible to switch between different valued resistors using transistors? (or another component?)

A: Yes, within limitations.  Low Rdson FETs would work as long as the lowest resistance you want to switch is significantly higher than the Rdson, if voltage is always applied one way, and the voltage is within the power supply limits.  If you need the resulting composite resistor to be more arbitrary, then you probably need to use relays.

A: Transistors are not a good choice; they can't handle AC, and DC in only one direction. That's not the way to emulate a resistor.
I would build a chain of 20 resistors, each double the previous one, so 1 \$\Omega\$, 2 \$\Omega\$, 4 \$\Omega\$, 8 \$\Omega\$, etc. By shorting selectively resistors you can create any value between 1 \$\Omega\$ and 1 M\$\Omega\$ with just those 20 values.
Use a reed relays parallel to each resistor.
This reed relay needs only 10 mA at 5 V, so can be driven directly by the microcontroller. Nick correctly points out that you have to check if the total current doesn't exceed the controller's capabilities. But at 20 \$\times\$ 10 mA we would stay way below the maximum of 300 mA for the ATMega8, for instance.
You can use latching relays, so that you can use the resistor without power supply. The price is higher than the reed relay (3.14 dollar vs. 1.20 dollar), and you need either extra logic, or twice the I/Os for driving them.
edit, re jippie's suggestion.
jippie suggests to use an R-2R ladder, so that only two different resistor values are needed. Though I felt immediately that this wouldn't work it took me a few minutes to understand why not. First intuition. An N-bit ladder network consists of (N+1) 2R resistors, and (N-1) R resistors. Without exact calculations, the largest resistor value you can create with these is always less than 2N \$\times\$ R, that's when you place the all in series. The smallest value is when they're all parallel, and that's always larger than R / (2N). So the ratio between largest and smallest is less than (2N)\$^2\$, which for 20 bits is 1600, and not 2\$^N\$, or 1048 576 as expected. How come? Because an R-2R ladder is ratiometric, i.e. the output depends on the ratio between two resistor values, and then you have a lot more possibilities. That's not what we have here; our network has just two nodes, not three. So it's a pity, but R-2R won't work.

A: Combine Steven's relays in his answer, with an R-2R ladder network. This way you only need two different value resistors.


text:
Q: Function executes despite call to `render` The objective of the app is to facilitate upload/download of files for users.
If the user does not select any file and tries to click upload, a prompt needs to be displayed.
def create
        @user = User.find(params[:user_id])
        @attachment = Attachment.new(params[:attachment => {:file => [ :original_filename ]}])

        if params[:attachment].nil?
          flash[:alert] = "No file!"
          render "new"
        end

        uploaded_io = params[:attachment][:file]
        @attachment.user_id = @user.id
        @attachment.name = params[:attachment][:file].original_filename
        @attachment.format = params[:attachment][:file].content_type
        @attachment.save
        File.open(Rails.root.join('public/data', @attachment.name), 'wb') do |file|
          file.write(uploaded_io.read)
        end

    redirect_to user_attachments_path, notice: "The file #{@attachment.name} has been uploaded."
end

Despite the if params[:atttachment].nil? block, I receive an error at the uploaded_io = params[:attachment][:file] statement.
params[:attachment].nil? returns true when no file is selected[checked using debugger]
Any reason why the if block is not executed?

A: you just have an if loop ,so irrespective of whether you code goes in if loop or  not,you are executing every code outside of if loop,which you needed to handle using if else.That means,code after if loop will always get executed,which should not be the case if its dependent of params[:attachment]
i have updated your code by using proper if else loop ..try to use this ...
            def create
                @user = User.find(params[:user_id])
                @attachment = Attachment.new(params[:attachment => {:file => [ :original_filename ]}])
                ##you can use .blank?  as well
                if params[:attachment].nil?
                  flash[:alert] = "No file!"
                  render "new"
                else
                 uploaded_io = params[:attachment][:file]
                 @attachment.user_id = @user.id
                 @attachment.name = params[:attachment][:file].original_filename
                 @attachment.format = params[:attachment][:file].content_type
                 @attachment.save
                 File.open(Rails.root.join('public/data', @attachment.name), 'wb') do |file|
                 file.write(uploaded_io.read)
                 end
                 redirect_to user_attachments_path, notice: "The file #{@attachment.name} has been uploaded."
               end
            end

A: You need to return to be able to render, otherwise you'll get a double render error, try something like this
if params[:attachment].nil?
  flash[:alert] = "No file!"
  return render "new"
end

Also another notice, when you're rendering directly, the flash message won't appear, it appears in the following request, instead you need to tell rails that you want that flash message to appear right away, so instead of just using flash, use flash.now
if params[:attachment].nil?
  flash.now[:alert] = "No file!"
  return render "new"
end


text:
Q: Returning disposable object and getting CA2000 warning I am trying to return XMLNodeReader to another function but getting CA2000 warning
XmlNodeReader obj =new XmlNodeReader(section);
return ser.method(obj);

If I use the following code, will it work properly? The warning is supressed but not sure if it will affect the logic or not.
XmlNodeReader tempObj =new XmlNodeReader(section);
XmlNodeReader retObj=null;
retObj = tempObj;
tempObj.Dispose();
return ser.method(retObj);

A: Well we have no idea what ser.method does, but passing a disposed object into method seems like a bad idea to me. Basically, your "fix" is bad.
There are three possibilities here (and probably others, but these are the main ones):

*

*ser.method disposes of its parameter itself. (That's probably a bad idea, but it might do.) In that case, your original code is fine.

*ser.method doesn't dispose of its parameter, but it returns something that relies on the reader still not being disposed

*ser.method doesn't dispose of its parameter, and returns something that doesn't need the reader to stay open

I'm hoping the last of these is the case, in which case you should change your code to:
using (XmlNodeReader reader = new XmlNodeReader(section))
{
    return ser.method(reader);
}


text:
Q: What is the shortcut to build and run a project in Visual Studio? Is there a shortcut that builds and run a project in the debug mode in the Visual Studio?
For example, Ctrl+Shift+B makes a build, but it does not run the program.


text:
Q: Jquery ajax POST response is null I want to get the url in this link:
CODE:

A: Looks like the returned data can't be parsed correctly. Here's my error message in Google Chrome:
 Uncaught SyntaxError: Unexpected token :

The data returned from http://www.panet.co.il/series/seriesLink/138099 has some UTF8 characters in it. Maybe that's the cause.

A: The problem is in the response. When you use JSONP the response result must be wrapped inside a jsonCallback() function:
jsonCallback({"Name": "Foo", "Id": 1234, "Rank": 7});

Look for more information here.


text:
Q: RecursionError: maximum recursion depth exceeded creating object of a class inside other class I want to call an object of another class in my class but when i run the code it says: RecursionError: maximum recursion depth exceeded
Any ideas of what error im making?
This is my code:
class Anden(Estacion):

    def __init__ (self,ID):

        self.ID=ID
        self.filas_anden=[0,0,0,0,0,0,0,0,0,0]
        self.puertas = []

        while len(self.puertas) < 10:
            puerta = Puerta(len(self.puertas))

    def asignar_fila(self, pasajero):
        aux=10000000000
        puerta_asignada = min(filas_anden)

        for i in range(10):
            if aux > self.puertas[i].total_fila:
                aux = self.puertas[i].total_fila
                fila_asignada = i
        pasajero.fila_actual = i
        self.filas_anden[i] +=1
        self.puertas[i].append(pasajero)

class Puerta(Anden):

    def _init_ (self,ID):
        self.ID = ID
        self.lista_pasajeros = []
        self.total_fila = 0

    def ingresa_pasajero_fila(self, pasajero):
        self.lista_pasajeros.append(pasajero)
        self.total_fila = self.total_fila + 1

    def remover_pasajero_fila(self, pasajero):
        self.lista_pasajeros.remove(pasajero)
        self.total_fila = self.total_fila - 1

A: So a few things. You made a typo in your Puerta constructor method. You're using _init_ instead of __init__, so when you initialize a Puerta object it's falling back to the constructor of its base class, Anden. That's what's causing this recursion error. Secondly, in your Anden constructor method, I think what you're trying to achieve is the following
def __init__ (self,ID):
    self.ID=ID
    self.filas_anden=[0,0,0,0,0,0,0,0,0,0]
    self.puertas = []

    while len(self.puertas) < 10:
        self.puertas.append(Puerta(len(self.puertas)))

In your current implementation, you're just setting an arbitrary variable puerta to a Puerta object which doesn't change the puertas list of your Anden instance and the while loop keeps going forever. Hope this helps!

A: You're having the same problem as Recursion error with class inheritance. A solution would be to make Puerta inherit from a base class common to Anden, instead of inheriting from Anden directly.


text:
Q: geom_tile different gradient scale and color for different factors Hi I would like to plot the following dataframe.
d<- data.frame (pid=c("d","b","c"), type=c("rna","rna","rna"), value = c(1,2,3) )
d2 <- data.frame (pid=c("d","b","c"), type=c("dna","dna","dna"), value = c(10,20,30) )
df <- rbind (d,d2)

 ggplot(df, aes(y=pid, x=type  ) ) + geom_tile(aes(fill = value),
  colour = "white") + scale_fill_gradient(low = "white",
  high = "steelblue")

This produces a plot that looks like this,

however, I would like to have each x factor have its own color gradient, so ideally rna is blue to white while dna is red to white.  Is there anyway to do this? Of if different gradient is not possible, then what about just different scales? thanks!

A: Here is what it looks like applying @Brian's suggestion to your original example. You may want to rescale the rna and dna value separately, to make the color ranges more comparable.
p = ggplot(df, aes(y=pid, x=type, fill=type, alpha=value)) +
    geom_tile(colour="white", size=1) +
    scale_fill_manual(values=c(dna="salmon", rna="steelblue")) +
    theme_bw() +
    theme(panel.grid=element_blank()) +
    coord_cartesian(expand=FALSE)

A: ggplot(iris, aes(Sepal.Length,
                 Petal.Width,
                 color = Species,
                 alpha = Sepal.Width)) +
  geom_point(size = 4)

Also see: How to create a continuous legend (color bar style) for scale_alpha?


text:
Q: Leaflet WFST style the markers I am working on the point data. I have managed to display the data using the WFST leaflet plugin.
var univ = new L.WFS({
        url: 'http://localhost:8080/geoserver/HEC/wfs',
        typeNS: 'HEC',
        typeName: 'Unis',
        crs: L.CRS.EPSG4326,
        geometryField: 'the_geom',
        showExisting: true,
        maxFeatures: 500,
}).addTo(map);

Now my question is: how do I style my simple markers? I have tried following this link but it's not working for me.
Also maybe because I want to use L.ExtraMarkers.icon for markers.
Even if I alter my code markers do not style as I want them to.:
var univ = new L.WFS({
        url: 'http://localhost:8080/geoserver/HEC/wfs',
        typeNS: 'HEC',
        typeName: 'Unis',
        crs: L.CRS.EPSG4326,
        geometryField: 'the_geom',
        showExisting: true,
        maxFeatures: 500,
        pointToLayer: function (feature, latlng){
                           switch (feature.properties.Sector){
                                   case 'Public' : return L.marker(latlng,{icon: L.ExtraMarkers.icon({icon: 'fa-graduation-cap', markerColor: 'orange', shape: 'circle', prefix: 'fa'})});
                                   case 'Private' : return L.marker(latlng,{icon: L.ExtraMarkers.icon({icon: 'fa-graduation-cap', markerColor: 'cyan', shape: 'circle', prefix: 'fa'})});
    }
}).addTo(map);

Any ideas where I could be going wrong?

A: So I solved it. For the L.WFST point feature, you need to pass two arguments: the options and a GeoJSON which you can use to style the marker. So the code now looks like this:
var univ = new L.WFST(
        {
            url: 'http://localhost:8080/geoserver/HEC/wfs',
            typeNS: 'HEC',
            typeName: 'Unis',
            crs: L.CRS.EPSG4326,
            geometryField: 'the_geom',
            showExisting: true,
            maxFeatures: 500,
        },
    new L.Format.GeoJSON({
        pointToLayer(feature, latlng) {
            switch (feature.properties.Sector){
                case 'Public' : return L.marker(latlng,{icon: L.ExtraMarkers.icon({icon: 'fa-graduation-cap', markerColor: 'orange', shape: 'circle', prefix: 'fa'})});
                case 'Private' : return L.marker(latlng,{icon: L.ExtraMarkers.icon({icon: 'fa-graduation-cap', markerColor: 'cyan', shape: 'circle', prefix: 'fa'})});
            }
        },
    })
).addTo(map);

Posting the answer in case it helps someone else.

A: Additionally, in case this helps someone else too, you can add this line right after the "case Public" and "case Private" lines:
       default: return L.marker(latlng,{icon: L.ExtraMarkers.icon({icon: 'fa-graduation-cap', markerColor: 'green', shape: 'circle', prefix: 'fa'})});

to give a color to the remaining "other values" than Public and Private


text:
Q: can I put password to individual database in mysql? I'm using phpmyadmin/wampserver. Is it possible to add a password on a database?Because my problem is I cannot access the whole thing(http://localhost/phpmyadmin) in my web browser if I put a password on it.

A: instead of doing that, i suggest you put a password to the mysql account you are using in connecting to mysql thru phpmyadmin. then, edit the field relating to the 'password' of the mysql account you are using in the config file of you phpmyadmin app... just a thought!

A: what do you need the password for?  you can create 2 users of the db - one for select/view only privs and another for full privs


text:
Q: Testing the diagonalizability of matrix $B=\left(\begin{smallmatrix}\lambda_1 &a&b\\0&\lambda_1 & c\\0&0& \lambda_2\end{smallmatrix}\right)$ How to show that the matrix
$$B= \left(\begin{array}(\lambda_1 & a & b \\ 0 & \lambda_1 & c\\ 0 & 0 & \lambda_2\end{array}\right)$$
is diagonalizable when $a\neq0$, when $\lambda_1\neq \lambda_2$. How should I work this out? I tried comparing the algebraic and geometric multiplicities of the eigenvalues of $B$ but I didn't succeed in this approach yet.

A: It suffices to note that $B - \lambda_1 I$ has nullity (null-space dimension) $1$ when $a \neq 0$ and $2$ when $a = 0$.  So, the geometric multiplicity of $\lambda_1$ is $1$ when $a \neq 0$ and $2$ when $a = 0$.

A: Clearly, when the dimension is $3$ and the repeated diagonal entries appear only in contiguous blocks, the problem is not really destabilizing.
The case when the dimension is $n$ is studied in If a matrix is triangular, is there a quicker way to tell if it is can be diagonalized?
When the repeated diagonal entries appear only in contiguous blocks, the matrix $B$ is similar to the matrix of diagonal blocks; here $B$ is similar to $diag(\begin{pmatrix}\lambda_1&a\\0&\lambda_1\end{pmatrix},\lambda_2)$. Thus $B$ is diagonalizable iff each block is diagonal; consequently, the complexity of this algorithm is $0$ algebraic operation.
The case when the equal eigenvalues are not grouped is much more difficult. We have not been able to find an algorithm that does the job in $O(n^2)$ and even in $o(n^3)$.
Who can do better?


text:
Q: Focus a Row in a standard DataGridView - not just select I have a standard DataGridView within a WinForms application.
The grid does not allow multi select.
I have a situation where I need to reload the grid's data and return the user back to the row they were focused on.
The code below works in terms of having the row required selected, however, the row is not focused.
The focus indicator stays on the first row of the grid.
How do I move focus to this row rather than just selecting it?  I don't really even need to select it, I just want to put the user to the row that they were on.
var selectedItem = string.Empty;
if (grd.CurrentRow != null)
    selectedItem = ((Item) grd.CurrentRow.DataBoundItem).ItemId;

this.ItemBindingSource.DataSource = null;
get my data
this.ItemBindingSource.DataSource = data;

foreach (DataGridViewRow row in grd.Rows)
{
    if (row != null && (string) row.Cells[0].Value == selectedItem)
    {
        grd.ClearSelection();
        row.Selected = true;
        break;
    }
}

A: Selected property can not obtain the focus. You should use the CurrentCell property.
Please try the below code.
foreach (DataGridViewRow row in grd.Rows)
        {
            if (row != null && (string)row.Cells[0].Value == selectedItem)
            {
                grd.ClearSelection();
                grd.CurrentCell = row.Cells[0];
                break;
            }
        }

Note: I used Cells[0] as an example. You can use any visible cell index.

A: You can do the following:
dataGridView1.FirstDisplayedScrollingRowIndex = dataGridView1.SelectedRows[0].Index;

Which will scroll the grid to the Selected Row.


text:
Q: ASP.NET Core: Session Id Always Changes Today started a brand new ASP.NET Core site.  Followed the instructions to add sessions.  We print out the Session ID on the index page, and it is always unique.
I figure it may be cookie compliance, so I nuked all cookies, both in Chrome's advanced settings and debugger.  But the banner won't reappear for me to accept.
I also tried simply disabling CheckConsentNeeded, but that also had no impact.
Pretty much a duplicate from the default project plus MSDN, except for the tweaks described above:
    // This method gets called by the runtime. Use this method to add services to the container.
    public void ConfigureServices(IServiceCollection services)
    {
        services.AddDistributedMemoryCache();

        services.AddSession(options =>
        {
            // Set a short timeout for easy testing.
            options.IdleTimeout = TimeSpan.FromSeconds(10);
            options.Cookie.HttpOnly = true;
            //options.Cookie.SecurePolicy = CookieSecurePolicy.Always; //require https
            // Make the session cookie essential
            options.Cookie.IsEssential = true;
        });

        services.Configure<CookiePolicyOptions>(options =>
        {
            // This lambda determines whether user consent for non-essential cookies is needed for a given request.
            options.CheckConsentNeeded = context => false; //true;
            options.MinimumSameSitePolicy = SameSiteMode.None;
        });

        services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
    }

    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
    public void Configure(IApplicationBuilder app, IHostingEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }
        else
        {
            app.UseExceptionHandler("/Home/Error");
            app.UseHsts();
        }

        app.UseHttpsRedirection();
        app.UseStaticFiles();
        app.UseCookiePolicy();
        app.UseSession();

        app.UseMvc(routes =>
        {
            routes.MapRoute(
                name: "default",
                template: "{controller=Home}/{action=Index}/{id?}");
        });
    }

A: Wiktor Zychla was correct in the first comment: you must assign any data for the ID to stick.
I simply assigned any data to the session in my controller:
        public IActionResult Index()
        {
            HttpContext.Session.Set("What", new byte[] { 1, 2, 3, 4, 5 });
        }

After that, HttpContext.Session.Id did not change, as one would expect.
As my first foray into ASP.NET Core from ASP.NET Framework, I didn't expect that, and I am sure I won't be the last!

A: Zoop's answer inspired me, but as my comment suggests, it becomes messy should your application have a lot of actions. Based on their answer, I came up with this:
Create a base controller for your application if you don't have one already. Derive all of your existing controllers from that controller. Override the base method that behaves like the old Page_Load from ASP.NET. OnActionExecuting gets invoked before any action code does.
public class MyApplicationController : Controller
{
    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        base.OnActionExecuting(filterContext);
        HttpContext.Session.Set("What", new byte[] { 1, 2, 3, 4, 5 });
    }
}

EDIT: This is an imperfect solution as well. I have abandoned trying to use Session at all in my MVC project. This will work in cases where you don't do anything but GET and POST. (e.g., $ajax will mess this up.)


text:
Q: How can I use a variable to subset an R data.table when the variable is also a column in the data.table? I often want to subset a data.table using a variable that is also a column name in the data.table. For example, imagine I have a data.table with a column called "sex". I also have a variable "sex" defined in my environment (e.g., sex = "male"). If I want to subset the data.table using my sex variable, dt[sex==sex] returns all rows in the data.table because data.table thinks I'm comparing the "sex" column to itself.
Is there a way to tell data.table that I'm using a variable outside of the scope of the column names? I currently have a hacky workaround for this (see below), but there must be a more elegant solution.
library(data.table)
subset_metadata = function(sex){
    .sex = sex # hacky workaround
    meta = data.table(sex=c("male","female","female","male","male"),
                      group=c("1w","2w","1w","2w","2w"),
                      var=rnorm(5))
    meta = meta[sex == .sex]
    return(meta)
}
subset_metadata("male")

A: This is mostly informed by Subsetting data.table using variables with same name as column, but some of them don't work cleanly so they can be rather frustrating.
This isn't much better, but it can be used universally if more than one variable is to be referenced:
subset_metadata = function(sex){
    .env <- environment()
    meta = data.table(sex=c("male","female","female","male","male"),
                      group=c("1w","2w","1w","2w","2w"),
                      var=rnorm(5))
    meta = meta[(sex == get("sex", envir = .env)),]
    return(meta)
}
subset_metadata("male")
#       sex  group        var
#    <char> <char>      <num>
# 1:   male     1w -0.9687163
# 2:   male     2w -0.2033112
# 3:   male     2w -0.4960741

Not yet, but when 1.14.3 is released, it will benefit from the use of env= (see https://rdatatable.gitlab.io/data.table/news/index.html#data-table-v1-14-3-in-development), where I suspect (without verifying yet) that one could use:
meta[ sex == .S, env = list(.S = I(sex)) ]

env is evaluated in a non-dt scope thus will catch expected argument.
I() is used to have "male" character scalar rather than a name of variable as a symbol, otherwise meta[sex==male]. In this simple use case, env is used as kind of renaming variable on the fly.


text:
Q: Database.yml configuration options I would like to know where I can read about valid configuration options for database.yml for ActiveRecord. I know the basic ones like adapter, database, username, password, etc., but I would like to have the full list for each adapter. Where would I find that?

A: I found a gist of database.yml examples using mysql, postgres, and sqlite3, and the Rails 3.2 source code for connection adapters provides good insight as well.
Looks to me that the following are the most widely used options:

*

*adapter

*encoding

*database

*pool

*username

*password

*socket

*host

*port

*timeout

The Rails 3.2 connection_specification.rb file looks like it simply merges any options you include, so I'd say what options you include are dependant on the database adapter you choose to use (lines 58-74):
def connection_url_to_hash(url) # :nodoc:
  config = URI.parse url
  adapter = config.scheme
  adapter = "postgresql" if adapter == "postgres"
  spec = { :adapter  => adapter,
           :username => config.user,
           :password => config.password,
           :port     => config.port,
           :database => config.path.sub(%r{^/},""),
           :host     => config.host }
  spec.reject!{ |_,value| !value }
  if config.query
    options = Hash[config.query.split("&").map{ |pair| pair.split("=") }].symbolize_keys
    spec.merge!(options)
  end
  spec
end


text:
Q: Implementing event sourcing on credit transaction system Currently we have a system that handles crediting and debiting of credits.
It stores each action as a transaction event in the database, but all in all we still update a "credit_bank" table that represents the current balance of the user.
          Table "public.credit_bank"
     Column     |          Type          | Modifiers
----------------+------------------------+-----------
 id             | bigint                 | not null
 user_id        | bigint                 |
 currency       | character varying(255) |
 amount         | numeric(40,10)         | not null

                 Table "public.transaction"
      Column      |            Type             | Modifiers
------------------+-----------------------------+-----------
 id               | bigint                      | not null
 amount           | numeric(40,10)              | not null
 credit_bank_id   | bigint                      |
 status           | character varying(255)      | not null
 transaction_date | timestamp without time zone |
 type             | character varying(255)      | not null

Since we process lots of transactions at a time, we were forced to lock the credit table every time we update it to avoid stale issues.
Then I came across event sourcing. Is that pattern good to apply in this scenario?
I'm really new to this, so please let me know if I have something wrong.
In my understanding, if we use event sourcing, we would not need to store the state of the "credit_bank", instead use events to come up with the state, or use snapshots. But how would that ensure that the current balance is still sufficient.
Also, if we get the state by processing events everytime, would that be bad for performance?

A:
Is that pattern good to apply in this scenario?

This sounds like an example I use when trying to describe some corner cases, so I think so.

In my understanding, if we use event sourcing, we would not need to store the state of the "credit_bank", instead use events to come up with the state, or use snapshots. But how would that ensure that the current balance is still sufficient.

Are those transactions come from your business model, or are they things that are reported to you by banks out in the world somewhere.  Because if it's the latter, then you need to give some thought to what "current" balance means -- you are being queried now, after a remote bank has dispatched a transaction to you but before that transaction gets recorded in your database.  Is the balance still "current"?
With information coming from "somewhere else", we don't usually make raw assumptions about time.  So not, "the current balance", but "the balance at time=t".  Or "the balance at time=t1, when the most recent available update was at time=t2"
In other words, you starting including temporal modeling, and discussing with the business whether the available latency is "good enough", what the costs are to making that latency shorter, what the costs are to not making the latency shorter, and so on.

if we get the state by processing events everytime, would that be bad for performance?

It might be.  Often, event sourcing is coupled with cqrs; which is another sort of latency tradeoff -- the responsibility for updating the model is separated from the responsibility for querying the model, with a bit of plumbing to copy new data from the update model to the query model.

A:
Since we process lots of transactions at a time, we were forced to lock the credit table every time we update it to avoid stale issues.

You probably needed to use database transactions (I'm not refering to financial transactions) in order to keep the two tables consistent. That hurts performance and scalability.

Then I came across event sourcing. Is that pattern good to apply in this scenario?

Event sourcing is a perfect fit for append-only systems, so yes.

In my understanding, if we use event sourcing, we would not need to store the state of the "credit_bank", instead use events to come up with the state, or use snapshots. But how would that ensure that the current balance is still sufficient.

Before every withdrawMoneyFromTheAccount command, you replay all the financial transactions on that account and compute the current balance; then you compare the transaction amount to that balance and permit or reject the transaction.

Also, if we get the state by processing events everytime, would that be bad for performance?

For locking, instead of using pessimistic locking (like transactions) you should use optimistic locking using a version column. The real benefit regarding performance is gained because using Event sourcing you need to protect only one table, the event store, and not two that must be kept in sync, like in your current architecture.


text:
Q: Output errors on advancved parameters panel I have no idea if the issue is regarding a update on php version on the server or some kind of attack I got in my store, but in my "advanced parameters" panel is outputting some errors, above I leave the information. Does anybody had some kind of similar issue?
PrestaShop™ 1.5.4.1

Verify Settings
Parameters required: OK
Optional parameters: Please fix the following errors
pdo_mysql

List of changed files

Changed/missing files have been detected.
Ficheiros em falta (6)
modules/blocknewsletter/mails/en/index.php
modules/blockwishlist/mails/en/index.php
modules/followup/mails/en/index.php
modules/mailalerts/mails/en/index.php
modules/referralprogram/mails/en/index.php
modules/sendtoafriend/mails/en/index.php

Ficheiros actualizados (64)
classes/controller/FrontController.php
modules/bankwire/bankwire.jpg
modules/bankwire/views/templates/hook/payment.tpl
modules/blocknewsletter/blocknewsletter.css
modules/blocknewsletter/blocknewsletter.php
modules/blocknewsletter/index.php
modules/blocknewsletter/controllers/index.php
modules/blocknewsletter/controllers/front/index.php
modules/blocknewsletter/controllers/front/verification.php
modules/blocknewsletter/img/index.php
modules/blocknewsletter/img/icon/index.php
modules/blocknewsletter/mails/index.php
modules/blocknewsletter/mails/en/newsletter_conf.html
modules/blocknewsletter/mails/en/newsletter_verif.html
modules/blocknewsletter/mails/en/newsletter_voucher.html
modules/blocknewsletter/translations/index.php
modules/blocknewsletter/views/index.php
modules/blocknewsletter/views/templates/index.php
modules/blocknewsletter/views/templates/front/index.php
modules/blocknewsletter/views/templates/front/verification_execution.tpl
modules/blocknewsletter/views/templates/hook/blocknewsletter.tpl
modules/blocknewsletter/views/templates/hook/index.php
modules/blockwishlist/mails/en/wishlink.html
modules/blockwishlist/mails/en/wishlist.html
modules/cashondelivery/cashondelivery.jpg
modules/cashondelivery/views/templates/hook/payment.tpl
modules/editorial/EditorialClass.php
modules/editorial/editorial.css
modules/editorial/editorial.php
modules/editorial/editorial.tpl
modules/editorial/index.php
modules/editorial/translations/index.php
modules/followup/mails/en/followup_1.html
modules/followup/mails/en/followup_2.html
modules/followup/mails/en/followup_3.html
modules/followup/mails/en/followup_4.html
modules/mailalerts/MailAlert.php
modules/mailalerts/index.php
modules/mailalerts/mailalerts-account.php
modules/mailalerts/mailalerts-ajax.php
modules/mailalerts/mailalerts-extra.php
modules/mailalerts/mailalerts.php
modules/mailalerts/controllers/index.php
modules/mailalerts/controllers/front/account.php
modules/mailalerts/controllers/front/actions.php
modules/mailalerts/controllers/front/index.php
modules/mailalerts/img/index.php
modules/mailalerts/mails/index.php
modules/mailalerts/mails/en/customer_qty.html
modules/mailalerts/mails/en/new_order.html
modules/mailalerts/mails/en/productcoverage.html
modules/mailalerts/mails/en/productoutofstock.html
modules/mailalerts/translations/index.php
modules/mailalerts/views/index.php
modules/mailalerts/views/templates/index.php
modules/mailalerts/views/templates/front/index.php
modules/mailalerts/views/templates/front/mailalerts-account.tpl
modules/mailalerts/views/templates/hook/index.php
modules/mailalerts/views/templates/hook/my-account.tpl
modules/mailalerts/views/templates/hook/product.tpl
modules/referralprogram/mails/en/referralprogram-congratulations.html
modules/referralprogram/mails/en/referralprogram-invitation.html
modules/referralprogram/mails/en/referralprogram-voucher.html
modules/sendtoafriend/mails/en/send_to_a_friend.html

A: Please check if _PS_DEBUG_PROFILING_ is enabled on your store. You can check the same in the following file on your store:
/config/defines.inc.php
Search for _PS_DEBUG_PROFILING_ and see if the value for it is 'true' or 'false'
It should be 'false', change it if it is not and see if the problem is solved.


text:
Q: call jmx operation on a local running process I have a java process on a linux server, which runs with this option: -Dcom.sun.management.jmxremote
So I cannot just connect to this process via jconsole running on my local pc (because neither port nor -Dcom.sun.management.jmxremote.ssl=false options are set up).
But still, how can I connect to the application and run some operations over some of its MBeans? It this possible? I have a ssh access to the server and would be able to run it "locally" on the server (but not changing the options unfortunately)

A: According to JMX documentation the -Dcom.sun.management.jmxremote option
Enables the JMX remote agent and local monitoring via JMX connector published on a private
interface used by jconsole. The jconsole tool can use this connector if it is executed by
the same user ID as the user ID that started the agent. No password or access files are
checked for requests coming via this connector.

The naming is a bit unfortunate because it in fact enables the local monitoring only.
Since you can not change the options but can access the server via SSH the only option is to use X server forwarding (ssh -X ...) and run jconsole (or better yet jvisualvm which has specific optimisations for running remotely).


text:
Q: Documents for MDM Integration in iPhone Can any one help me out how to do MDM Integration in iPhone from client prespective without using APN. Because I want to do an enterprise application which need to list all the installed apps in iPhone and also should allow the user to delete some apps from current application.

A: *

*You need to have an enterprise developer account to get the documents. If you can't get an enterprise account, you can't get the documents.

*Apple has only given the iOS MDM documents to a select few enterprise developers around the world. You won't get access to them unless you can prove to Apple your business is in the field of Device Management and/or Mobility.

*MDM uses apns. You have to use apns.

*You can't get an application list without MDM.

*You can't delete applications from inside an app.

*You're not going to get the documents from Apple.


text:
Q: Angular, Using Elvis sing in [(ngModel)] with mat-form-field I want to achieve when object or id is null don't show anything, be empty so when user want to update, it can do it later on..
<mat-form-field appearance="legacy">
  <mat-label>LOCATION</mat-label>
    <mat-select name="obj"  [(ngModel)]="exampleObj.obj.id" >
      <ng-container *ngFor="let obj of objs">
      <mat-option [value]="obj.id">
        {{obj.location}}
      </mat-option>
    </ng-container>
  </mat-select>
</mat-form-field>

The error is ctx.exampleObj.obj is null.
The Elvis sing (?) doesn't work with mat-form-field.
Can someone please help me?

A: I fixed it. Just added an empty string in properties of obj. for example:
obj = { id : ' ' , location : ' ' }


text:
Q: Deploy a website in one country I have a website and i need to deploy it in a single country for example Lebanon. In other words, any request that comes to the website from any other country should not be responded to.
I think I may use the IP address of the request and know from which country it was generated.
How can I do this in C#.

A:
I think I may use the IP address of the request and know from which country it was generated

No, you dont. Illusion.

*

*you can not know which country a request comes frmo, only where the IP address is registere, pretty much. More information is avaialble parsing the reverse dns SOMETIMES if you are smart at this.

*This ignores little issuesl ike large international providers that may use a central pool of addresses, like VPN providers etc. Or satellite phone providers (which may be used out of a country but not be resident there).

At the end this will be of RELATIVELY limtied use, depending what your exact busienss case is it may be totally useless.

How can I do this in C#.

Programming.
Get a GeoIP database (look up the term in google, a provider will show up, otherwise try it in combination with "maxmind"). THen query the IP against the database. Decide how to handle "maybe" scenarios like international businesses. Example... IBM has address space. They use it for all their oprations. How you want to deal with this?

A: One thing you can do to encourage local indexing and participation is deploy your website with a Lebanon country code suffix.
www.example.co.lb

Here's a list of country suffix domains.