text:
Q: How does the "this" keyword in Java inheritance work? In the below code snippet, the result is really confusing.
public class TestInheritance {
    public static void main(String[] args) {
        new Son();
        /*
        Father father = new Son();
        System.out.println(father); //[1]I know the result is "I'm Son" here
        */
    }
}

class Father {
    public String x = "Father";

    @Override
    public String toString() {
       return "I'm Father";
    }

    public Father() {
        System.out.println(this);//[2]It is called in Father constructor
        System.out.println(this.x);
    }
}

class Son extends Father {
    public String x = "Son";

    @Override
    public String toString() {
        return "I'm Son";
    }
}

The result is
I'm Son
Father

Why is "this" pointing to Son in the Father constructor, but "this.x" is pointing to "x" field in Father. How is the "this" keyword working?
I know about the polymorphic concept, but won't there be different between [1] and [2]? What's going on in memory when new Son() is triggered?

A: As other stated, you cannot override fields, you can only hide them. See JLS 8.3. Field Declarations

If the class declares a field with a certain name, then the declaration of that field is said to hide any and all accessible declarations of fields with the same name in superclasses, and superinterfaces of the class.
In this respect, hiding of fields differs from hiding of methods (§8.4.8.3), for there is no distinction drawn between static and non-static fields in field hiding whereas a distinction is drawn between static and non-static methods in method hiding.
A hidden field can be accessed by using a qualified name (§6.5.6.2) if it is static, or by using a field access expression that contains the keyword super (§15.11.2) or a cast to a superclass type.
In this respect, hiding of fields is similar to hiding of methods.
A class inherits from its direct superclass and direct superinterfaces all the non-private fields of the superclass and superinterfaces that are both accessible to code in the class and not hidden by a declaration in the class.

You can access Father's hidden fields from Son's scope using super keyword, but the opposite is impossible since Father class is not aware of its subclasses.

A: While methods can be overridden, attributes can be hidden.
In your case, the attribute x is hidden: in your Son class, you can't access the Father's x value unless you use the super keyword. The Father class doesn't know about the Son's x attribute.
In the opposit, the toString() method is overriden: the implementation that will always be called is the one of the instantiated class (unless it does not override it), i.e. in your case Son, whatever the variable's type (Object, Father...).

A: All member functions are polymorphic in Java by default. That means when you call this.toString() Java uses dynamic binding to resolve the call, calling the child version. When you access the member x, you access the member of your current scope (the father) because members are not polymorphic.

A: This is a behaviour done specially to have access to private members. So this.x looks at the variable X which is declared for Father, but when you pass this as a parameter to System.out.println in a method in Father - it looks at the method to call depending on the type of the parameter - in your case Son.
So how do you call the super classes method? Using super.toString(), etc.
From Father it cannot access the x variable of Son.

A: Polymorphic method invocations apply only to instance methods. You can always refer to an object with a more general reference variable type ( a superclass or interface ), but at runtime, the ONLY things that are dynamically selected based on the actual object (rather than the reference type) are instance methods NOT STATIC METHODS. NOT VARIABLES. Only overridden instance methods are dynamically invoked based on the real object's type.
So variable x has not polymorphic behaviour because IT WILL NOT BE SELECTED DYNAMICALLY AT RUNTIME.
Explaining your code :
System.out.println(this);

The Object type is Son so toString() method's Overridden Son version will be invoked.
System.out.println(this.x);

Object type is not in picture here, this.x is in Father class so x variable's Father version will be printed.
See more at: Polymorphism in java

A: Two things are going on here, let's look at them:
First of all, you are creating two different fields. Taking a look at a (very isolated) chunks of the bytecode, you see this:
class Father {
  public java.lang.String x;

  // Method descriptor #17 ()V
  // Stack: 2, Locals: 1
  public Father();
        ...
    10  getstatic java.lang.System.out : java.io.PrintStream [23]
    13  aload_0 [this]
    14  invokevirtual java.io.PrintStream.println(java.lang.Object) : void [29]
    17  getstatic java.lang.System.out : java.io.PrintStream [23]
    20  aload_0 [this]
    21  getfield Father.x : java.lang.String [21]
    24  invokevirtual java.io.PrintStream.println(java.lang.String) : void [35]
    27  return
}

class Son extends Father {

  // Field descriptor #6 Ljava/lang/String;
  public java.lang.String x;
}

Important are lines 13, 20 and 21; the others represent the System.out.println(); itself, or the implicit return;. aload_0 loads the this reference, getfield retrieves a field value from an object, in this case, from this. What you see here is that the field name is qualified: Father.x. In the one line in Son, you can see there is a separate field. But Son.x is never used; only Father.x is.
Now, what if we remove Son.x and instead add this constructor:
public Son() {
    x = "Son";
}

First a look at the bytecode:
class Son extends Father {
  // Field descriptor #6 Ljava/lang/String;
  public java.lang.String x;

  // Method descriptor #8 ()V
  // Stack: 2, Locals: 1
  Son();
     0  aload_0 [this]
     1  invokespecial Father() [10]
     4  aload_0 [this]
     5  ldc <String "Son"> [12]
     7  putfield Son.x : java.lang.String [13]
    10  return
}

Lines 4, 5 and 7 look good: this and "Son" are loaded, and the field is set with putfield. Why Son.x? because the JVM can find the inherited field. But it's important to note that even though the field is referenced as Son.x, the field found by the JVM is actually Father.x.
So does it give the right output? Unfortunately, no:
I'm Son
Father

The reason is the order of statements. Lines 0 and 1 in the bytecode are the implicit super(); call, so the order of statements is like this:
System.out.println(this);
System.out.println(this.x);
x = "Son";

Of course it's gonna print "Father". To get rid of that, a few things could be done.
Probably the cleanest is: don't print in the constructor! As long as the constructor hasn't finished, the object is not fully initialized. You are working on the assumption that, since the printlns are the last statements in your constructor, your object is complete. As you have experienced, this is not true when you have subclasses, because the superclass constructor will always finish before your subclass has a chance to initialize the object.
Some see this as a flaw in the concept of constructors itself; and some languages don't even use constructors in this sense. You could use an init() method instead. In ordinary methods, you have the advantage of polymorphism, so you can call init() on a Father reference, and Son.init() is invoked; whereas, new Father() always creates a Father object. (of course, in Java you still need to call the right constructor at some point).
But I think what you need is something like this:
class Father {
    public String x;

    public Father() {
        init();
        System.out.println(this);//[2]It is called in Father constructor
        System.out.println(this.x);
    }

    protected void init() {
        x = "Father";
    }

    @Override
    public String toString() {
        return "I'm Father";
    }
}

class Son extends Father {
    @Override
    protected void init() {
        //you could do super.init(); here in cases where it's possibly not redundant
        x = "Son";
    }

    @Override
    public String toString() {
        return "I'm Son";
    }
}

I don't have a name for it, but try it out. It will print
I'm Son
Son

So what's going on here? Your topmost constructor (that of Father) calls an init() method, which is overridden in a subclass. As all constructor call super(); first, they are effectively executed superclass to subclass. So if the topmost constructor's first call is init(); then all of the init happens before any constructor code. If your init method fully initializes the object, then all constructors can work with an initialized object. And since init() is polymorphic, it can even initialize the object when there are subclasses, unlike with the constructor.
Note that init() is protected: subclasses will be able to call and override it, but classes in other package won't be able to call it. That's a slight improvement over public and should be considered for x too.

A: This is commonly referred to as shadowing. Note your class declarations:
class Father {
    public String x = "Father";

and
class Son extends Father {
    public String x = "Son";

This creates 2 distinct variables named x when you create an instance of Son. One x belongs to the Father superclass, and the second x belongs to the Son subclass. Based on the output, we can see that when in the Father scope, this accesses the Father's x instance variable. So the behavior is not related to "what this points to"; it's a result of how the runtime searches for instance variables. It only goes up the class hierarchy to search for variables. A class can only reference variables from itself and its parent classes; it can't access variables from its child classes directly because it doesn't know anything about its children.
To obtain the polymorphic behavior you want, you should only declare x in Father:
class Father {
    public String x;

    public Father() {
        this.x = "Father"
    }

and
class Son extends Father {
    public Son() {
        this.x = "Son"
    }

This article discussed the behavior you're experiencing exactly: http://www.xyzws.com/Javafaq/what-is-variable-hiding-and-shadowing/15.


text:
Q: Draw node shape and node color by attribute using networkx In a Graph G i have a set of nodes. Some of them have a Attribute Type which can be MASTER or  DOC. Others do not have the a Type define:
>>> import networkx as nx
>>> import matplotlib.pyplot as plt
>>> G=nx.Graph()
[...]
>>> G.node['ART1']
{'Type': 'MASTER'}
>>> G.node['ZG1']
{'Type': 'DOC'}
>>> G.node['MG1']
{}

Afterwards I plot the Graph using
>>> nx.draw(G,with_labels = True)
>>> plt.show()

Now i get a graph with red Circles. How can I get e.g.
blue cylces for ART
red squares for DOC
purple cylces for everything undefined
in my plot?

A: There are various ways to select nodes based on their attributes.  Here is how to do it with get_node_attributes and a list comprehension to take the subset.  The drawing functions then accept a nodelist argument.
It should be easy enough to extend to a broader set of conditions or modify the appearance of each subset as suits your needs based on this approach
import networkx as nx

# define a graph, some nodes with a "Type" attribute, some without.
G = nx.Graph()
G.add_nodes_from([1,2,3], Type='MASTER')
G.add_nodes_from([4,5], Type='DOC')
G.add_nodes_from([6])

# extract nodes with specific setting of the attribute
master_nodes = [n for (n,ty) in \
    nx.get_node_attributes(G,'Type').iteritems() if ty == 'MASTER']
doc_nodes = [n for (n,ty) in \
    nx.get_node_attributes(G,'Type').iteritems() if ty == 'DOC']
# and find all the remaining nodes.
other_nodes = list(set(G.nodes()) - set(master_nodes) - set(doc_nodes))

# now draw them in subsets  using the `nodelist` arg
pos = nx.spring_layout(G)
nx.draw_networkx_nodes(G, pos, nodelist=master_nodes, \
    node_color='red', node_shape='o')
nx.draw_networkx_nodes(G, pos, nodelist=doc_nodes, \
    node_color='blue', node_shape='o')
nx.draw_networkx_nodes(G, pos, nodelist=other_nodes, \
    node_color='purple', node_shape='s')

redpajama_set_name: RedPajamaStackExchange


text:
Q: Maven Projection creation error I am trying to learn Maven.
I have following JDK and Maven version
C:\Users\iXXXXXX>java -version
java version "1.8.0_171"
Java(TM) SE Runtime Environment (build 1.8.0_171-b11)
Java HotSpot(TM) Client VM (build 25.171-b11, mixed mode)

C:\Users\iXXXXXX>mvn -version
Apache Maven 3.5.3 (3383c37e1f9e9b3bc3df5050c29c8aff9f295297; 2018-02-24T14:49:0
5-05:00)
Maven home: C:\Users\iXXXXXX\Documents\apache-maven-3.5.3\bin\..
Java version: 1.8.0_171, vendor: Oracle Corporation
Java home: C:\Program Files (x86)\Java\jdk1.8.0_171\jre
Default locale: en_US, platform encoding: Cp1252
OS name: "windows 7", version: "6.1", arch: "x86", family: "windows"

I have also set the Environment variables - JAVA_HOME, M2_HOME and edited the path variable to both the bin folders.
I am trying to create a new Maven Project in Eclipse in two ways but not successful. Looks like access or security issue but do not know how to resolve.

*

*I am getting following error when I try to  create from File  New  Maven Project  Entering Group Id and Artifact Id  Finish.

"Could not resolve archetype org.apache.maven.archetypes:maven-archetype-quickstart:1.1 from any of the configured repositories.
Could not write artifact lastUpdated status
C:\Users\i716181\.m2\repository\org\apache\maven\archetypes\maven-archetype-quickstart\1.1\m2e-lastUpdated.properties (Access is denied)."

*I tried to create a simple project and then convert to Maven. This is successful but when I try to add dependency for selenium using the Add dependency wizard – I get following error

Failed to read artifact descriptor for org.seleniumhq.selenium:selenium-java:jar:3.12.0

org.eclipse.aether.resolution.ArtifactDescriptorException: Failed to read artifact descriptor for org.seleniumhq.selenium:selenium-java:jar:3.12.0
    at org.apache.maven.repository.internal.DefaultArtifactDescriptorReader.loadPom(DefaultArtifactDescriptorReader.java:282)
    at org.apache.maven.repository.internal.DefaultArtifactDescriptorReader.readArtifactDescriptor(DefaultArtifactDescriptorReader.java:198)
    at org.eclipse.aether.internal.impl.DefaultDependencyCollector.resolveCachedArtifactDescriptor(DefaultDependencyCollector.java:535)
    at org.eclipse.aether.internal.impl.DefaultDependencyCollector.getArtifactDescriptorResult(DefaultDependencyCollector.java:519)
    at org.eclipse.aether.internal.impl.DefaultDependencyCollector.processDependency(DefaultDependencyCollector.java:409)
    at org.eclipse.aether.internal.impl.DefaultDependencyCollector.processDependency(DefaultDependencyCollector.java:363)
    at org.eclipse.aether.internal.impl.DefaultDependencyCollector.process(DefaultDependencyCollector.java:351)
    at org.eclipse.aether.internal.impl.DefaultDependencyCollector.collectDependencies(DefaultDependencyCollector.java:254)
    at org.eclipse.aether.internal.impl.DefaultRepositorySystem.collectDependencies(DefaultRepositorySystem.java:316)
    at org.apache.maven.project.DefaultProjectDependenciesResolver.resolve(DefaultProjectDependenciesResolver.java:172)
    at org.apache.maven.project.DefaultProjectBuilder.resolveDependencies(DefaultProjectBuilder.java:215)
    at org.apache.maven.project.DefaultProjectBuilder.build(DefaultProjectBuilder.java:188)
    at org.apache.maven.project.DefaultProjectBuilder.build(DefaultProjectBuilder.java:119)
    at org.eclipse.m2e.core.internal.embedder.MavenImpl.readMavenProject(MavenImpl.java:636)
    at org.eclipse.m2e.core.internal.project.registry.DefaultMavenDependencyResolver.resolveProjectDependencies(DefaultMavenDependencyResolver.java:63)
    at org.eclipse.m2e.core.internal.project.registry.ProjectRegistryManager.refreshPhase2(ProjectRegistryManager.java:530)
    at org.eclipse.m2e.core.internal.project.registry.ProjectRegistryManager$3.call(ProjectRegistryManager.java:492)
    at org.eclipse.m2e.core.internal.project.registry.ProjectRegistryManager$3.call(ProjectRegistryManager.java:1)
    at org.eclipse.m2e.core.internal.embedder.MavenExecutionContext.executeBare(MavenExecutionContext.java:177)
    at org.eclipse.m2e.core.internal.embedder.MavenExecutionContext.execute(MavenExecutionContext.java:151)
    at org.eclipse.m2e.core.internal.project.registry.ProjectRegistryManager.refresh(ProjectRegistryManager.java:496)
    at org.eclipse.m2e.core.internal.project.registry.ProjectRegistryManager.refresh(ProjectRegistryManager.java:351)
    at org.eclipse.m2e.core.internal.project.registry.ProjectRegistryManager.refresh(ProjectRegistryManager.java:298)
    at org.eclipse.m2e.core.internal.builder.MavenBuilder$BuildMethod.getProjectFacade(MavenBuilder.java:154)
    at org.eclipse.m2e.core.internal.builder.MavenBuilder$BuildMethod$1.call(MavenBuilder.java:89)
    at org.eclipse.m2e.core.internal.embedder.MavenExecutionContext.executeBare(MavenExecutionContext.java:177)
    at org.eclipse.m2e.core.internal.embedder.MavenExecutionContext.execute(MavenExecutionContext.java:151)
    at org.eclipse.m2e.core.internal.embedder.MavenExecutionContext.execute(MavenExecutionContext.java:99)
    at org.eclipse.m2e.core.internal.builder.MavenBuilder$BuildMethod.execute(MavenBuilder.java:86)
    at org.eclipse.m2e.core.internal.builder.MavenBuilder.build(MavenBuilder.java:200)
    at org.eclipse.core.internal.events.BuildManager$2.run(BuildManager.java:735)
    at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42)
    at org.eclipse.core.internal.events.BuildManager.basicBuild(BuildManager.java:206)
    at org.eclipse.core.internal.events.BuildManager.basicBuild(BuildManager.java:246)
    at org.eclipse.core.internal.events.BuildManager$1.run(BuildManager.java:301)
    at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42)
    at org.eclipse.core.internal.events.BuildManager.basicBuild(BuildManager.java:304)
    at org.eclipse.core.internal.events.BuildManager.basicBuildLoop(BuildManager.java:360)
    at org.eclipse.core.internal.events.BuildManager.build(BuildManager.java:383)
    at org.eclipse.core.internal.events.AutoBuildJob.doBuild(AutoBuildJob.java:142)
    at org.eclipse.core.internal.events.AutoBuildJob.run(AutoBuildJob.java:232)
    at org.eclipse.core.internal.jobs.Worker.run(Worker.java:56)
Caused by: org.eclipse.aether.resolution.ArtifactResolutionException: Could not transfer artifact org.seleniumhq.selenium:selenium-java:pom:3.12.0 from/to central (https://repo.maven.apache.org/maven2): sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
    at org.eclipse.aether.internal.impl.DefaultArtifactResolver.resolve(DefaultArtifactResolver.java:444)
    at org.eclipse.aether.internal.impl.DefaultArtifactResolver.resolveArtifacts(DefaultArtifactResolver.java:246)
    at org.eclipse.aether.internal.impl.DefaultArtifactResolver.resolveArtifact(DefaultArtifactResolver.java:223)
    at org.apache.maven.repository.internal.DefaultArtifactDescriptorReader.loadPom(DefaultArtifactDescriptorReader.java:267)
    ... 41 more
Caused by: org.eclipse.aether.transfer.ArtifactTransferException: Could not transfer artifact org.seleniumhq.selenium:selenium-java:pom:3.12.0 from/to central (https://repo.maven.apache.org/maven2): sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
    at io.takari.aether.connector.AetherRepositoryConnector$2.wrap(AetherRepositoryConnector.java:904)
    at io.takari.aether.connector.AetherRepositoryConnector$2.wrap(AetherRepositoryConnector.java:1)
    at io.takari.aether.connector.AetherRepositoryConnector$GetTask.flush(AetherRepositoryConnector.java:678)
    at io.takari.aether.connector.AetherRepositoryConnector.get(AetherRepositoryConnector.java:310)
    at org.eclipse.aether.internal.impl.DefaultArtifactResolver.performDownloads(DefaultArtifactResolver.java:520)
    at org.eclipse.aether.internal.impl.DefaultArtifactResolver.resolve(DefaultArtifactResolver.java:421)
    ... 44 more
Caused by: javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
    at sun.security.ssl.Alerts.getSSLException(Unknown Source)
    at sun.security.ssl.SSLSocketImpl.fatal(Unknown Source)
    at sun.security.ssl.Handshaker.fatalSE(Unknown Source)
    at sun.security.ssl.Handshaker.fatalSE(Unknown Source)
    at sun.security.ssl.ClientHandshaker.serverCertificate(Unknown Source)
    at sun.security.ssl.ClientHandshaker.processMessage(Unknown Source)
    at sun.security.ssl.Handshaker.processLoop(Unknown Source)
    at sun.security.ssl.Handshaker.process_record(Unknown Source)
    at sun.security.ssl.SSLSocketImpl.readRecord(Unknown Source)
    at sun.security.ssl.SSLSocketImpl.performInitialHandshake(Unknown Source)
    at sun.security.ssl.SSLSocketImpl.startHandshake(Unknown Source)
    at sun.security.ssl.SSLSocketImpl.startHandshake(Unknown Source)
    at okhttp3.internal.connection.RealConnection.connectTls(RealConnection.java:268)
    at okhttp3.internal.connection.RealConnection.establishProtocol(RealConnection.java:238)
    at okhttp3.internal.connection.RealConnection.connect(RealConnection.java:149)
    at okhttp3.internal.connection.StreamAllocation.findConnection(StreamAllocation.java:192)
    at okhttp3.internal.connection.StreamAllocation.findHealthyConnection(StreamAllocation.java:121)
    at okhttp3.internal.connection.StreamAllocation.newStream(StreamAllocation.java:100)
    at okhttp3.internal.connection.ConnectInterceptor.intercept(ConnectInterceptor.java:42)
    at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:92)
    at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:67)
    at okhttp3.internal.cache.CacheInterceptor.intercept(CacheInterceptor.java:93)
    at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:92)
    at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:67)
    at okhttp3.internal.http.BridgeInterceptor.intercept(BridgeInterceptor.java:93)
    at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:92)
    at okhttp3.internal.http.RetryAndFollowUpInterceptor.intercept(RetryAndFollowUpInterceptor.java:120)
    at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:92)
    at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:67)
    at okhttp3.RealCall.getResponseWithInterceptorChain(RealCall.java:185)
    at okhttp3.RealCall.execute(RealCall.java:69)
    at io.takari.aether.okhttp.OkHttpAetherClient.execute(OkHttpAetherClient.java:207)
    at io.takari.aether.okhttp.OkHttpAetherClient.get(OkHttpAetherClient.java:153)
    at io.takari.aether.connector.AetherRepositoryConnector$GetTask.getResponse(AetherRepositoryConnector.java:672)
    at io.takari.aether.connector.AetherRepositoryConnector$GetTask.resumableGet(AetherRepositoryConnector.java:587)
    at io.takari.aether.connector.AetherRepositoryConnector$GetTask.run(AetherRepositoryConnector.java:453)
    at io.takari.aether.connector.AetherRepositoryConnector.get(AetherRepositoryConnector.java:304)
    ... 46 more
Caused by: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
    at sun.security.validator.PKIXValidator.doBuild(Unknown Source)
    at sun.security.validator.PKIXValidator.engineValidate(Unknown Source)
    at sun.security.validator.Validator.validate(Unknown Source)
    at sun.security.ssl.X509TrustManagerImpl.validate(Unknown Source)
    at sun.security.ssl.X509TrustManagerImpl.checkTrusted(Unknown Source)
    at sun.security.ssl.X509TrustManagerImpl.checkServerTrusted(Unknown Source)
    ... 79 more
Caused by: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
    at sun.security.provider.certpath.SunCertPathBuilder.build(Unknown Source)
    at sun.security.provider.certpath.SunCertPathBuilder.engineBuild(Unknown Source)
    at java.security.cert.CertPathBuilder.build(Unknown Source)
    ... 85 more"


text:
Q: Support TLSv1.0 or SSLv3 on Android in React Native I want to fetch a site which is using TLSv1 protocol, but when I use fetch to request, react native will throw a error: Network request failed.
I just normally fetch like this:
fetch('https://stu255.ntust.edu.tw/ntust_stu/stu.aspx')
  .then((r) => { return r.text(); })
  .catch((e) => { console.error(e); })
  .then((r) => { console.warn(r); });

And the certification of that site is:
---
SSL handshake has read 3076 bytes and written 632 bytes
---
New, TLSv1/SSLv3, Cipher is RC4-SHA
Server public key is 2048 bit
Secure Renegotiation IS NOT supported
Compression: NONE
Expansion: NONE
No ALPN negotiated
SSL-Session:
    Protocol  : TLSv1
    Cipher    : RC4-SHA
    Session-ID: D118    0000199B804B84C7EC06FF6CAFEBEB96617DA1721EFA42FD2CD1B350350C
    Session-ID-ctx:
    Master-Key: A93C9E54CEAB4235C64EB3A0799CA3761F13EACEA0B0FE34D377DBD615A666CE13EB7E58DF18E96E30AA1C97644CF050
    Start Time: 1530941378
    Timeout   : 300 (sec)
    Verify return code: 0 (ok)
---

Finally, I found that react native use okhttp to implement network in Android, but doesn't support TLSv1.0 by default.
I wonder how to enable TLSv1.0 on Android?
Thanks.


text:
Q: possible to go through all the controls in a form to check if they have been filled or not on submitting the form to sharepoint? I have built a form library in sharepoint, which will contain an info path form inside it.
I wonder if it is possible in any way to iterate through all the controls inside an info path without the need of external c# code, when a specific button has been clicked. I.e. only using info path rules engine. I need to do the following because i want to create a bitmask representation of the form. such that it would be possible to see and check which fields have been filled and which others are yet to be filled for a specific instance of the form


text:
Q: Graph db: how to trigger on event? We are looking to store Windows process tree information in a graph database.
We have an endpoint detection tool that collects process creation and deletion information. For example, the process id, the command that started the process, the parent process and so on.
The data will be loaded into the graph database in real-time.
Is there a way in Neo4j to trigger an event anytime we see "iexplore.exe" as the parent of processes such as "powershell.exe" or "cmd.exe"? In some cases, there may be several other processes between iexplore and powershell/cmd.
For example: the attacker exploits a vulnerability in IE, drops of a file on disk, executes it, and then uses powershell.exe.
Does graph databases provide us the ability to build in rules to capture more complex events like that?

A: You can use apoc triggers for set trigger and apoc.es.postRaw  for external API call. For example:
CALL apoc.trigger.add(
        'iexplorer',
        'MATCH (P:Process {name:"iexplore.exe"})-[:parent_of*]->(C:Process)
           WHERE C.name IN ["powershell.exe", "cmd.exe"]
         WITH collect(distinct id(P)) as ids
         CALL apoc.es.postRaw("http://localhost", "neo4jevent", ids)  yield value
         RETURN value',
         '{phase:'after'}'
)


text:
Q: gsl, Multidimensional Minimization I like to use of the gsl library for minimizing two functions.
My functions are f1 (x, y) = (x-y-2) ^2 and f2 (x, y) = (x-y) ^2.
How can I initialize two functions to minimizer of gsl operate on?


text:
Q: Plot a 2D binary matrix as a line in matplotlib using plot? I have a 2D matrix containing zeros and ones. The ones define a shape from which I want to plot its contour/edge on a matplotlib figure. The initial 2D binary matrix:
[[0 0 0 0 0 0 0 0 0 0 0]
 [0 0 0 1 1 1 1 1 0 0 0]
 [0 0 0 1 1 1 1 1 0 0 0]
 [0 0 0 1 1 1 1 1 0 0 0]
 [0 0 0 1 1 1 1 1 0 0 0]
 [0 0 0 0 0 0 0 0 0 0 0]]

I found here the method to get the corresponding 2D binary matrix of the edge of the shape:
[[0 0 0 0 0 0 0 0 0 0 0]
 [0 0 0 1 1 1 1 1 0 0 0]
 [0 0 0 1 0 0 0 1 0 0 0]
 [0 0 0 1 0 0 0 1 0 0 0]
 [0 0 0 1 1 1 1 1 0 0 0]
 [0 0 0 0 0 0 0 0 0 0 0]]

Using plt.imshow, I get the following result:

How would you do to plot the ones in this matrix as a dotted line in a matplotlib figure using plt.plot() ? I would like to get this result:

A: For more complex geometries than a rectangle you can use the ConvexHull from scipy.spatial:
#starting with the original data
data = [
 [0,0,0,0,0,0,0,0,0,0,0]
,[0,0,0,1,1,1,1,1,0,0,0]
,[0,0,0,1,1,1,1,1,0,0,0]
,[0,0,0,1,1,1,1,1,0,0,0]
,[0,0,0,1,1,1,1,1,0,0,0]
,[0,0,0,0,0,0,0,0,0,0,0]]

#convert the data array into x-y coordinates
#assume (0,0) is the lower left corner of the array
def array_to_coords(data):
    for y, line in enumerate(reversed(data)):
        for x, point in enumerate(line):
            if point == 1:
                yield(x, y)

points = list(array_to_coords(data))

#plot the points, skip this if you only need the dotted line
x,y = zip(*points)
plt.plot(x, y, 'o')

plt.xlim(0,10)
plt.ylim(0,5)

#plot the convex hull
from scipy.spatial import ConvexHull
hull = ConvexHull(points)
for simplex in hull.simplices:
    plt.plot(hull.points[simplex,0], hull.points[simplex,1], 'ro-')

A more complex situation:
data = [
 [0,0,0,0,0,1,0,0,0,0,0]
,[0,0,0,1,1,1,1,1,0,0,0]
,[0,0,0,1,1,1,1,1,0,0,0]
,[0,0,0,1,1,1,1,1,0,0,0]
,[0,0,1,1,1,1,1,0,0,0,0]
,[0,0,0,0,0,0,0,0,0,0,0]]

A: This isn't exactly the same, but maybe it can give you a start.  You can see what I did.  I extracted the x,y locations of the 1 values, then plotted x against y in a scatter plot.
import matplotlib.pyplot as plt
import numpy as np
array = np.array(
[[0,0,0,0,0,0,0,0,0,0,0],
 [0,0,0,1,1,1,1,1,0,0,0],
 [0,0,0,1,0,0,0,1,0,0,0],
 [0,0,0,1,0,0,0,1,0,0,0],
 [0,0,0,1,1,1,1,1,0,0,0],
 [0,0,0,0,0,0,0,0,0,0,0]])

coords = np.argwhere(array==1)
plt.xlim(0,10)
plt.ylim(0,5)
plt.scatter(coords[:,1],coords[:,0])
plt.show()

Output:

Followup
import matplotlib.pyplot as plt
import numpy as np
array = np.array(
[[0,0,0,0,0,0,0,0,0,0,0],
 [0,0,0,1,1,1,1,1,0,0,0],
 [0,0,0,1,0,0,0,1,0,0,0],
 [0,0,0,1,0,0,0,1,0,0,0],
 [0,0,0,1,1,1,1,1,0,0,0],
 [0,0,0,0,0,0,0,0,0,0,0]])

coords = np.argwhere(array==1)
xmin = np.min(coords[:,1])
xmax = np.max(coords[:,1])
ymin = np.min(coords[:,0])
ymax = np.max(coords[:,0])
x = [xmin,xmin,xmax,xmax,xmin]
y = [ymin,ymax,ymax,ymin,ymin]

plt.xlim(0,10)
plt.ylim(0,5)
plt.plot(x, y, '--')
plt.show()

Output:


text:
Q: Throttling method cURL I'm working on a project using an api, my subscription allows me 2 requests per second.
This API allows you to find words that are related to another word.
My project is to use this API recursively.
the word A gives the word B and C
words B and C each give 2 words, etc., recursively, on a limit that the user specifies.
I store each word in a "word" object. In the __construct of this object, I call the function which calls this API, and which transforms each result into a new object.
Everything works, the only concern is that when the specified recursivity layer is too high, the API doesn't return anything, even though I have a timer of 0.5 seconds.
So I set up a loop. As long as the response to my cURL request is not a 200, I replay it, with a timer of 0.5 seconds.
        $a = 200;
        $httpcode = 0;
        while ($httpcode !== $a) {

            $postRequest = [
                'content' => $this->getMot(),
                'lang' => 'fr',
                'limit' => $this->getLimite(),
                'key' => "//////////////////////"
            ];
            $cURLConnection = curl_init('https://api.keywords.gg/entities');
            curl_setopt($cURLConnection, CURLOPT_HTTPHEADER,
                ['Content-Type: application/json']);
            curl_setopt($cURLConnection, CURLOPT_POSTFIELDS, json_encode($postRequest));
            curl_setopt($cURLConnection, CURLOPT_RETURNTRANSFER, true);
            $apiResponse = curl_exec($cURLConnection);
            $httpcode = curl_getinfo($cURLConnection, CURLINFO_HTTP_CODE);
            $apiResponse = curl_exec($cURLConnection);
            curl_close($cURLConnection);
        }

I think my throttling method is wrong. Could you give me some advice?

A: As you can see in the sleep documentation it expects an integer.
You send a floating number 0.6 then cast to the integer value 0.
So your sleep call become:
sleep(0)

You need to use usleep(int microseconds) if you need more precision.
usleep(600)


text:
Q: Deploy Sidekiq Pro on Heroku This is a question to help others, I've actually solved it but couldn't easily find an answer:
I'm having issues with Sidekiq Pro, I can't find how to install Sidekiq Pro  from the private gem server (contrybsys) on heroku.
Heroku rejects my deploy saying:
remote :       Authentication is required for gems.contribsys.com.

remote:        Please supply credentials for this source. You can do this by running:

remote:        bundle config gems.contribsys.com username:password

remote:        Bundler Output: Authentication is required for gems.contribsys.com.

remote:        Please supply credentials for this source. You can do this by running:

remote:        bundle config gems.contribsys.com username:password

Which I did locally to install the gem. Everything works out fine locally, but can't deploy it.

A: Here is the solution:
heroku config:set BUNDLE_GEMS__CONTRIBSYS__COM=username:password

Then deploy


text:
Q: How can I make this SQL sort by most relevent? I have what appears to be a working set of SQL statements, which operate on a drop-down scenario. The first is an all-inclusive AND, where every requested option is matched. Failing that, it goes to the second sql call which is based on OR's.
Can someone please explain to me or provide better statements where the second tier OR scenario is sorted by most relevent first, meaning the most options are matched as the first entries and going downwards from there?
Or, alternately, if you have a better method of handling this search, possibly with a single call, that would be even better.
The first SQL call based on AND:
SELECT
    l.id,l.title,l.city
FROM listings l
JOIN listings_facilities_xref x ON l.id = x.listing_id
WHERE l.property_type = '1'
    AND x.facility_id = '1'
    AND x.facility_id = '8'
    AND x.facility_id = '54'
    AND x.facility_id = '11'
    AND l.city = 'Orlando'
    AND l.state = '16'
GROUP BY l.id

The second tier call based on OR:
SELECT l.id,l.title,l.city
FROM listings l
JOIN listings_facilities_xref x ON l.id = x.listing_id
WHERE l.property_type = '1'
AND (
    x.facility_id = '1'
    OR x.facility_id = '8'
    OR x.facility_id = '54'
    OR x.facility_id = '11'
)
AND l.city = 'Orlando'
AND l.state = '16'
GROUP BY l.id

My table layout is as follows:
mysql> describe listings;
+---------------+--------------+------+-----+---------+----------------+
| Field         | Type         | Null | Key | Default | Extra          |
+---------------+--------------+------+-----+---------+----------------+
| id            | int(12)      | NO   | PRI | NULL    | auto_increment |
| owner_id      | int(12)      | NO   |     | NULL    |                |
| property_type | int(12)      | NO   |     | NULL    |                |
| title         | varchar(100) | NO   |     | NULL    |                |
| description   | text         | NO   |     | NULL    |                |
| yearbuilt     | int(12)      | NO   |     | NULL    |                |
| beds          | int(11)      | NO   |     | NULL    |                |
| baths         | int(11)      | NO   |     | NULL    |                |
| sleeps        | int(11)      | NO   |     | NULL    |                |
| sqfeet        | int(12)      | NO   |     | NULL    |                |
| lotsize       | int(12)      | NO   |     | NULL    |                |
| address1      | varchar(255) | NO   |     | NULL    |                |
| address2      | varchar(255) | NO   |     | NULL    |                |
| city          | varchar(100) | NO   |     | NULL    |                |
| state         | int(12)      | NO   |     | NULL    |                |
| zipcode       | varchar(50)  | NO   |     | NULL    |                |
| latitude      | varchar(50)  | NO   |     | NULL    |                |
| longitude     | varchar(50)  | NO   |     | NULL    |                |
| created       | int(12)      | NO   |     | NULL    |                |
| updated       | int(12)      | NO   |     | NULL    |                |
+---------------+--------------+------+-----+---------+----------------+

mysql> describe listings_facilities_xref;
+-------------+---------+------+-----+---------+----------------+
| Field       | Type    | Null | Key | Default | Extra          |
+-------------+---------+------+-----+---------+----------------+
| id          | int(12) | NO   | PRI | NULL    | auto_increment |
| listing_id  | int(12) | NO   |     | NULL    |                |
| facility_id | int(12) | NO   |     | NULL    |                |
| category_id | int(12) | NO   |     | NULL    |                |
+-------------+---------+------+-----+---------+----------------+

Sample Import Data can be found at:
listings:  https://pastebin.com/EeuaEFrR
listings_facilities_xref: https://pastebin.com/7WeHgEaE

A: I suspect that you want:
SELECT l.id, l.title, l.city
FROM listings l
JOIN listings_facilities_xref x ON l.id = x.listing_id
WHERE l.property_type = 1 AND
      x.facility_id IN (1, 8, 54, 11) AND
      l.city = 'Orlando' AND
      l.state = 16
GROUP BY l.id, l.title, l.city
ORDER BY COUNT(*) DESC;


text:
Q: Restlet: use "index.html" as default for serving static content using CLAP protocol I want to put static content in my restlet based web service. The static part must reside into the jar of the service. The code I'm using is:
Directory directory = new Directory(getContext(), "clap://class/pageData");
router.attach("/page", directory);
If I access the service with .../page/index.html the page is displayed in the browser. But the call of .../page or .../page/ results in a "Not found" error page.
How can I make index.html the default file?

A: You should try to specify implicitely the indexName property on your directory:
Directory directory = new Directory(
     getContext(), "clap://class/pageData");
directory.setIndexName("index.html");
router.attach("/page", directory);

It seems that the default value is index and not index.html...
Hope it helps you,
Thierry


text:
Q: Como pegar uma informação especifica do ToListAsync Gostaria de criar um sistema que imprimisse na pagina Index cada Postagem igual a da imagem abaixo

E para isso criei um método que busque as últimas 3 postagens, porém, não sei como imprimir na view, porque quando uso foreach ele cria diversas vezes o front end. Como posso Imprimir esse dados de uma maneira que eu consiga acessar uma posição específica do array que ele me retornou no ToListAsync?
Controller:
using Blog.Data;
using Blog.Models;
using Blog.Services;
using Blog.Services.Exceptions;
using Blog.Services.Exceptions.Exceptions;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Rendering;
using System;
using System.Diagnostics;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Identity;
using System.Security.Claims;
using Blog.Areas.Identity.Data;

namespace Blog.Controllers
{
    public class PostagemsController : Controller
    {
        private readonly PostagemService _postagemService;

        private readonly BlogContext _context;

        private UserManager<BlogUser> _userManager;

        public PostagemsController(PostagemService postagemService, BlogContext context, UserManager<BlogUser> userManager)
        {
            _postagemService = postagemService;
            _context = context;
            _userManager = userManager;

        }

        [Authorize]
        public async Task<IActionResult> Index()
        {

            var list = await _postagemService.FindAllAsync();
            return View(list);
        }

        // GET: Postagems

        [Authorize]
        public IActionResult Create()
        {

            ViewData["AssuntoSelect"] = new SelectList(_context.Assunto, "Id", "Nome");
            ViewData["UserSelect"] = new SelectList(_context.BlogUser, "Id", "Email");

            return View();

        }

        [HttpPost]
        [ValidateAntiForgeryToken]
        public async Task<IActionResult> Create(Postagem Postagem)
        {
            var user = await _userManager.GetUserAsync(User);
            var id = user.Id;

            Postagem.Status = "1";
            Postagem.DataPostagem = DateTime.Now;
            Postagem.Likes = 0;
            Postagem.BlogUserId = id;
            Postagem.Visualizacoes = 0;

            if (!ModelState.IsValid)
            {
                return View();
            }

            await _postagemService.InsertAsync(Postagem);
            return RedirectToAction(nameof(Index));
        }

        public async Task<IActionResult> Delete(int? id)
        {
            if (id == null)
            {
                return RedirectToAction(nameof(Error), new { message = "Id not provided" });
            }

            var obj = await _postagemService.FindByIdAsync(id.Value);
            if (obj == null)
            {
                return RedirectToAction(nameof(Error), new { message = "Id not found" });

            }

            return View(obj);
        }
        [HttpPost]
        [AutoValidateAntiforgeryToken]
        public async Task<IActionResult> Delete(int id)
        {
            try
            {
                await _postagemService.RemoveAsync(id);
                return RedirectToAction(nameof(Index));
            }
            catch (IntegrityException e)
            {
                return RedirectToAction(nameof(Error), new { message = e.Message });
            }
        }

        public async Task<IActionResult> Details(int? id)
        {
            if (id == null)
            {
                return RedirectToAction(nameof(Error), new { message = "Id not provided" });
            }

            var obj = await _postagemService.FindByIdAsync(id.Value);
            if (obj == null)
            {
                return RedirectToAction(nameof(Error), new { message = "Id not found" });

            }

            return View(obj);

        }

        public async Task<IActionResult> Edit(int? id)
        {
            if (id == null)
            {
                return RedirectToAction(nameof(Error), new { message = "Id not provided" });
            }

            var obj = await _postagemService.FindByIdAsync(id.Value);
            if (obj == null)
            {
                return RedirectToAction(nameof(Error), new { message = "Id not found" });
            }

            return View();
        }

        [HttpPost]
        [AutoValidateAntiforgeryToken]
        public async Task<IActionResult> Edit(int id, Postagem Postagem)
        {
            if (!ModelState.IsValid)
            {
                return View();
            }
            if (id != Postagem.Id)
            {
                return RedirectToAction(nameof(Error), new { message = "Id mismatch" });
            }
            try
            {
                await _postagemService.UpdateAsync(Postagem);
                return RedirectToAction(nameof(Index));
            }
            catch (NotFoundException e)
            {
                return RedirectToAction(nameof(Error), new { message = e.Message });
            }
            catch (DbConcurrencyException e)
            {
                return RedirectToAction(nameof(Error), new { message = e.Message });
            }
        }

        public IActionResult Error(string message)
        {
            var viewModel = new ErrorViewModel
            {

                RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier
            };
            return View();

        }

        /*
        public IActionResult Create()
        {
            ViewData["PostagemId"] = new SelectList(_context.Postagem, "Id", "Nome");
            ViewData["PostagemId1"] = new SelectList(_context1.BlogUser,"Id","Email");
            return View();
        }
        */

    }
}

Services

using Blog.Data;
using Blog.Models;
using Blog.Services.Exceptions;
using Blog.Services.Exceptions.Exceptions;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Newtonsoft;
using Microsoft.AspNetCore.Identity;
using System.Security.Claims;

namespace Blog.Services
{
    public class PostagemService
    {

        private readonly BlogContext _context;

        public PostagemService(BlogContext context)
        {
            _context = context;

        }

        public async Task<List<Postagem>> FindAllAsync()
        {
            return  await _context.Postagem.Include(obj => obj.Assunto).ToListAsync();
        }

        public async Task InsertAsync(Postagem obj)
        {

            _context.Add(obj);
            await _context.SaveChangesAsync();
        }

        public async Task<Postagem> FindByIdAsync(int id)
        {
            return await _context.Postagem.Include(obj => obj.Assunto).FirstOrDefaultAsync(obj => obj.Id == id);
        }

        public async Task RemoveAsync(int id)
        {
            try
            {
                var obj = await _context.Postagem.FindAsync(id);
                _context.Postagem.Remove(obj);
                await _context.SaveChangesAsync();
            }
            catch (DbUpdateException e)
            {
                throw new IntegrityException(e.Message);
            }
        }

        public async Task UpdateAsync(Postagem obj)
        {
            bool hasAny = await _context.Postagem.AnyAsync(x => x.Id == obj.Id);
            if (!hasAny)
            {
                throw new NotFoundException("Id not Found");
            }

            try
            {
                _context.Update(obj);
                await _context.SaveChangesAsync();
            }
            catch (DbUpdateConcurrencyException e)
            {
                throw new DbConcurrencyException(e.Message);
            }
        }

        public async Task<List<Postagem>> EncontrarUltimas3()
        {
            var result = _context.Postagem.Include(obj => obj.Assunto).OrderByDescending(obj => obj.DataPostagem).Take(3).ToListAsync();
            return await result;
        }

        //var result = _context.Postagem.Where(p => p.Status == "2").Include(obj => obj.Assunto).ToListAsync();
        //return await result;
        //return  await _context.Postagem.Include(obj => obj.Assunto).Where(p => p.Status == "1").OrderBy(p => p.DataPostagem).Take(4).ToListAsync();

    }
}

Model:
using Blog.Areas.Identity.Data;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Identity;

namespace Blog.Models
{
    public class Postagem
    {

        //Atributos

        public int Id { get; set; }

        [DisplayFormat(DataFormatString = "{0:dd/MM/yyyy}")]
        [DataType(DataType.Date)]
        public DateTime DataPostagem { get; set; }

        [DisplayFormat(DataFormatString = "{0:dd/MM/yyyy}")]
        [DataType(DataType.Date)]
        public DateTime DataAtualizacao { get; set; }

        [Required(ErrorMessage = "{0} required")]
        public string Titulo { get; set; }

        public string Descricao { get; set; }

        [Required(ErrorMessage = "{0} required")]
        [DataType(DataType.Text)]
        public string Texto { get; set; }

        public string Status { get; set; }

        public int Likes { get; set; }
        public int Visualizacoes { get; set; }
        public string ImagemInicial { get; set; }

        //Chaves Estrangeiras
        public Assunto Assunto { get; set; }
        public BlogUser BlogUser { get; set; }
        public int AssuntoId { get; set; }
        public string BlogUserId { get; set; }

        public ICollection<Comentario> Comentarios { get; set; } = new List<Comentario>();

        public Postagem()
        {

        }

        public Postagem(int id, DateTime dataPostagem, DateTime dataAtualizacao, string titulo, string descricao, string texto, string status, Assunto assunto, BlogUser blogUser)
        {

            Id = id;
            DataPostagem = dataPostagem;
            DataAtualizacao = dataAtualizacao;
            Titulo = titulo;
            Descricao = descricao;
            Texto = texto;
            Status = status;
            Assunto = assunto;
            BlogUser = blogUser;

        }

    }
}

Caso tenha alguma outra maneira de fazer, por favor, deixe sua sugestão.

A: Consegui resolver.
Para isso eu criei uma ViewModel Para Armazenar cada coleção que eu estava passando, no controller eu criei um objeto para armazenar o resultado de cada consulta e depois na view do referenciei a minha ViewModel. O código de tudo ficou assim:
View Model:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Blog.Models;

namespace Blog.ViewModel
{
    public class ExibirPostagemsViewModel
    {

        public IEnumerable<Postagem> CollectionA { get; set; }
        public IEnumerable<Postagem> CollectionB { get; set; }
        public IEnumerable<Postagem> CollectionC { get; set; }
    }
}

Controller:
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using Blog.Models;
using Blog.Services;
using Blog.ViewModel;

namespace Blog.Controllers
{
    public class HomeController : Controller
    {
        private readonly ILogger<HomeController> _logger;

        private readonly PostagemService _postagemService;

        public HomeController(ILogger<HomeController> logger, PostagemService postagemService)
        {
            _postagemService = postagemService;
            _logger = logger;
        }

        public async Task<IActionResult> Index()
        {
            var model = new ExibirPostagemsViewModel()
            {

                CollectionA = await _postagemService.EncontrarPrimeira(),
            CollectionB = await _postagemService.EncontrarSegunda(),
                CollectionC = await _postagemService.EncontrarTerceira(),
            };

            return View(model);

        }

        public IActionResult Privacy()
        {
            return View();
        }

        [ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
        public IActionResult Error()
        {
            return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
        }
    }
}

View:
@model Blog.ViewModel.ExibirPostagemsViewModel
@{

    ViewData["Title"] = "Home Page";

}

            @foreach (var item in Model.CollectionA)
            {

                         item.ImagemInicial)" alt="">

                                Lifestyle

Postea senserit id eos, vivendo periculis ei qui

John Doe

20 April 2018

            }

            @foreach (var item in Model.CollectionB)
            {

                     item.ImagemInicial)" alt="">

                            Lifestyle

Sed ut perspiciatis, unde omnis iste natus error sit

John Doe

20 April 2018

            }

            @foreach (var item in Model.CollectionC)
            {

                     item.ImagemInicial)" alt="">

                            Fashion
                            Lifestyle

Mel ut impetus suscipit tincidunt. Cum id ullum laboramus persequeris.

John Doe

20 April 2018

            }

O que consegui concluir é que caso queira passar mais de um valor para a View, seja ele fixo ou um select do banco, a melhor maneira é criar uma ViewModel para isso.


text:
Q: How to download jar file? I guess this might be a quiet stupid question but this is the first time I want to bring an external jar file ile to Eclipse and I just don´t know how to download it. I want to import: "nl.flotsam.xeger.Xeger"
I found this link but I don´t understand how to download it.. https://code.google.com/p/xeger/source/browse/trunk/src/main/java/nl/flotsam/xeger/Xeger.java?r=4

A: Right click on your project folder in eclipse -> build path -> configure build path.
Select "Library" tab, click on "Add External Jars" button and select your jar


text:
Q: In what way beautiful soup works differenty in fetching links? Insted of using beautiful soup why is it not smart to get the html content and extract all links by finding all the instances of strings which starts with <a href=".
What other way is there to extracting links if beautiful soup cannot be used?

A: This is because it is not sufficient to look for links that start with

There could be different variations of the hyperlink in the HTML utilising class, id or HTML5 data attributes like:

Using Beautiful Soup would allow you to do this very simply in Python, especially if you have a background in HTML and CSS:
# src is the html of the web page.
soup = BeautifulSoup(src)

linkElements = soup.select('a.someclass')

if len(linkElements) > 0:
    for alinktag in linkElements:
        print alinktag['href']

In addition, if the HTML is in some tree structure like the following, Beautiful soup can easily extract the  elements out:

        first link

        second link

Beautiful Soup code:
linkElements = soup.select('parent a.linkclass')

If you are looking for alternatives to Beautiful Soup in Python, there is a good discussion on Quora.

A: Perhaps others may not like my answer, but BeautifulSoup isn't the only way to manipulate html content. And in fact BeautifulSoup itself DOESN'T do that, it's the underlying HTML Parser who does the job.
You can use lxml (even BeautifulSoup recommends it) or even just Python's standard library xml / html parser modules to parse the html content and manipulate it.
Take an example here that I took from @maskie (sorry because I am lazy to do a dummy):
Sample using xml module:
import xml.etree.ElementTree as ET

s = '''

               first link

               second link

'''

html = ET.fromstring(s)

for a in html.findall('.//a[@class="linkclass"]'):
    print a.attrib

{'href': 'http://www.google.com', 'class': 'linkclass'}
{'href': 'http://www.yahoo.com', 'class': 'linkclass'}

You can simply get the html content from the web by using Python standard-library urllib or the excellent requests modules. I do web scraping quite often and most of the time I'm only using requests and lxml and they do the job beautifully.
NO you don't need BeautifulSoup to extract contents from html, I'd say it just makes manipulating html content in a much easier way (for some people).
And my answer is YES you can use any competent HTML Parser to manipulate html content like what you suggested and still get the job done.


text:
Q: teradata sql - regexp_substr to split on ' - ' I am somewhat new to Teradata.  I am more familiar with Presto SQL, where split_part is available.
I'm looking to split a string on a space, hyphen, space (' - ').
Example: 'Wal-Mart - Target - Best Buy - K-Mart - Staples'
I'm used to using split_part(split_part(COLUMN, ' - ',2), ' - '), 1) to get Target, which ignores the hyphens in Wal-Mart and K-Mart because the hyphen is not preceeded and followed by a space.
But, I can't figure out how to get 'Target' with Teradata.
strtok() only seems to work with a single character, which isn't sufficient since I want to split on 3 (' - ').
Any help would be appreciated!

A: Depending on your version (14.0 or recent), you could use strtok to parse it out
select strtok(oreplace('Wal-Mart - Target - Costco - K-Mart - Staples',' - ','|'),'|',2)

A: While not a direct answer, maybe it will help with the logic so at the risk of getting flamed I'm throwing it out here anyway.  With a regex you should be able to first describe your pattern in plain language to help analyze and define what you really need to get.  i.e. You want the 2nd occurrence of a string that is surrounded by the pattern space-dash-space.  What if the pattern is at the start or end of the line?  Let's revise. You want a specified occurrence of a string that is preceded by the start of the line optionally OR by the pattern space-dash-space, and is followed by space-dash-space OR the end of the line.
In Oracle it would look like this where the first '2' in the argument list means get the 2nd occurrence of the pattern and the 2nd '2' means return the 2nd remembered group (in parenthesis).  The WITH statement just sets up the data.  You would have to translate this regex to Teradata.
WITH tbl(str) AS (
  SELECT 'Wal-Mart - Target - Best Buy - K-Mart - Staples' FROM dual
)
SELECT REGEXP_SUBSTR(str, '(^?| - )(.*?)( - |$)', 1, 2, NULL, 2) retailer
FROM tbl;

RETAILER
--------
Target
1 row selected.

Play with query here


text:
Q: Android Remove  in parsing rss I am creating an app which pulls in an rss feed and displays the title and date. Once clicked, a Toast box will open and display the description for that rss feed story.
When you view the description in the toast view, it is pulling in the < br/> tags from the actual code on the RSS Feed. Can someone help me on how to remove the < br/> tags? I think I need them in the code still to keep the style of the story's text. But for the java to read it as HTML would so they wouldn't show in the toast view.
You can view the RSS feed here.
This is the code that shows the Toast but not sure if that will help.
   public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

    Toast.makeText(this, episode_titles.get(position) + ": " + episode_description.get(position), Toast.LENGTH_LONG).show();

}

A: Do something like this:
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
  String title = episode_titles.get(position);
  String descrip = episode_description.get(position);
  title = removeBr(title);
  descript = removeBr(descript);
  Toast.makeText(this, title + ": " +  descript, Toast.LENGTH_LONG).show();

}

private String removeBr(String str1){
  return str1.replaceAll("<br/>", "");
}


text:
Q: UIImageView with ScaleAspectFit mode makes image pixelated I'd like to show an image in a UIImageView. The image is bigger than the UIImageView, so I set the contentMode like this:
previewImageView.contentMode = .scaleAspectFill

The problem now is that it looks pixelated like ...

but should look like ...

I remember that back in the days with Swift 2.3 and Xcode 7.x on iOS 9.x it looked "correct".
Any ideas?
Edit:
If I set the heightConstraint.constant of the UIImageView to 49.5 in viewDidLoad() the image is scaled correct without pixelation.
I should also mention that the UIImageView was created in the InterfaceBuilder. Is there any known bug?

A: Set content mode to 'Aspect fit' and
Just resize your original image to lower size and it will work for u!


text:
Q: Embedded Transaction management JPA I have these two classes:
public class A {
   @Transactional(propagation = Propagation.REQUIRED, readOnly = true, value="transactionManager")
   public void methodA() {
      B.methodB();
   }
}

@Transactional(propagation = Propagation.REQUIRED, readOnly = false, rollbackFor=Exception.class,  noRollbackFor = MyCustomCheckedException.class, value="transactionManager")
public class B {
   @Transactional(propagation = Propagation.REQUIRED, readOnly = true, value="transactionManager")
   public void methodB() throws MyCustomCheckedException {
       try {
       } catch ( AnotherException ex ) {
          throw new MyCustomCheckedException(ex.getCode(), ex.getMessage(), ex);
       }
   }
}

MyCustomCheckedException is raised in B.methodB().
In the inner Transaction I am not expecting rollback , but I get an exception after all A.methodA() is executed

org.apache.cxf.interceptor.Fault: Transaction rolled back because it has been marked as rollback-only
      at org.apache.cxf.service.invoker.AbstractInvoker.createFault(AbstractInvoker.java:162) ~[cxf-core-3.1.16.jar:3.1.16]
      at org.apache.cxf.jaxws.AbstractJAXWSMethodInvoker.createFault(AbstractJAXWSMethodInvoker.java:267) ~[cxf-rt-frontend-jaxws-3.1.16.jar:3.1.16]
      at org.apache.cxf.service.invoker.AbstractInvoker.invoke(AbstractInvoker.java:128) ~[cxf-core-3.1.16.jar:3.1.16]
      at org.apache.cxf.jaxws.AbstractJAXWSMethodInvoker.invoke(AbstractJAXWSMethodInvoker.java:232) ~[cxf-rt-frontend-jaxws-3.1.16.jar:3.1.16]
      at org.apache.cxf.jaxws.JAXWSMethodInvoker.invoke(JAXWSMethodInvoker.java:85) ~[cxf-rt-frontend-jaxws-3.1.16.jar:3.1.16]
      at org.apache.cxf.service.invoker.AbstractInvoker.invoke(AbstractInvoker.java:74) ~[cxf-core-3.1.16.jar:3.1.16]
      at org.apache.cxf.interceptor.ServiceInvokerInterceptor$1.run(ServiceInvokerInterceptor.java:59) ~[cxf-core-3.1.16.jar:3.1.16]
      at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511) ~[na:1.8.0_181]
      at java.util.concurrent.FutureTask.run$$$capture(FutureTask.java:266) ~[na:1.8.0_181]
      at java.util.concurrent.FutureTask.run(FutureTask.java) ~[na:1.8.0_181]
      at org.apache.cxf.interceptor.ServiceInvokerInterceptor$2.run(ServiceInvokerInterceptor.java:126) ~[cxf-core-3.1.16.jar:3.1.16]
      at org.apache.cxf.workqueue.SynchronousExecutor.execute(SynchronousExecutor.java:37) ~[cxf-core-3.1.16.jar:3.1.16]
      at org.apache.cxf.interceptor.ServiceInvokerInterceptor.handleMessage(ServiceInvokerInterceptor.java:131) ~[cxf-core-3.1.16.jar:3.1.16]
      at org.apache.cxf.phase.PhaseInterceptorChain.doIntercept(PhaseInterceptorChain.java:309) ~[cxf-core-3.1.16.jar:3.1.16]
      at org.apache.cxf.transport.ChainInitiationObserver.onMessage(ChainInitiationObserver.java:121) [cxf-core-3.1.16.jar:3.1.16]
      at org.apache.cxf.transport.http.AbstractHTTPDestination.invoke(AbstractHTTPDestination.java:267) [cxf-rt-transports-http-3.1.16.jar:3.1.16]
      at org.apache.cxf.transport.servlet.ServletController.invokeDestination(ServletController.java:234) [cxf-rt-transports-http-3.1.16.jar:3.1.16]
      at org.apache.cxf.transport.servlet.ServletController.invoke(ServletController.java:208) [cxf-rt-transports-http-3.1.16.jar:3.1.16]
      at org.apache.cxf.transport.servlet.ServletController.invoke(ServletController.java:160) [cxf-rt-transports-http-3.1.16.jar:3.1.16]
      at org.apache.cxf.transport.servlet.CXFNonSpringServlet.invoke(CXFNonSpringServlet.java:189) [cxf-rt-transports-http-3.1.16.jar:3.1.16]
      at org.apache.cxf.transport.servlet.AbstractHTTPServlet.handleRequest(AbstractHTTPServlet.java:303) [cxf-rt-transports-http-3.1.16.jar:3.1.16]
      at org.apache.cxf.transport.servlet.AbstractHTTPServlet.doPost(AbstractHTTPServlet.java:222) [cxf-rt-transports-http-3.1.16.jar:3.1.16]
      at javax.servlet.http.HttpServlet.service(HttpServlet.java:650) [servlet-api.jar:na]
      at org.apache.cxf.transport.servlet.AbstractHTTPServlet.service(AbstractHTTPServlet.java:278) [cxf-rt-transports-http-3.1.16.jar:3.1.16]
      at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:303) [catalina.jar:7.0.88]
      at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208) [catalina.jar:7.0.88]
      at org.jasypt.web.pbeconfig.WebPBEConfigFilter.doFilter(WebPBEConfigFilter.java:68) [jasypt-1.9.2.jar:na]
      at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241) [catalina.jar:7.0.88]
      at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208) [catalina.jar:7.0.88]
      at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52) [tomcat-embed-websocket-8.5.6.jar:7.0.88]
      at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241) [catalina.jar:7.0.88]
      at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208) [catalina.jar:7.0.88]
      at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:219) [catalina.jar:7.0.88]
      at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:110) [catalina.jar:7.0.88]
      at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:498) [catalina.jar:7.0.88]
      at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:169) [catalina.jar:7.0.88]
      at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:103) [catalina.jar:7.0.88]
      at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:1025) [catalina.jar:7.0.88]
      at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:116) [catalina.jar:7.0.88]
      at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:445) [catalina.jar:7.0.88]
      at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1139) [tomcat-coyote.jar:7.0.88]
      at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:637) [tomcat-coyote.jar:7.0.88]
      at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:316) [tomcat-coyote.jar:7.0.88]
      at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149) [na:1.8.0_181]
      at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624) [na:1.8.0_181]
      at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61) [tomcat-coyote.jar:7.0.88]
      at java.lang.Thread.run(Thread.java:748) [na:1.8.0_181]
  Caused by: org.springframework.transaction.UnexpectedRollbackException: Transaction rolled back because it has been marked as rollback-only
      at org.springframework.transaction.support.AbstractPlatformTransactionManager.commit(AbstractPlatformTransactionManager.java:724) ~[spring-tx-4.3.4.RELEASE.jar:4.3.4.RELEASE]
      at org.springframework.transaction.interceptor.TransactionAspectSupport.commitTransactionAfterReturning(TransactionAspectSupport.java:504) ~[spring-tx-4.3.4.RELEASE.jar:4.3.4.RELEASE]
      at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:292) ~[spring-tx-4.3.4.RELEASE.jar:4.3.4.RELEASE]
      at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:96) ~[spring-tx-4.3.4.RELEASE.jar:4.3.4.RELEASE]
      at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179) ~[spring-aop-4.3.4.RELEASE.jar:4.3.4.RELEASE]
      at org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:655) ~[spring-aop-4.3.4.RELEASE.jar:4.3.4.RELEASE]
      at com.wandrian.vagabond.ws.booking.impl.BookingServicesEndpointImpl$$EnhancerBySpringCGLIB$$7adde343.redeliverValueDocumentRequest() ~[classes/:na]
      at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_181]
      at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:1.8.0_181]
      at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:1.8.0_181]
      at java.lang.reflect.Method.invoke(Method.java:498) ~[na:1.8.0_181]
      at org.apache.cxf.service.invoker.AbstractInvoker.performInvocation(AbstractInvoker.java:180) ~[cxf-core-3.1.16.jar:3.1.16]
      at org.apache.cxf.jaxws.JAXWSMethodInvoker.performInvocation(JAXWSMethodInvoker.java:66) ~[cxf-rt-frontend-jaxws-3.1.16.jar:3.1.16]
      at org.apache.cxf.service.invoker.AbstractInvoker.invoke(AbstractInvoker.java:96) ~[cxf-core-3.1.16.jar:3.1.16]

Any ideas?

A: Basically the transaction starts on methodA() call and all the @Transactional inside the call hierarchy are ignored. The transaction changes only if one of the inner @Transactional has Propagation.REQUIRES_NEW which creates new transaction irrespective of an existing transaction.
The methodA(), where the transaction starts, doesn't have noRollBackFor, hence you see the error.
From javadoc on Propagation.REQUIRED
/**
 * Support a current transaction, create a new one if none exists.
 * Analogous to EJB transaction attribute of the same name.
 * <p>This is the default setting of a transaction annotation.
 */
REQUIRED(TransactionDefinition.PROPAGATION_REQUIRED)

There are a few other propagation types also, which can alter the ongoing transaction e.g NOT_SUPPORTED which suspends the ongoing transaction.


text:
Q: ASP.net deny access to folder doesn't work on IIS I want to deny access to the folder with images on my site.
I use the following section in web.config for this:
<location path="images/catalog">
    <system.web>
      <authorization>
        <deny users="*"/>
      </authorization>
    </system.web>
  </location>

It works fine locally but doesn't work on the server (IIS7). Any ideas?
May be you have another solution how to deny access to images in specific folder.

A: I have found solution.
I have added this section to web.config:
<system.webServer>
  <modules runAllManagedModulesForAllRequests="false">
    <remove name="FormsAuthenticationModule" />
    <add name="FormsAuthenticationModule" type="System.Web.Security.FormsAuthenticationModule" />

    <remove name="UrlAuthorization" />
    <add name="UrlAuthorization" type="System.Web.Security.UrlAuthorizationModule" />
  </modules>
</system.webServer>

The reason - IIS7 for some reason ignores forms authentication.
In these questions you can find the cause and solution:

*

*asp.net - runAllManagedModulesForAllRequests = "true" killing windows authentication in IIS7

*IIS7 Forms Authentication Doesn't Deny Image Access


text:
Q: How to instruct MS Visual C++ compiler to use an uninitialized __m512i register How to instruct the Visual C++ compiler (1926) to use an uninitialized __m512i register. In the following code snippet a not(or(A,B)) is calculated, the content of dummy is irrelevant.
__m512i dummy;
const __m512i n8 = _mm512_ternarylogic_epi64(dummy, A, B, 0x11);

Somehow the compiler assumes the register needs to have some content, (it does not), and an expensive and unnecessary memory reference is generated for zmm0:
62 F1 7E 48 6F 45 00 vmovdqu32   zmm0,zmmword ptr [rbp]
62 F3 DD 48 25 C5 11 vpternlogq  zmm0,zmm4,zmm5,11h

ICC 19.0.1 understands the this situation and does not generate the vmovdqu32.
What have I tried: initializing dummy with 0 replaces the vmovdqu32 with:
C5 F1 EF C9          vpxor       xmm1,xmm1,xmm1

This still gives an unnecessary instruction and a stall.
Thus the question: how to instruct the Visual C++ compiler to do the same as the Intel compiler? Just do not initialize the dummy register.

A:
and a stall

xor-zeroing is dependency breaking.  It's also literally as cheap as a NOP on current Intel CPUs, and avoids the risk of an output dependency coupling this dep chain into another one.  It won't cause a stall (except indirectly, like from an I-cache miss), but it is a potential waste of one fused-domain uop of front-end throughput.

If A or B are dead after this, use one of them as the dummy input, like this
__m512i nor_A(__m512i A, __m512i B) {
    return _mm512_ternarylogic_epi64(A, A, B, 0x11);
}

When not inlined, so the input regs are dead afterward, and it has to return in the same reg it received A in, all 4 major x86 compilers make ideal code for this simple case.  (Some optimize the immediate to 5 instead of 0x11, I guess using the first input.)
; MSVC 19.24 -O2 -arch:AVX512 -Gv    (vectorcall calling convention)
# gcc10/clang10/ICC19 -O3 -march=skylake-avx512
nor_A:
        vpternlogq      zmm0, zmm0, zmm1, 17
        ret

Or if you're using this in a loop, you could intentionally create a loop-carried dep chain by using the destination as the first input.  Declare the vector outside the loop.  If you're using ternlog inside a wrapper function, you'd need to pass a reference to the vector into that function to make this work.

If you want to risk a false dependency, _mm512_undefined_epi32() is your best hope for what you want.  It safely expresses what you want (an arbitrary register) while avoiding Undefined Behaviour from reading an uninitialized C variable.  (And no, IDK why Intel thought epi32 would make more sense than si512 like _mm_undefined_si128().  There isn't a masked version of it!)
ICC compiles it to zero extra instructions.  Clang, GCC and MSVC do xor-zero a destination register, though, perhaps implementing it as _mm512_setzero_si512 if they don't really support undefined inputs in their internals.  Godbolt
I also included versions with actual UB; ICC and clang do what you wanted there, picking zmm0 as the dummy input.
__m512i nor_undef(__m512i A, __m512i B) {
    return _mm512_ternarylogic_epi64(_mm512_undefined_epi32(), A, B, 0x11);
}

MSVC 19.24 -O2 -arch:AVX512 -Gv - not great, but basically fine, so the same source can compile to what you want for ICC without being terrible anywhere.
__m512i nor_undef(__m512i,__m512i) PROC             ; nor_undef, COMDAT
    vpxor   xmm2, xmm2, xmm2
    vpternlogq zmm2, zmm0, zmm1, 17
    vmovdqu32 zmm0, zmm2
    ret     0

GCC 10.1:
nor_undef:
    vmovdqa64       zmm2, zmm0
    vpxor   xmm0, xmm0, xmm0
    vpternlogq      zmm0, zmm2, zmm1, 17
    ret

Clang 10.0
nor_undef:
    vpxor   xmm2, xmm2, xmm2
    vpternlogq      zmm0, zmm2, zmm1, 5
    ret

ICC 19.0.1
nor_undef:
    vpternlogq zmm0, zmm2, zmm1, 5                          #15.12
    ret                                                     #15.12


text:
Q: How to set zero instead of null Using VB.Net
I want to make a datagird cell value zero instead of null
For example
Datagridview1
Id value1 value2 value3

01 null null 0
02 0 null 10
03 100 null 100
...

Expected output
Id value1 value2 value3

01 0 0 0
02 0 0 10
03 100 0 100
...

I have more than 80 columns and 100 rows, instead of checking the cell one by one any other method is available
Tried Code
    Private Sub dataGridView1_CellFormatting(sender As Object, e As DataGridViewCellFormattingEventArgs)
        If e.ColumnIndex = 0 AndAlso e.Value IsNot Nothing Then
            If CInt(e.Value) = 0 Then
                e.Value = ""
            End If
        End If
    End Sub

The above code is not working properly, when i add the details in datagridview from database, showing null cell also.
How to make zero instead of null.  Any other method or suggestion
Need VB.Net code help

A: *

*Right-Click the DatagridView and click on Properties.

*In the Property window, locate DefaultCellStyle

*Click on the Tab

*In the Dialog that appear, specify the NullValue

You can also set it from code

dataGridView1.DefaultCellStyle.NullValue = 0;
Gets or sets the System.Windows.Forms.DataGridView cell display value corresponding
  to a cell value of System.DBNull.Value or null.


text:
Q: Couldn't infer template argument in my attempt to make "map" function I want to make a "map" function in C++, which takes a function and a container and returns that container but with elements of type, returned by the function, those elements should be the results of applying the function to elements of container argument.
So for example we should be able to do this:
map([](int i){return float(i + 1);}, vector<int> {1, 2, 3});  // vector<float> {2.0, 3.0, 4.0}

This is my attempt to implement it but looks like I don't fully understand template programming:
http://ideone.com/zMYCVw
#include <iostream>
#include <functional>
#include <string>
#include <list>
#include <vector>

template <
    typename FunctionT,
    template <typename> class ContainerT,
    typename ElemT,
    class FunctionResultT = typename std::result_of<FunctionT>
>
ContainerT<FunctionResultT> map(
    FunctionT func,
    const ContainerT<ElemT>& container
){
    ContainerT<FunctionResultT> resultContainer;
    for (const auto& elem : container){
        resultContainer.push_back(func(elem));
    }
    return resultContainer;
}

template <typename T>
T increaseByOne(const T& number){
    return number + 1;
}

template <typename T>
std::string numberToString(const T& number){
    return std::to_string(number);
}

int main(){
    const auto theList = std::list<float> {1.0, 2.0, 3.0, 4.0, 5.0};

    for (const auto& ele : map(numberToString, map(increaseByOne, theList))){
        std::cout << ele << std::endl;
    }
}

This is the compiler's error:
file.cpp:39:48: error: no matching function for call to 'map'
    for (const auto& ele : map(numberToString, map(increaseByOne, theList))){
                                           ^~~
file.cpp:13:29: note: candidate template ignored: couldn't infer template argument 'FunctionT'
ContainerT<FunctionResultT> map(
                        ^
1 error generated.

A: I found several things that were causing problems. Here's a list of what I found:

*

*Function templates represent an infinite overload set. The type of the function needs to be known when you are passing it in as an argument. That means it template arguments need to be explicitly specified. That is, these need to be changed:
map(numberToString, map(increaseByOne, theList)
//  ^^^^^^^^^^^^^^      ^^^^^^^^^^^^^

To this:
map(numberToString<float>, map(increaseByOne<float>, theList)
//                ^^^^^^^                   ^^^^^^^

*std::list takes more than one template argument. The rest are defaulted. When you defined your template argument as:
template<typename> class ContainerT,

it meant ContainerT could only accept a single template argument. When the compiler sees that you're trying to deduce this type from an instance of std::list it sees that that the number of template arguments don't match. Then type deduction fails. C++11 has variadic parameter packs, you can use them to make ContainerT accept any number of template arguments:
template<typename...> class ContainerT,

*And lastly, you didn't provide the type for FunctionResultT. You can do this here:
class FunctionResultT = typename std::result_of<FunctionT>::type
//                                                        ^^^^^^

But note that this will fail because std::result_of is a template that only provides a ::type member if its template argument is a functor. This basically means that if it is a class that has an overloaded operator() member function.
Instead of using std::result_of, you can have FunctionResultT defaulted to the type of the function call. Like this:
class FunctionResultT = decltype(std::declval<FunctionT>()(std::declval<ElemT>()));

Now this is the result of the changes I made:
template <
    typename FunctionT,
    template <typename...> class ContainerT,
    typename ElemT,
    class FunctionResultT = decltype(std::declval<FunctionT>()(std::declval<ElemT>()))
>

A: template<class OutputContainer, class InputContainer, typename Fn>
OutputContainer map(Fn fn, InputContainer input_container){
    OutputContainer output;
    for(auto&i:input_container)
        output.push_back(fn(i));
    return output;
}


text:
Q: Add dots to a boxplot chart (for outliers) I would like to do a boxplot chart like this one with AmCharts4 but in addition I want to add some dots to represent the outliers. What is the way to go? (I'm not asking for the identification of the outliers, just for the way to add some dots).

A: I've found the way:
var outliers = [{
    "date": "2019-08-01",
     y: 125
  }, {
    "date": "2019-08-01",
     y: 128
  }, {
    "date": "2019-08-02",
     y: 130
  }];

var bulletSeries = chart.series.push(new am4charts.LineSeries());
bulletSeries.strokeOpacity = 0;
bulletSeries.data = outliers;
bulletSeries.dataFields.dateX = "date";
bulletSeries.dataFields.valueY = "y";
var bullet = bulletSeries.bullets.push(new am4charts.CircleBullet());
bulletSeries.tooltipText = "{valueY.value}";


text:
Q: Simplifying $\cosh \mathrm{arcsinh} \ x$ How can I simplify the following:
$$\cosh \mathrm{arcsinh} \ x$$
I know that an expression of the form $f(g^{-1}(x))$ where $f$ and $g$ are trigonometric functions can be simplified by constructing a right triangle. Is there an analgous construction for the hyperbolic functions?

A: Recall that $\cosh^{2}(x)-\sinh^{2}(x)=1$ and take $x=\mathrm{arcsinh(y)}$.
On the hyperbola $x^{2}-y^{2}=1$ you can interpret the $x$ and $y$ components as $\cosh(A)$ and $\sinh(A)$ respectively (where $A$ is the area described in the diagram). Putting $A=\mathrm{arcsinh(t)}$ and recalling that the $x$ and $y$ components satisfy $x^{2}-y^{2}=1$ gives you the formula. This is analogous to drawing triangles to solve for an identity.


text:
Q: all radis data to the json file I would like to fetch all the data from Redis (database '10') into JSON and send it to the client, but I'm a bit confused. How would it be possible?
output:
['iraa', 'Iad', 'TCH', 'name', 'user', 'KPI_NAME', 'pch', 'name2', 'Croatia', 'msg:hello', 'irf', 'Bahamas', 'enodb', 'key']

def main():

    # step 3: create the Redis Connection object
    try:

        # The decode_repsonses flag here directs the client to convert the responses from Redis into Python strings
        # using the default encoding utf-8.  This is client specific.
        r = redis.StrictRedis(host=redis_host, port=redis_port, password=redis_password, decode_responses=True)
        msg = r.keys()
        print(msg)
        #r = redis.Redis()
        #obj= json.loads(r.get('keys'))
        #print (obj)

        #df = pd.DataFrame(msg(json.loads, vals))  # OR redis_values
        #print(df)

        #myFrame = pd.DataFrame(redis_values)
        #print(myFrame.head()

        #myJson = []
        #for rv in redis_values:
        #rv = json.loads(rv)
        #myJson.append(rv)
        #myFrame = pd.read_json(myJson)

    except Exception as e:
        print(e)
if __name__ == '__main__':
    main()


text:
Q: How can I scale a velocity value from native units (ticks per 100ms) to meters per second? I'm trying to convert the native units on Talon SRX Mag/Quad encoders to meters per second to find the max velocity and acceleration of my tank drive robot. This is how I calculated the scalar to convert native to meters per second, but when I tested with this, the values seemed pretty low (.6 m/s, or 1.3mph, which I'm fairly sure is slower than the bot is):
/**
 * Drive values
 */
public static final double
    GEAR_RATIO         = 4.67,
    CTRE_TICKS         = 4096,
    CTRE_TICKS_PER_REV = CTRE_TICKS * GEAR_RATIO, // wheel revs per revolution * ticks per revolution
    WHEEL_DIAMETER     = 6, // inches
    CIRCUMFERENCE      = WHEEL_DIAMETER * Math.PI,
    INCHES_PER_TICK    = CIRCUMFERENCE / CTRE_TICKS_PER_REV, // inches per rev divided by ticks per rev
    IPDS_TO_MPH        = .568, // convert inches per decisecond to miles per hour
    IPDS_TO_MEPS       = .254, // this is a conspiracy bigger than all of us
    CTRE_NATIVE_TO_MPH = INCHES_PER_TICK * IPDS_TO_MPH,
    CTRE_NATIVE_TO_MPS = INCHES_PER_TICK * IPDS_TO_MEPS;

The encoder itself records 4096 ticks per turn of the motor shaft, which then goes through a 4.67:1 gearbox (4.67 motor revs per wheel rev), and to 6-inch wheels.
To find the converted velocity, I report the encoder's velocity times Constants.CTRE_NATIVE_TO_MPS.

A: My encoders are different from yours but the formulas should be the same.
I did a video on how to use wheel encoders and calculate the robot linear and angular speeds. (https://youtu.be/ktZTN5aUYPY)
If you follow the video you will see that in the project doc folder, there is a ppt file with all the formulas. (https://github.com/gusbots/mark01/tree/v3.1/doc)
Here is a snapshot of it:

where vr and vl are the angular velocities in rad/s, R is the radius of the wheel and L is the distance between the wheels.


text:
Q: Error when printing more than one objects in one command line print () (Spyder 2.7) print ('Tính chỉ số BMI')
my_weight = 65
print ('Cân nặng:', my_weight, 'kg')
my_height = 1.65
print ('Chiều cao:', my_height, 'm')
bmi = my_weight/my_height**2
print ('Chỉ số BMI=', bmi)

Tính chỉ số BMI
('C\xc3\xa2n n\xe1\xba\xb7ng:', 65, 'kg')
('Chi\xe1\xbb\x81u cao:', 1.65, 'm')
('Ch\xe1\xbb\x89 s\xe1\xbb\x91 BMI=', 23.875114784205696)


text:
Q: Attachment file display link text This is driving me slightly demented. It's taken me a few hours to work out how to do this and I thought I finally had it, but the link text will only echo the file name and not the link text I want it to. Easy solution is re-name the file to "View Price List", but what if someone further down the line adds a new file and doesn't realise the name has to be the same as the button link text.
I would like the link text to be the same no matter what the name of the attached file is i.e. "Download Price List" or "Pobierz cennik".
<?php if( $post->ID == 38) {?>
     <?php $default_strings = array(
            'price_text' => array(
            'en' => 'Download Price List',
            'pl' => 'Pobierz cennik'
            )
        );?>

     <?php
     global $post;
     $args = array(
            'numberposts' => -1,
            'order'=> 'ASC',
            'post_mime_type' => 'application/msword, application/vnd.ms-excel, application/pdf',
            'post_parent' => $post->ID,
            'post_status' => 'any',
            'post_type' => 'attachment'
            );

    $attachments = get_posts($args);
            if ($attachments) { ?>
            <?php
            foreach ($attachments as $attachment) {?>

            <a class="button big brand-1" <?php echo the_attachment_link($attachment->ID, false); ?>>
            <?php echo $default_strings['price_text'][ $lang ]; ?>

            <?php }
           }?>

          <?php }?>

A: I've changed the button to:
    <a class="button big brand-1" a href="<?php echo wp_get_attachment_url($attachment->ID, false); ?>">
            <?php echo $default_strings['price_text'][ $lang ]; ?>

a href is added around the wp_get_attachment_url rather than using the_attachment_link which contains the whole link.


text:
Q: JavaPairRDD - mapToPair() throws outofmemoryerror I am trying to iterate JavaPairRDD and apply some transformation on Value(which is Java Model class, Key is String) and returning the same Key Value Pair as JavaPairRDD.
Before throwing outofMemoryError it says Marking Stage 5 (saveAsTextFile at AppDaoImpl.java:219) as failed due to a fetch failure from Stage 1 (mapToPair at AppDataUtil.java:221)
Is there anyway can we optimise the below code, it seems to me very simple code. but when i process huge file i am facing this outofmemoryerror.
i am also passing the below parameters.
--num-executors 20  --executor-memory 12288M --executor-cores 5 --driver-memory 6G --conf spark.yarn.executor.memoryOverhead=1332

Sample Code Is:
return parquetFileContent.mapToPair(tuple -> {
                SimpleGroup simpleGroup = tuple._2();
                Model inputData = applyTransformationLogic(simpleGroup);
                return new Tuple2<String, Model>(inputData.getSomeStringField(), inputData);
            });

Before calling saveAsTextFile(), i am adding three RDD's using union and calling this method.
javaSparkCtx.union(rdd1, rdd2, rdd3).saveAsTextFile("hdfs filepath");

i wanted to write all the rdd's to same location, so i am using union
Is it possible to call each rdd seperately in the same location?
log trace is:
15/12/18 15:47:39 INFO scheduler.DAGScheduler: Marking Stage 5 (saveAsTextFile at AppDaoImpl.java:219) as failed due to a fetch failure from Stage 1 (mapToPair at AppDataUtil.java:221)
15/12/18 15:47:39 INFO scheduler.DAGScheduler: Stage 5 (saveAsTextFile at AppDaoImpl.java:219) failed in 78.951 s
15/12/18 15:47:39 INFO scheduler.DAGScheduler: Resubmitting Stage 1 (mapToPair at AppDataUtil.java:221) and Stage 5 (saveAsTextFile at AppDaoImpl.java:219) due to fetch failure
15/12/18 15:47:39 INFO scheduler.DAGScheduler: Executor lost: 2 (epoch 5)
15/12/18 15:47:39 INFO storage.BlockManagerMasterActor: Trying to remove executor 2 from BlockManagerMaster.
15/12/18 15:47:39 INFO storage.BlockManagerMasterActor: Removing block manager BlockManagerId(2, lpdn0185.com, 37626)
15/12/18 15:47:39 INFO storage.BlockManagerMaster: Removed 2 successfully in removeExecutor
15/12/18 15:47:39 INFO scheduler.Stage: Stage 1 is now unavailable on executor 2 (26/56, false)
15/12/18 15:47:39 INFO scheduler.Stage: Stage 2 is now unavailable on executor 2 (25/56, false)
15/12/18 15:47:39 WARN scheduler.TaskSetManager: Lost task 2.1 in stage 5.0 (TID 119, lpdn0185.com): FetchFailed(BlockManagerId(2, lpdn0185.com, 37626), shuffleId=4, mapId=0, reduceId=2, message=
org.apache.spark.shuffle.FetchFailedException: Error in opening FileSegmentManagedBuffer{file=/hdfs1/yarn/nm/usercache/phdpentcustcdibtch/appcache/application_1449986083135_60217/blockmgr-34a2e882-6b36-42c6-bcff-03d9bc5ef80b/2c/shuffle_4_0_0.data, offset=3038022, length=2959077}
    at org.apache.spark.shuffle.hash.BlockStoreShuffleFetcher$.org$apache$spark$shuffle$hash$BlockStoreShuffleFetcher$$unpackBlock$1(BlockStoreShuffleFetcher.scala:67)


text:
Q: How are n-ary trees implemented when you don't know how many children a parent might have? This is something I've been struggling with theoretically, but haven't found any good answers online. I've written programs with binary trees before, which were easy: each node had two links. But now I'm planning out a filesystem based on trees for a project, and I'm not sure how to proceed. Here's the trouble:
I want a tree that has pointers to files for leaves and subdirectories for internal nodes (I think this is how Unix does it?). But if a user wants to create a new file or directory, then the number of links in the parent node must be increased.
How can I account for this when I design my struct? I'm not sure what my options are besides hardcoding, say, 10 links and restricting directory members to that. Any pointers? (Hah, get it?)
If not, does anybody know of any good resources where I could learn more about this? Like I said, so far my internet searches have been fruitless.

A: You can simply use a linked list of children.
Pardon my ASCII graphics:
+------+
|parent|
+------+
   |
   |
   \    +-----------+     +----------+       +----------+
    --->|first child|---->|next child|--...->|last child|-->NULL
        +-----------+     +----------+       +----------+

This makes it slighly tricker to walk the children, since to get the n:th child you need to visit the n-1 preceding children, but I think it's a viable approach that is used.

A: You can use a linked list of children. e.g.:
struct tree {
   /* data */
   struct children_list* children;
}

struct children_list {
   struct tree* child;
   struct children_list* next;
}

A: Here is how Linux handles the directories
http://en.wikipedia.org/wiki/Inode_pointer_structure

A: make a node with data members=> 1.data 2.leftchild 3.rightsibling
suppose a parent has k children.
1st child will be pointed at by leftchild pointer in parent node..
2nd child will be pointed at by rightsibling pointer in 1st child..
In similar fashion ith child(1

This allows us navigation from parent to children & vice versa..
NOTE: Dummy node is just an indicator for last child...

A: A simple solution is have a list in each tree-node.

A: You could use a dynamically allocated array, and store the array pointer and its size. When you need to edit it, you just realloc it.
But, in this kind of situation, you should search for accepted solutions in OS and file system books, articles, scientific magazines/publications, etc.


text:
Q: How can I get the penultimate element in an array in Swift? I only want the second to last element, not the last two as in:
let streets = ["Adams", "Bryant", "Channing", "Douglas", "Evarts"]
let penultimate = streets.suffix(2)
print(penultimate) // ["Douglas", "Evarts"]

Also, I do not want to use the syntax streets[3], because the array is continuously filling up with entries.

A: You can simply drop the last element of your collection and return the last element of the result:
extension BidirectionalCollection {
    var elementBeforeLast: Element? {
        return dropLast().last
    }
}

Usage:
if let elementBeforeLast = streets.elementBeforeLast {
    print(elementBeforeLast)  // "Douglas"
}

A: Just wrote an extension
extension Array {
  func penultimate() -> Element? {
      if self.count < 2 {
          return nil
      }
      let index = self.count - 2
      return self[index]
  }
}

You can use it like
yourArr.penultimate()
Here's a Playground example, it works as intended

A: Here is a solution for a Collection.
public extension Collection {
    @inlinable
    var penultimate: Element? {
        guard let index = index(endIndex, offsetBy: -2, limitedBy: startIndex) else {
            return nil
        }
        return self[index]
    }
}


text:
Q: Window themes not getting applied I downloaded Tweak Tool changing window theme doesn't change anything but changing from Appearance changes.
Why is it so?

*

*Has the default theme directory changed from /usr/share/themes?

*Tweak tool doesnt work for Unity?

*How to install new (metacity,gtk3) themes downloaded from gnome-look.org ?

A: In 14.04 Ubuntu stopped using metacity to draown the windows, and now it's integrated with the gtk css code (located in [theme]/gtk-3.0). You have to find a theme that supports Unity 14.04 windows.
Here's a sample from Zukiwi theme
UnityDecoration.top {
    border: 0px solid shade (@theme_bg_color, 0.5);
    border-bottom-width: 0;
    border-radius: 6px 6px 0 0; /* Corner radius, only the top ones should be */
    padding: 1px 8px 0 8px; /* This padding will be applied to the content of the top layout */
    background-color: @theme_bg_color; /* Decoration background */
    background-image: linear-gradient(to bottom,
        @wm_bg_a,
        @wm_bg_b);
    color: @theme_fg_color; /* The foreground color will be used to paint the text */
    text-shadow: 0 1px @wm_title_shadow;
    box-shadow: inset 0 1px alpha(@theme_base_color, 0.6);
}

You can paste this in the gtk.css file of your theme and tweak as you like.


text:
Q: How can I minimize an application from the Ubuntu dock? If I click a minimized application from the dock it will show the window, but a second click does nothing. Also, the right click menu has no option to minimize. I have seen answers involving modifying the dock behavior with extensions like dash-to-dock, but is there a way to minimize from the dock without modifying it or using extensions?

A: Shift+Middle-Click is the default way to do this.


text:
Q: How do I use an array of indices to alter a specific item in a multi-dimensional object of unknown depth? Imagine I have an array, which looks like:
const x = ["a", "b", "c", "d"]

I wish to use it in order to navigate an object that I don't know the structure of, like:
const y = {
    "a": {
        "b": {
            "c": {
                "d": "Value I require"
            }
        },
        "f": ["g", "h"]
    },
    "e": null
}

However, my issue is that I don't know how deep y will be, or how many indices are in the array x.  How do I do the following:
let someVariable = {"prefilled": "data"}
someVariable[x[0]][x[1]][x[2]][x[3]] = y[x[0]][x[1]][x[2]][x[3]]

In a way which is neither specific to the length of x, the depth of y (and also preferably isn't my current solution, which is a case statement upto a depth of 6)?  For this simplified case, someVariable should hopefully look as follows:
{
    "prefilled": "data",
    "a": {
        "b": {
            "c": {
                "d": "Value I require"
            }
        }
    }
}

A: I would either use a tool like Lodash's _.get or implement something similar that can navigate an object:
let _ = require('lodash');
const x = ["a", "b", "c", "d"]
_.get(object, x.join('.'))

A: You could iterate the array and walk the object.

const getValue = (object, path) => path.reduce((o, k) => (o || {})[k], object),
      y = { a: { b: { c: { d: "Value I require" } }, f: ["g", "h"] }, e: null },
      x = ["a", "b", "c", "d"]

console.log(getValue(y, x));


text:
Q: Google Docs with Codeigniter Now, newbie question here.
1 - I would like to know if there's a way to view a google drive (google doc) document in a browser using php/codeigniter?
2 - Can I edit it directly from that view?
3 - I found others using Zend GData, but is it only limited to spreadsheets?
Can I possibly use codeigniter for this?

A: Google has an API for Docs. I haven't used it, but according to it's table of contents you can do a bunch with it. Like Robin said, it you can do it with PHP you can with CI.
Perhaps you could be more clear on what you want to accomplish. It's not entirely clear right now.


text:
Q: Is it possible to associate an IAM role with an Aurora cluster? I would like to load one of my tables in RDS directly onto S3 using INTO OUTFILE S3 ....
I am following the directions here: https://docs.aws.amazon.com/AmazonRDS/latest/AuroraUserGuide/AuroraMySQL.Integrating.SaveIntoS3.html
One of the steps requires that I associate an IAM role with my cluster. But for some reason, that option is grayed out:

As a result, when I try to use INTO OUTFILE S3 ... I still get this error message: S3 API returned error: Missing Credentials: Cannot instantiate S3 Client.
I am 99% certain that it worked for me in the past by just following the rules but I can't seem to reproduce it.
Does anybody know how to fix this?
Thanks a ton!

A: I believe this is a UI bug, my account does not show this new UI. In general, adding roles is a cluster level action. Your screenshot is sensored heavily, so I can't make out if you were trying this on a cluster or on an instance.
The workaround as you've figured out already is to use the AddRoleToCluster Api. If you do think it's a UI bug, do post on AWS Forums or open a support case so that someone addresses it. Cheers.

A: Found the solution. The console is sometimes not displaying things properly. Use the command in the CLI and it should work fine. Here it is:
PROMPT> aws rds add-role-to-db-cluster --db-cluster-identifier [ENTER_YOUR_CLUSTER] --role-arn [ENTER_THE_ROLE]

Taken from: https://docs.aws.amazon.com/AmazonRDS/latest/AuroraUserGuide/CHAP_AuroraSettingUp.html


text:
Q: Pivoting dates in bigquery My current data is in the form of:

How do I transform it into the following:

Is the following a good way to accomplish this? I have not tried on the original dataset
since there are too many columns, so I want to get the pseudocode correct first.
SELECT * FROM
(

  SELECT
    date,
    event1,
    event2,
    event3

  FROM dataset
)
PIVOT
(

  sum(count)

  FOR event in ('event1', 'event2', 'event3')
)

A: I don't think selecting event1,event2 and event 3 will work because they are not columns, either select data and event or select all.
SELECT * FROM dataset
pivot(sum(count) for event in ('event1', 'event2', 'event3'));