text:
Q: How to read file from res/raw by name I want to open a file from the folder res/raw/.
I am absolutely sure that the file exists.
To open the file I have tried
File ddd = new File("res/raw/example.png");

The command
ddd.exists();

yields FALSE. So this method does not work.
Trying
MyContext.getAssets().open("example.png");

ends up in an exception with getMessage() "null".
Simply using
R.raw.example

is not possible because the filename is only known during runtime as a string.
Why is it so difficult to access a file in the folder /res/raw/ ?

A: Here is example of taking XML file from raw folder:
 InputStream XmlFileInputStream = getResources().openRawResource(R.raw.taskslists5items); // getting XML

Then you can:
 String sxml = readTextFile(XmlFileInputStream);

when:
 public String readTextFile(InputStream inputStream) {
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();

        byte buf[] = new byte[1024];
        int len;
        try {
            while ((len = inputStream.read(buf)) != -1) {
                outputStream.write(buf, 0, len);
            }
            outputStream.close();
            inputStream.close();
        } catch (IOException e) {

        }
        return outputStream.toString();
    }

A: Here are two approaches you can read raw resources using Kotlin.
You can get it by getting the resource id. Or, you can use string identifier in which you can programmatically change the filename with incrementation.
Cheers mate
// R.raw.data_post

this.context.resources.openRawResource(R.raw.data_post)
this.context.resources.getIdentifier("data_post", "raw", this.context.packageName)

A: With the help of the given links I was able to solve the problem myself. The correct way is to get the resource ID with
getResources().getIdentifier("FILENAME_WITHOUT_EXTENSION",
                             "raw", getPackageName());

To get it as a InputStream
InputStream ins = getResources().openRawResource(
            getResources().getIdentifier("FILENAME_WITHOUT_EXTENSION",
            "raw", getPackageName()));

A: You can read files in raw/res using getResources().openRawResource(R.raw.myfilename).
BUT there is an IDE limitation that the file name you use can only contain lower case alphanumeric characters and dot. So file names like XYZ.txt or my_data.bin will not be listed in R.


text:
Q: Can maven parent project include a module at same directory level I am working in an established codebase with an existing standalone pom.xml.
Th intention is to incorporate a child project called "hive"  in a subdirectory off of the parent one.  Note: the hive/pom.xml does already exist and it works fine by itself.
So in the parent's pom.xml I added:
   <modules>
      <module>hive</module>
   </modules>

The problem is I basically lose ability to create the deployable jar from the  parent project.
 stephenb@gondolin:/shared/git2/etl$ mvn package assembly:single
[INFO] Scanning for projects...
[INFO] ------------------------------------------------------------------------
[ERROR] FATAL ERROR
[INFO] ------------------------------------------------------------------------
[INFO] Error building POM (may not be this project's POM).

Project ID: com.myco.etl:etl
POM Location: /shared/git2/etl/pom.xml
Validation Messages:

    [0]  Packaging 'jar' is invalid. Aggregator projects require 'pom' as packaging.

Reason: Failed to validate POM for project com.myco.etl:etl at /shared/git2/etl/pom.xml

[INFO] ------------------------------------------------------------------------
[INFO] Trace
org.apache.maven.reactor.MavenExecutionException: Failed to validate POM for project com.myco.etl:etl at /shared/git2/etl/pom.xml
    at org.apache.maven.DefaultMaven.getProjects(DefaultMaven.java:404)
    at org.apache.maven.DefaultMaven.doExecute(DefaultMaven.java:272)
    at org.apache.maven.DefaultMaven.execute(DefaultMaven.java:138)
    at org.apache.maven.cli.MavenCli.main(MavenCli.java:362)
    at org.apache.maven.cli.compat.CompatibleMain.main(CompatibleMain.java:60)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)

It seems that maven wants me to create a parent pom that basically does nothing except define the dependency modules.
Well I can create a new pom.xml.  But what I cannot do is to push the existing project files into a new subdirectory.
Is there a way to work around this?  E.g. defining a submodule that lives at the same level (not subdir)?  Or some other way to work with the existing dir structure?
thanks
Follow-up:  Based on input that a module can simply be a file in local dir, I
created another pom that calls the original one. The original one was renamed to pommod.xml and the new one shown below is called pom.xml.
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.myco.etl</groupId>
    <artifactId>etl</artifactId>
    <name> ETL Helpers</name>
    <version>1.0.0-SNAPSHOT</version>
    <packaging>pom</packaging>
        <modules>
  <module>appminer</module>
  <module>pommod.xml</module>
   </modules>

I ran "mvn compile package"  But still get same error:
Project ID: com.myco:app_miner
POM Location: /shared/git2/etl/mycopom.xml
Validation Messages:

[0]  Packaging 'jar' is invalid. Aggregator projects require 'pom' as packaging.

Reason: Failed to validate POM for project com.myco:app_miner at /shared/git2/etl/myco/pom.xml

A: This issue could be solved by using maven's Project Aggregation instead of Project Inheritance.

A: To answer the question in the title of this post:
Yes, Maven can include parent and module at same directory level. I feel I first have to explain that a parent can have children and modules. Children and modules are not the same thing:

*

*Child relationship is defined through parent in the child POM. If your parent is in the repo, that's that. If your parent is on the file system, you have to play with parent.relativePath for it to be found in the same folder

*Module is defined through modules in the parent POM. Module typically contains a folder name, and the POM file is implied (e.g. <module>mod</module> is equivalent to <module>mod/pom.xml</module>). Hence a module in the same folder would be <module>pom1.xml</module> or something. (I called the module's POM file pom1.xml in this example, assuming that pom.xml is already taken by the parent — see what a mess we're getting ourselves in)

Let me quickly given an example where children and modules are distinctly different: you may have POMs to build the application of each of your teams. Each of your team may have webapps and backend apps. You may have parent POMs for webapps and backend apps. So some backend app would be a child of the POM for backend apps, while being a module of the team that is working on it.

A thing that strikes me is that you're talking about packaging. A parent POM (packaging pom) is typically just a blob of metadata and nothing else. If you want it to be something else you can still attach plugin executions to lifecycle phases. You can even run packaging plugins and attach the results to the artifact.

I didn't understand why hive cannot be a child (own folder, own POM in that folder), nicely one level down from the parent, how Maven had meant it to be. But it sounded to me like you could have some project, in whatever other directory, be dependent on the jar artifact in hive, and turn it into whatever assembly you want. So hive would be a dependency of the assembly project (let's say hive-assembly). That is getting to my next point...

The fact that Maven does in fact let you have parent and child in the same folder is not at all a good argument for doing so. It's only a matter of time for some part of Maven or one of its plugins is going to work against you. Maven is "convention over configuration", live by that!

A: Please refer the simple examples given in maven site:
http://maven.apache.org/guides/introduction/introduction-to-the-pom.html#Project_Inheritance_vs_Project_Aggregation
Which clearly explains when do you want to have parent-child relationship or package-modules relationship or parent-modules relationship(combination of both).
Example with Spring Boot projects:

I use all my sprint boot projects with spring boot starter project as
  parent, so here i am having parent -child relationship.
For packaging, i have separate pom file in the root directory( or
  relative path) that defines all the modules in it. But there is no
  reference of my parent project in my modules. so here i am using it as
  a package-module relationship.
But recently changed my configuration to use parent-modules relationship, created a parent pom file and referred
  spring boot starter projects as my parent with in it. finally used my parent
  references in all of my child modules. So this way i am using it as
  combination of both models.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Android: Establish internet connection I'm surprised I cannot find any info on the internet on this common situation: How can I start an internet connection? I looked at ConnectivityManager but it seems it is just for monitoring network connectivity.
PS: The phone will be rooted, so it is not a problem.

A: If you want simply enable WiFi you can use this method:
private boolean changeWifiState(boolean state) {
    final WifiManager wifi = (WifiManager) getSystemService(Context.WIFI_SERVICE);
    wifi.setWifiEnabled(state);
    return wifi.isWifiEnabled();
}

Check the permissions required for this. I think you should add these permissions:
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE"/>

A: You can indeed turn wifi on or off (see also this article)
but there is no guarantee that if wifi is turned on there will be an internet connection.
The ConnectivityManager only allows you to inspect the current connectivity state. You cannot use it to enable a connection. Also the ConnectivityManager has no knowledge if an active network connection is an internet connection, but it is easy to check this yourself (see this post
for example).

A: I found the following solution:
1) Add preferred wifi/APN(Access Point Name) configuration to phone settings
2) Enable Wifi/APN
3) Connection will be established automatically
Wifi configuration is straightforward and the following page shows how it could be done:
How to programmatically create and read WEP/EAP WiFi configurations in Android?
APN configuration is tricky. Android has some hidden API's that allow you to access/modify these settings, and you need to use Reflection to do this. This might of course break with future versions of Android. The following page explains how to access/modify those settings:
http://blogs.msdn.com/b/zhengpei/archive/2009/10/13/managing-apn-data-in-google-android.aspx

A: Sockets are what you need. To get your basic info on them, read it here:
http://en.wikipedia.org/wiki/Internet_socket You don't have to read it all, but I think its important you read atleast all of the "implementation issues" to get familiar with the socket methods. Those methods are, of course, implemented differently for each platform (Windows, Android...) but they usually do the same everywhere. So once you understand what each one does, you can work with sockets in any platform with ease.
This diagram (From wiki) helps to demonstrate the sockets usage:

You are in the client side. So just create a socket and call the connect method for the IP address of your server.
Personally, I have never used sockets in Android development. But I think you should use this class:
http://developer.android.com/reference/java/net/Socket.html


text:
Q: tf.while_loop gives wrong result when it runs in parallel I want to update a two dimensional tf.variable inside a tf.while_loop in tensorflow by row. For this reason, I use the tf.assign method. The problem is that with my implementation and parallel_iterations>1 the result is wrong. With parallel_iterations=1 the result is correct. The code is like this:
a = tf.Variable(tf.zeros([100, 100]), dtype=tf.int64)

i = tf.constant(0)
def condition(i, var):
    return tf.less(i, 100)

def body(i, var):
    updated_row = method() # This method returns a [1, 100] tensor which is the updated row for the variable
    temp = tf.assign(a[i], updated_row)
    return [tf.add(i, 1), temp]

z = tf.while_loop(condition, body, [i, a], back_prop=False, parallel_iterations=10)

The iterations are completely independent and I do not know what is the problem.
Strangely If I change the code like this:
a = tf.Variable(tf.zeros([100, 100]), dtype=tf.int64)

i = tf.constant(0)
def condition(i, var):
    return tf.less(i, 100)

def body(i, var):
    zeros = lambda: tf.zeros([100, 100], dtype=tf.int64)
    temp = tf.Variable(initial_value=zeros, dtype=tf.int64)
    updated_row = method() # This method returns a [1, 100] tensor which is the updated row for the variable
    temp = tf.assign(temp[i], updated_row)
    return [tf.add(i, 1), temp]

z = tf.while_loop(condition, body, [i, a], back_prop=False, parallel_iterations=10)

the code gives the correct outcome for parallel_iterations>1. Can someone explain me what is going on here and give me an efficient solution to update the variable because the original variable I want to update is huge and the solution I found is very inefficient.

A: You do not need to use variables for this, you can just generate the row-updated tensor on the loop body:
import tensorflow as tf

def method(i):
    # Placeholder logic
    return tf.cast(tf.range(i, i + 100), tf.float32)

def condition(i, var):
    return tf.less(i, 100)

def body(i, var):
    # Produce new row
    updated_row = method(i)
    # Index vector that is 1 only on the row to update
    idx = tf.equal(tf.range(tf.shape(a)[0]), i)
    idx = tf.cast(idx[:, tf.newaxis], var.dtype)
    # Compose the new tensor with the old one and the new row
    var_updated = (1 - idx) * var + idx * updated_row
    return [tf.add(i, 1), var_updated]

# Start with zeros
a = tf.zeros([100, 100], tf.float32)
i = tf.constant(0)
i_end, a_updated = tf.while_loop(condition, body, [i, a], parallel_iterations=10)

with tf.Session() as sess:
    print(sess.run(a_updated))

Output:
[[  0.   1.   2. ...  97.  98.  99.]
 [  1.   2.   3. ...  98.  99. 100.]
 [  2.   3.   4. ...  99. 100. 101.]
 ...
 [ 97.  98.  99. ... 194. 195. 196.]
 [ 98.  99. 100. ... 195. 196. 197.]
 [ 99. 100. 101. ... 196. 197. 198.]]

A: In tf.function I've found the following:

Key Point: Any Python side-effects (appending to a list, printing with print, etc) will only happen once, when func is traced. To have side-effects executed into your tf.function they need to be written as TF ops:

I'm pretty sure that's what's going on here. You're expecting a to change but that is a "side effect" ( https://runestone.academy/runestone/books/published/fopp/Functions/SideEffects.html ) which tensorflow does not fully support. When you change a to temp you're no longer relying on the side effect and the code works.


text:
Q: select dropdown/flatten observable This is a two-part question. With Angular 6, I'm returning an observable with a nested collection. I need the nested collection to serve as the selected values in a reactive forms multiple select list. 1) Using patchValue, I can't get the values to show as selected items. 2) How do I flatten the observable, or push the nested collection into the control?
HTML:
<mat-form-field>
<mat-select [compareWith]="compareFn" placeholder="Menus" formArrayName="menus" multiple >
<mat-option *ngFor="let menu of menus" [value]="menu">{{menu.name}}</mat-option>
</mat-select>
</mat-form-field>

menuItem Class:
id: string
name: string
menus: [id: string, name: string]

...'menus' is the nested collection which holds the id and name of the menus to which this menuItem is assigned.
API call:
getMenuItem(id: string) : Observable<MenuItem>{
    return this.http.get<MenuItem>(`${this.URL}/${id}`)
    .pipe(catchError(this.handleError<MenuItem>('getMenuItem')));}

Component
Relevants parts of the component:
createForm(){
this.menuItemForm = this.formBuilder.group({
  itemName: ['', Validators.required ],
  itemDescription: ['', Validators.required ],
  active: true,
  menus: this.menus
})

'this.menus' is the select list of all menus
Subscription
getMenuItem(id: string){
this.menuItemService.getMenuItem(id)
  .subscribe(
  (data: MenuItem) => this.onItemRetrieved(data),
  (err: any) => console.log(err));}

I think this is where I need to flatten the observable in order to take the nested collection out of being nested, but I'm not sure how to do it and still retain my class definition.
OnItemRetrieved
onItemRetrieved(menuItem: MenuItem): void {
if (this.menuItemForm){
  this.menuItemForm.reset();
}

this.menuItem = menuItem;

this.menuItemForm.patchValue({
  ...
  menus: this.menuItem.menus

});

Nothing I've tried is getting the values in this.menuItem.menus to show as selected in my select list. In the sample data, I have one menu(id/name) and I've tried this.menuItem.menus[0], and that doesn't work either, which is why I have two problems. :)
Thanks in advance!


text:
Q: Impossible to launch Maven project after upgrade Postgresql from 9.6 to 10.17 I have a Big problem to start my web application with maven.
Config :

*

*Maven 3.6.3

*JAVA 8

*Postgresql 10.17

I can start Maven when I use Postgresqlserver 9.6. I don't have problems.
But when I try to upgrade to postgres 10 or 11, I can't start maven.
I'm looking for the reason since 2 days, but i don't find an issue.
If you have any ideas, help me please. Thank you !
Look the error :
INFOS: Starting tomcat server
juin 29, 2021 5:45:23 PM org.apache.catalina.core.StandardEngine start
INFOS: Starting Servlet Engine: Apache Tomcat/6.0.29
SLF4J: Failed to load class "org.slf4j.impl.StaticLoggerBinder".
SLF4J: Defaulting to no-operation (NOP) logger implementation
SLF4J: See http://www.slf4j.org/codes.html#StaticLoggerBinder for further details.
juin 29, 2021 5:45:24 PM org.apache.catalina.core.ApplicationContext log
INFOS: Initializing Spring root WebApplicationContext
juin 29, 2021 5:45:37 PM org.apache.catalina.core.StandardContext listenerStart
GRAVE: Exception sending context initialized event to listener instance of class org.springframework.web.context.ContextLoaderListener
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'webConfig': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: com.agrisoftci.service.LanguageSettingService com.agrisoftci.serviceImpl.WebConfig.ls; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'languageSettingService': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: com.agrisoftci.repository.LanguageSettingRepository com.agrisoftci.serviceImpl.LanguageSettingServiceImpl.languageSettingRepository; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'languageSettingRepository': Cannot create inner bean '(inner bean)#586737ff' of type [org.springframework.orm.jpa.SharedEntityManagerCreator] while setting bean property 'entityManager'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name '(inner bean)#586737ff': Cannot resolve reference to bean 'entityManagerFactory' while setting constructor argument; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'entityManagerFactory' defined in ServletContext resource [/WEB-INF/applicationContext-persistence.xml]: Cannot resolve reference to bean 'dataSource' while setting bean property 'dataSource'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'dataSource' defined in ServletContext resource [/WEB-INF/applicationContext-persistence.xml]: Bean instantiation via constructor failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [com.zaxxer.hikari.HikariDataSource]: Constructor threw exception; nested exception is com.zaxxer.hikari.pool.PoolInitializationException: Exception during pool initialization
        at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:334)
....
        at com.zaxxer.hikari.pool.PoolUtilities.setupConnection(PoolUtilities.java:133)
        at com.zaxxer.hikari.pool.BaseHikariPool.addConnection(BaseHikariPool.java:420)
        at com.zaxxer.hikari.pool.BaseHikariPool.initializeConnections(BaseHikariPool.java:512)
        ... 118 more

juin 29, 2021 5:45:37 PM org.apache.catalina.core.ApplicationContext log
INFOS: Set web app root system property: 'webapp.root.two' = [C:\Users\olivier\Desktop\pmspilocal\src\main\webapp\]
juin 29, 2021 5:45:37 PM org.apache.catalina.core.ApplicationContext log
INFOS: Initializing log4j from [classpath:log4j.properties]
juin 29, 2021 5:45:37 PM org.apache.catalina.core.StandardContext start
GRAVE: Error listenerStart
juin 29, 2021 5:45:37 PM org.apache.catalina.core.StandardContext start
GRAVE: Context [/agrisoftci] startup failed due to previous errors
juin 29, 2021 5:45:37 PM org.apache.catalina.core.ApplicationContext log
INFOS: Shutting down log4j
juin 29, 2021 5:45:37 PM org.apache.catalina.core.ApplicationContext log
INFOS: Closing Spring root WebApplicationContext
juin 29, 2021 5:45:37 PM org.apache.catalina.loader.WebappClassLoader clearReferencesJdbc
GRAVE: The web application [/agrisoftci] registered the JBDC driver [com.mysql.jdbc.Driver] but failed to unregister it when the web application was stopped. To prevent a memory leak, the JDBC Driver has been forcibly unregistered.
juin 29, 2021 5:45:37 PM org.apache.catalina.loader.WebappClassLoader clearReferencesJdbc
GRAVE: The web application [/agrisoftci] registered the JBDC driver [org.postgresql.Driver] but failed to unregister it when the web application was stopped. To prevent a memory leak, the JDBC Driver has been forcibly unregistered.

This is my applicationContext-persistence.xml file :
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:jpa="http://www.springframework.org/schema/data/jpa"
       xmlns:tx="http://www.springframework.org/schema/tx"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/data/jpa http://www.springframework.org/schema/data/jpa/spring-jpa-1.0.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd">

     <!-- Configures the database connection. -->
    <bean id="hikariConfig" class="com.zaxxer.hikari.HikariConfig">
        <property name="poolName" value="springHikariCP" />
        <property name="connectionTestQuery" value="SELECT 1" />
        <property name="transactionIsolation" value="TRANSACTION_READ_COMMITTED" />
        <property name="maximumPoolSize" value="10" />
        <property name="idleTimeout" value="30000" />
        <property name="driverClassName" value="org.postgresql.ds.PGSimpleDataSource"/>
        <property name="jdbcUrl" value="jdbc:postgresql:agrisoftci"/>
        <property name="username" value="$username"/>
        <property name="password" value="&password!"/>
    </bean>

    <!-- Creates the datasource bean. -->
    <bean id="dataSource" class="com.zaxxer.hikari.HikariDataSource">
        <constructor-arg  ref="hikariConfig"/>
    </bean>

    <bean id="hibernateJpaVendorAdapter" class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter"/>

    <!-- Creates the bean that creates the JPA entity manager factory. -->
    <bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
        <property name="dataSource" ref="dataSource"/>
        <property name="jpaVendorAdapter" ref="hibernateJpaVendorAdapter"/>
        <property name="packagesToScan" value="com.agrisoftci.entities"/>
        <property name="jpaProperties">
            <props>
                <prop key="hibernate.dialect">org.hibernate.spatial.dialect.postgis.PostgisDialect</prop>
                <!--<prop key="hibernate.dialect">org.hibernate.dialect.PostgreSQLDialect</prop>-->
                <prop key="hibernate.hbm2ddl.auto">update</prop>
                <prop key="hibernate.show_sql">true</prop>
                <prop key="hibernate.format_sql">true</prop>
                <prop key="hibernate.hbm2ddl.import_files">/WEB-INF/resources/sql/user.sql</prop>
            </props>
        </property>
    </bean>

    <bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
        <property name="entityManagerFactory" ref="entityManagerFactory"/>
    </bean>

    <!-- Enables annotation-driven transaction management.-->
    <tx:annotation-driven/>

    <jpa:repositories base-package="com.agrisoftci.repository" />

</beans>

And this is my pom.xml file :
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.agrisoftci</groupId>
    <artifactId>agrisoftci</artifactId>
    <packaging>war</packaging>
    <version>1.0-SNAPSHOT</version>
    <name>agrisoftci Maven Webapp</name>
    <url>http://maven.apache.org</url>

    <properties>
        <maven.test.failure.ignore>true</maven.test.failure.ignore>
        <spring.framework.version>4.1.6.RELEASE</spring.framework.version>
        <spring.framework.security.version>3.2.0.RELEASE</spring.framework.security.version>

        <hibernate.version>4.1.9.Final</hibernate.version>
        <sl4j.version>1.7.2</sl4j.version>
        <junit.version>4.11</junit.version>
        <webappDirectory>${project.build.directory}/${project.build.finalName}</webappDirectory>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    </properties>

    <repositories>
        <repository>
            <url>http://download.eclipse.org/rt/eclipselink/maven.repo/</url>
            <id>jpa20-persistence</id>
            <layout>default</layout>
            <name>Repository for library Persistence (JPA 2.1)</name>
        </repository>

        <!-- Dynamic Jasper-->
        <repository>
            <id>fdvsolution.public</id>
            <url>http://archiva.fdvs.com.ar/repository/public1/</url>
        </repository>

            <repository>
                <releases>
                    <enabled>true</enabled>
                    <updatePolicy>always</updatePolicy>
                    <checksumPolicy>fail</checksumPolicy>
                </releases>
                <id>license4j-runtime-library</id>
                <name>License4J Runtime Library Maven Repository</name>
                <url>https://www.license4j.com/maven/</url>
                <layout>default</layout>
            </repository>

            <repository>
                <id>OSGEO GeoTools repo</id>
                <url>http://download.osgeo.org/webdav/geotools</url>
            </repository>
            <repository>
                <id>Hibernate Spatial repo</id>
                <url>http://www.hibernatespatial.org/repository</url>
            </repository>
            <!-- add JBOSS repository for easy access to Hibernate libraries -->
            <repository>
                <id>JBOSS</id>
                <url>https://repository.jboss.org/nexus/content/repositories/releases/</url>
            </repository>
            <repository>
                <id>sonatype-oss</id>
                <url>https://oss.sonatype.org/content/groups/public</url>
            </repository>

    </repositories>

    <dependencies>

        <dependency>
            <groupId>com.license4j</groupId>
            <artifactId>license4j-runtime-library</artifactId>
            <version>4.7.3</version>
        </dependency>

        <!-- Fileupload-->
        <dependency>
            <groupId>commons-fileupload</groupId>
            <artifactId>commons-fileupload</artifactId>
            <version>1.3.1</version>
        </dependency>

        <!-- Apache Commons IO -->
        <dependency>
            <groupId>commons-io</groupId>
            <artifactId>commons-io</artifactId>
            <version>2.4</version>
        </dependency>

          <dependency>
            <groupId>org.apachiro.maven</groupId>
            <artifactId>apereo</artifactId>
            <version>1.2</version>
         </dependency>

        <!-- Dynamic Reports -->
        <dependency>
                <groupId>net.sourceforge.dynamicreports</groupId>
                <artifactId>dynamicreports-core</artifactId>
                <version>4.0.0</version>
        </dependency>

        <!-- Apache POI -->
        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi</artifactId>
            <version>3.11</version>
        </dependency>

        <!-- Apache POI Excel 2007 et +-->
        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi-ooxml</artifactId>
            <version>3.11</version>
        </dependency>

        <!-- Jasper Report -->
       <dependency>
            <groupId>net.sf.jasperreports</groupId>
            <artifactId>jasperreports</artifactId>
            <version>6.0.0</version>
            <type>jar</type>
            <scope>compile</scope>
          <exclusions>
             <exclusion>
                <artifactId>olap4j</artifactId>
                <groupId>org.olap4j</groupId>
             </exclusion>
          </exclusions>
       </dependency>

        <dependency>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
            <version>1.2.16</version>
        </dependency>

        <dependency>
            <groupId>commons-digester</groupId>
            <artifactId>commons-digester</artifactId>
            <version>2.1</version>
            <type>jar</type>
            <scope>compile</scope>
        </dependency>

        <dependency>
            <groupId>org.codehaus.groovy</groupId>
            <artifactId>groovy-all</artifactId>
            <version>1.7.0</version>
        </dependency>

          <!--****************************** servlet-api ******************************-->

        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
            <version>3.0.1</version>
            <scope>provided</scope>
        </dependency>

        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>jstl</artifactId>
            <version>1.2</version>
        </dependency>

        <dependency>
              <groupId>javax.servlet.jsp</groupId>
              <artifactId>jsp-api</artifactId>
              <version>2.1</version>
              <scope>provided</scope>
         </dependency>

        <!--****************************** servlet-api ******************************-->

        <!-- **********************************************************************
        **              SPRING DEPENDENCIES                              **
        ********************************************************************** -->

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-beans</artifactId>
            <version>${spring.framework.version}</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-tx</artifactId>
            <version>${spring.framework.version}</version>
        </dependency>

        <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-context</artifactId>
                <version>${spring.framework.version}</version>
        </dependency>

        <dependency>
            <groupId>org.springframework.security</groupId>
            <artifactId>spring-security-core</artifactId>
            <version>${spring.framework.security.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.security</groupId>
            <artifactId>spring-security-web</artifactId>
            <version>${spring.framework.security.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.security</groupId>
            <artifactId>spring-security-config</artifactId>
            <version>${spring.framework.security.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.security</groupId>
            <artifactId>spring-security-taglibs</artifactId>
            <version>${spring.framework.security.version}</version>
        </dependency>
       <dependency>
            <groupId>javax.annotation</groupId>
            <artifactId>jsr250-api</artifactId>
            <version>1.0</version>
        </dependency>

        <!-- Spring ORM -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-orm</artifactId>
            <version>${spring.framework.version}</version>
        </dependency>

        <!-- Spring web -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-web</artifactId>
            <version>${spring.framework.version}</version>
        </dependency>

        <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-webmvc</artifactId>
                <version>${spring.framework.version}</version>
        </dependency>

        <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-context-support</artifactId>
                <version>${spring.framework.version}</version>
        </dependency>

        <!-- Java Mail -->
        <dependency>
                <groupId>javax.mail</groupId>
                <artifactId>mail</artifactId>
                <version>1.4.7</version>
        </dependency>
        <dependency>
                <groupId>javax.mail</groupId>
                <artifactId>javax.mail-api</artifactId>
                <version>1.5.5</version>
        </dependency>

        <!-- Spring Data JPA -->
        <dependency>
            <groupId>org.springframework.data</groupId>
            <artifactId>spring-data-jpa</artifactId>
            <version>1.7.0.RELEASE</version>
        </dependency>

        <!-- **********************************************************************
        **              HIBERNATE DEPENDENCIES                  **
        ********************************************************************** -->

        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-entitymanager</artifactId>
            <version>${hibernate.version}</version>
        </dependency>

        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-core</artifactId>
            <version>${hibernate.version}</version>
        </dependency>

        <!-- Hibernate Spatial -->
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-spatial</artifactId>
            <version>4.0</version>
        </dependency>

        <!-- Integre les annotations  de hibernate: Remplace hibernate-annotations-->
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>jtidy</artifactId>
            <version>r8-21122004</version>
        </dependency>

        <dependency>
            <groupId>org.hibernate.javax.persistence</groupId>
            <artifactId>hibernate-jpa-2.0-api</artifactId>
            <version>1.0.0.Final</version>
        </dependency>
        <dependency>
            <groupId>org.eclipse.persistence</groupId>
            <artifactId>eclipselink</artifactId>
            <version>2.1.1</version>
            <type>pom</type>
            <scope>compile</scope>
        </dependency>

        <!-- DataSource (HikariCP) -->

        <dependency>
            <groupId>commons-dbcp</groupId>
            <artifactId>commons-dbcp</artifactId>
            <version>1.0</version>
        </dependency>

        <dependency>
            <groupId>javax.sql</groupId>
            <artifactId>jdbc-stdext</artifactId>
            <version>2.0</version>
        </dependency>

        <!-- **********************************************************************
        **              OTHER DEPENDENCIES                               **
        ********************************************************************** -->

        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpclient</artifactId>
            <version>4.3.1</version>
        </dependency>

        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpcore</artifactId>
            <version>4.3.2</version>
        </dependency>

        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-api</artifactId>
            <version>${sl4j.version}</version>
        </dependency>

        <dependency>
         <groupId>org.codehaus.jackson</groupId>
         <artifactId>jackson-core-asl</artifactId>
         <version>1.9.13</version>
      </dependency>
      <dependency>
         <groupId>org.codehaus.jackson</groupId>
         <artifactId>jackson-mapper-asl</artifactId>
         <version>1.9.13</version>
      </dependency>

        <dependency>
         <groupId>com.fasterxml.jackson.core</groupId>
         <artifactId>jackson-annotations</artifactId>
         <version>2.5.1</version>
      </dependency>
      <dependency>
         <groupId>com.fasterxml.jackson.datatype</groupId>
         <artifactId>jackson-datatype-joda</artifactId>
         <version>2.5.1</version>
      </dependency>
      <dependency>
         <groupId>com.fasterxml.jackson.datatype</groupId>
         <artifactId>jackson-datatype-jsr310</artifactId>
         <version>2.5.1</version>
      </dependency>
      <dependency>
         <groupId>com.fasterxml.jackson.core</groupId>
         <artifactId>jackson-core</artifactId>
         <version>2.5.1</version>
      </dependency>
      <dependency>
         <groupId>com.fasterxml.jackson.core</groupId>
         <artifactId>jackson-databind</artifactId>
         <version>2.5.1</version>
      </dependency>

      <dependency>
        <groupId>com.bedatadriven</groupId>
        <artifactId>jackson-datatype-jts</artifactId>
        <version>2.2</version>
      </dependency>

        <!-- Mysql -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.6</version>
        </dependency>

         <dependency>
            <groupId>org.postgresql</groupId>
            <artifactId>postgresql</artifactId>
            <version>42.2.16</version>
        </dependency>
        <!--MAJ POSTGRES 20200122-->
        <dependency>
            <groupId>javax.transaction</groupId>
            <artifactId>jta</artifactId>
            <version>1.1</version>
        </dependency>

        <!-- Http Client -->
        <dependency>
            <groupId>com.ning</groupId>
            <artifactId>async-http-client</artifactId>
            <version>1.9.31</version>
        </dependency>

        <!-- Apache Commons NET :  Echo, Finger, FTP, NNTP, NTP, POP3(S), SMTP(S), Telnet, Whois -->
        <dependency>
            <groupId>commons-net</groupId>
            <artifactId>commons-net</artifactId>
            <version>3.3</version>
        </dependency>

        <!-- **********************************************************************
                ** TEST DEPENDENCIES
        ** ********************************************************************** -->

        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>${junit.version}</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-test</artifactId>
            <version>${spring.framework.version}</version>
        </dependency>
        <dependency>
            <groupId>org.eclipse.persistence</groupId>
            <artifactId>javax.persistence</artifactId>
            <version>2.1.0-SNAPSHOT</version>
        </dependency>

        <!-- https://mvnrepository.com/artifact/org.apache.commons/commons-collections4 -->
        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-collections4</artifactId>
            <version>4.0</version>
        </dependency>

         <!-- javamelody-core -->
        <dependency>
            <groupId>net.bull.javamelody</groupId>
            <artifactId>javamelody-core</artifactId>
            <version>1.60.0</version>
        </dependency>

        <!-- itext, option to add PDF export -->
        <dependency>
            <groupId>com.lowagie</groupId>
            <artifactId>itext</artifactId>
            <version>2.1.7</version>
            <exclusions>
                <exclusion>
                    <artifactId>bcmail-jdk14</artifactId>
                    <groupId>bouncycastle</groupId>
                </exclusion>
                <exclusion>
                    <artifactId>bcprov-jdk14</artifactId>
                    <groupId>bouncycastle</groupId>
                </exclusion>
                <exclusion>
                    <artifactId>bctsp-jdk14</artifactId>
                    <groupId>bouncycastle</groupId>
                </exclusion>
            </exclusions>
        </dependency>
        <dependency>
            <groupId>net.sourceforge.dynamicreports</groupId>
            <artifactId>dynamicreports-googlecharts</artifactId>
            <version>4.1.1</version>
            <type>jar</type>
        </dependency>
        <dependency>
            <groupId>com.zaxxer</groupId>
            <artifactId>HikariCP</artifactId>
            <version>3.4.5</version>
        </dependency>
    </dependencies>

    <build>

        <finalName>agrisoftci</finalName>
        <outputDirectory>${webappDirectory}/WEB-INF/classes</outputDirectory>

        <pluginManagement>
            <plugins>
                <plugin>
                    <artifactId>maven-compiler-plugin</artifactId>
                    <configuration>
                        <source>1.8</source>
                        <target>1.8</target>
                    </configuration>
                </plugin>
                <!--
                <plugin>
                    <groupId>org.apache.tomcat.maven</groupId>
                    <artifactId>tomcat6-maven-plugin</artifactId>
                    <version>2.1</version>
                </plugin>
               -->
               <plugin>
                    <groupId>org.apache.tomcat.maven</groupId>
                    <artifactId>tomcat7-maven-plugin</artifactId>
                    <version>2.2</version>
                </plugin>
            </plugins>
            <!--MAJ TOMCAT PLUGIN 20200122-->
        </pluginManagement>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>2.3.2</version>
                <configuration>
                    <encoding>${project.build.sourceEncoding}</encoding>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-resources-plugin</artifactId>
                <version>2.4.3</version>
                <configuration>
                    <encoding>${project.build.sourceEncoding}</encoding>
                </configuration>
            </plugin>
        </plugins>
    </build>

</project>

A: the problem is solved after add a dependancie for hikaricp v3.4.5.
Thank you,
Olivier


text:
Q: Question on Specular Reflection Does anybody know why Specular Reflection is defined as
 Reflection = 2 ( Normal . Light ) Normal - Light
where Normal is the normal of the plane and
Light is the normalize vector from the light source?

A: To reflect a vector you need to reverse the component of that vector that lies on a particular axis. For example, to reflect a vector off the x-axis, you could just flip the sign of the y component. Another way to look at that is to multiply the y component by a factor of -1. Yet another way to achieve that goal is to subtract twice the y component from itself. This last variant is what is used in the formula you site.
We want to subtract some multiple of the surface normal from our direction vector. The (Normal.Light) term gives you the component of the light vector that lies along the normal (similar to the y component in the example above). We then need twice that amount (hence the 2) and we want to change the vector in the direction of the normal, so that number needs to be multiplied by the normal. You do seem to have swapped the terms on around the minus.

A: It is perhaps a consequence of the general reflection described here:
http://en.wikipedia.org/wiki/Reflection_(mathematics)
You probably need to know a bit vector geometry or linear algebra to understand why though.


text:
Q: Measure time spent in each iterate in a while loop in java or android I want to know how long spent for execute an iterate in a while loop? More precisely I write a while loop for execute a download task and write data to file and I want to measure download speed every time that loop goes to next iterate.

A: just use a calendar.getInstance().getTimeInMillis();
List <Long> elapsedTimes = new ArrayList<>();   //contains the time taken for all iterations.
long startTime = Calendar.getInstance().getTimeInMillis();
long elapsedTime = startTime;
for (... your for loop)
{
    ... //do your stuff ...
    long currTime = Calendar.getInstance.getTimeInMillis();
    elapsedTimes.add(currTime - elapsedTime);
    elapsedtime = currTime;

}
long endTime = Calendar.getInstance().getTimeInMillis();

long totalTime= endtime - startTime.


text:
Q: Read out definitions of a text file based dictionary I'm trying to write a Python function that takes as an input a text file based dictionary, for example Webster's free dictionary. The function "webster_definition" will then search through the text file and print the definition for a specific word, e.g. "Canada".
Here is what I've got so far:
import re
import sys

def webster_definition(word):
    word = word.upper()
    output = ""
    doc = open("webster.txt",'r')

    for line in doc:
        if re.match(word,line):
            print line

    return output

print webster_definition("Canada")

This will output the word I looked for. But the definition starts three lines later with "Defn:" and is of variable length, e.g.:
CANADA
Can"a*da, n.

Defn: A British province in North America, giving its name to various
plants and animals. Canada balsam. See under Balsam.
 -- Canada goose. (Zoöl.) See Whisky Jack.
 -- Canada lynx. (Zoöl.) See Lynx.
 -- Canada porcupine (Zoöl.) See Porcupine, and Urson.
 -- Canada rice (Bot.) See under Rick.
 -- Canada robin (Zoöl.), the cedar bird.

The desired output should look like:
CANADA
Defn: A British province in North America, giving its name to various
plants and animals. Canada balsam. See under Balsam.
 -- Canada goose. (Zoöl.) See Whisky Jack.
 -- Canada lynx. (Zoöl.) See Lynx.
 -- Canada porcupine (Zoöl.) See Porcupine, and Urson.
 -- Canada rice (Bot.) See under Rick.
 -- Canada robin (Zoöl.), the cedar bird.

Can anyone help me with the output of the definition?

A: in file:
CANADA
Can"a*da, n.

Defn: A British province in North America, giving its name to various
plants and animals. Canada balsam. See under Balsam.
 -- Canada goose. (Zoöl.) See Whisky Jack.
 -- Canada lynx. (Zoöl.) See Lynx.
 -- Canada porcupine (Zoöl.) See Porcupine, and Urson.
 -- Canada rice (Bot.) See under Rick.
 -- Canada robin (Zoöl.), the cedar bird.

 ANOTHER DEFENITION
 another defenition

 Defn.. some words
 more words
 ......

with open('webster_file', 'r') as f:
     # read into a string.
     data = f.read()

# uppercase word to search for
word = 'canada'.upper()
# search for empty line and the get everything non-greedy up to the
# another empty line.
pattern = '^' + word + '.*?\n^$\n.*?^$'

mo = re.search(pattern,data,re.M|re.DOTALL)

if mo:
    print(mo.group(0))

CANADA
Can"a*da, n.

Defn: A British province in North America, giving its name to various
plants and animals. Canada balsam. See under Balsam.
 -- Canada goose. (Zoöl.) See Whisky Jack.
 -- Canada lynx. (Zoöl.) See Lynx.
 -- Canada porcupine (Zoöl.) See Porcupine, and Urson.
 -- Canada rice (Bot.) See under Rick.
 -- Canada robin (Zoöl.), the cedar bird

A: I am not sure i completely follow.
But if you do not want to print empty lines you can check for it and not print them, eg:
if line in ['\n', '\r\n', '']:
    continue
print line

A: # coding: utf-8

data = '''CANADA
Can"a*da, n.

Defn: A British province in North America, giving its name to various
plants and animals. Canada balsam. See under Balsam.
 -- Canada goose. (Zoöl.) See Whisky Jack.
 -- Canada lynx. (Zoöl.) See Lynx.
 -- Canada porcupine (Zoöl.) See Porcupine, and Urson.
 -- Canada rice (Bot.) See under Rick.
 -- Canada robin (Zoöl.), the cedar bird.'''

data = data.split('\n\n')
data = [data[0].split('\n')[0]] + [data[1]]
data = '\n'.join(data)

A: It usually helps to decompose the task into simpler functions. For the case of text files parsing, generators are very handy:
def read_paragraph(fp):
    """
    Read lines from the file until the end of the paragraph
    """
    while True:
        line = fp.readline()
        if not line.strip():
            break
        yield line

def skip_paragraph(fp):
    while fp.readline().strip():
        pass

def find_definition(fp, word):
    word = word.upper()
    while True:
        line = fp.readline()
        if not line:
            break  # end of file, consider raising an exception here

        if line.strip() == word:
            yield line          # found the word
            skip_paragraph(fp)  # move to the definition
            for defline in read_paragraph(fp):
                yield defline
            break
        else:
            # we're not interested in the current word, just skipping it
            skip_paragraph(fp)
            skip_paragraph(fp)

Finally, to get a definition:
with open('webster.txt') as fp:
    definition = find_definition(fp, 'Canada')
    print ''.join(definition)

That said, if you need to query the dictionary often, and performance is of any concern, consider converting the text file into an sqlite database.


text:
Q: How to save variable without using database in ruby Currently I have some code like this:
class WorkingWithThread
  def self.start_first_thread
    @@first_thread = Thread.new do
      do something
      repeat # infinitive loop
    end
  end
  def self.start_second_thread
    @@second_thread = Thread.new do
      do something
      repeat # infinitive loop
    end
  end

  def self.stop_thread
    begin
      Thread.kill @@first_thread
      Thread.kill @@second_thread
      p 'STOP THREAD'
    rescue Exception => e
      p 'NO THREAD OPENING'
    end
  end
end

Max threads pool is 3, timeout = 600 secs. I made 2 api requests to start and stop threads.
It works properly. However, if the start api is called 2 times, the variables @@first_thread and @@second_thread seems to be reinitialized and those running threads can't be killed. In addition, after a while, sometimes, the stop api also doesn't works even when I call start api one time only (i need explanation here).
The questions is:

*

*How to store thread variables so I can stop it without using database?

*I'm thinking about adding method to block start api when there are running threads? Is it viable? If it is, how to stop those threads when it happens as unexplained reason that i mentioned above?

A: Why not instantiate an instance of the class and store the running threads there? For example:
class WorkingWithThread
  attr_accessor :first_thread, :second_thread

  def run
    start_first_thread
    start_second_thread
  end

  def start_first_thread
    return puts("First thread already running") if self.first_thread

    puts "Launching thread one!"
    self.first_thread = Thread.new do
      # do something
      repeat # infinite loop
    end
  end

  def start_second_thread
    return puts("Second thread already running") if self.second_thread

    puts "Launching thread two!"
    self.second_thread = Thread.new do
      # do something
      repeat # infinite loop
    end
  end

  def stop_threads
    begin
      Thread.kill first_thread if first_thread
      Thread.kill second_thread if second_thread
      p 'STOP THREADS'
    rescue Exception => e
      p 'NO THREADS OPENING'
    end
  end
end

Then to use it:
worker = WorkingWithThread.new
worker.run
# => Launching thread one!
# => Launching thread two!

worker.run
# => First thread already running
# => Second thread already running

worker.stop_threads
# => STOP THREADS

That way you'll have access to the running threads throughout - let me know if that helps and how you get on :)


text:
Q: What is importance of labelling a k8s resource and then applying selector on label in spec on same k8s resource? Following are the example which I encountered on k8s website.
apiVersion: v1
kind: Service
metadata:
  name: my-nginx
  labels:
    run: my-nginx
spec:
  ports:
  - port: 80
    protocol: TCP
  selector:
    run: my-nginx

selector:
    run: my-nginx
Not able to figure out what is the rationale behind labeling it in spec and then applying same selector on the spec definition.Found plenty of example but no explanation for them.
apiVersion: apps/v1
kind: Deployment
metadata:
  name: hello-world
spec:
  selector:
    matchLabels:
      run: load-balancer-example
  replicas: 2
  template:
    metadata:
      labels:
        run: load-balancer-example
    spec:
      containers:
        - name: hello-world
          image: gcr.io/google-samples/node-hello:1.0
          ports:
            - containerPort: 8080
              protocol: TCP

**
 selector:
matchLabels:

  run: load-balancer-example**

A: This is one of the fundamental design concepts of Kubernetes:
Resources are linked by labels and selectors.
Resources such as a Service or Deployment that must refer to other resources have a selector which defines a set of labels. These resources select all those resources (of a specific type) that have labels matching this selector.
For example, a Deployment with a selector of a=b refers to all Pods that happen to have the label a=b.
That's why in your Deployment specification, you have to define the same label (run=load-balancer-example) in the Pod template (template section) as in the selector of the Deployment. Because you want the Deployment to manage these Pods:
apiVersion: apps/v1
kind: Deployment
metadata:
  name: hello-world
spec:
  selector:
    matchLabels:
      run: load-balancer-example    # <<<<<----- must match
  replicas: 2
  template:  # <- you define a template for the Pods that will be created here
    metadata:
      labels:
        run: load-balancer-example  # <<<<------ must match
    spec:
      containers:
        - name: hello-world
          image: gcr.io/google-samples/node-hello:1.0
          ports:
            - containerPort: 8080
              protocol: TCP

If you have any other Pods with the run=load-balancer-example, the Deployment will manage these too. On the other hand, if the labels in the Pod template of the Deployment specification were different from the selector, the Deployment wouldn't manage these Pods because their labels don't match the selector of the Deployment.
In your first example, the label definitions within the Service specification are unrelated. The first one (labels) is the label of the Service (you could omit it, if you want), the second one (selector) is the selector of the Service:
apiVersion: v1
kind: Service
metadata:
  name: my-nginx
  labels:
    run: my-nginx  # <<<<<---- unrelated to the other 'run: my-nginx'
spec:
  ports:
  - port: 80
    protocol: TCP
  selector:
    run: my-nginx  # <<<<<---- unrelated to the other 'run: my-nginx'

However, the selector is related to the labels of any Pods. In particular, this Service will apply to all Pods that have the run=my-nginx label.

A: Labels are there to group resources. Label selectors are there to target these grouped resources.
Depending on the resource, labels are used for one purpose or another. Deployments use labels to know what pods are their children (no label selectors are involved here), Services use labels to forward traffic to the backends (Pods). Network Policies use labels to allow or deny traffic, etc.
Why using labels? The most clear example is with services. Pods die all the time. When they are re-created, they have a different IP address. You can't rely on the IP address of a Pod, as it can change at any moment. So you create a service and target a group of pods, according their labels. Services don't die, unless you delete them. A pod that has been re-created with a different IP address has the same labels, so the service gets the new IP address of the pod as possible endpoint, and the traffic can still flow.


text:
Q: Allow user registration via API and from website rails 5 Currently I am working on sample web application. In this application, user can sign up via JSON API as well as from browser.
For JSON API authentication I have used gem devise_token_auth https://github.com/lynndylanhurley/devise_token_auth and it is working fine. I am able to sign up via API.
But now I have to provide sign up functionality from the web browser.
(URL: http://localhost:3000/auth/sign_up) getting following error
The action 'new' could not be found for DeviseTokenAuth::RegistrationsController

So how can I allow sign up from the web browser.
Here is my routes.rb file
Rails.application.routes.draw do
  mount_devise_token_auth_for 'User', at: 'auth'
end

Generated routes
                  Prefix Verb     URI Pattern                            Controller#Action
        new_user_session GET      /auth/sign_in(.:format)                devise_token_auth/sessions#new
            user_session POST     /auth/sign_in(.:format)                devise_token_auth/sessions#create
    destroy_user_session DELETE   /auth/sign_out(.:format)               devise_token_auth/sessions#destroy
       new_user_password GET      /auth/password/new(.:format)           devise_token_auth/passwords#new
      edit_user_password GET      /auth/password/edit(.:format)          devise_token_auth/passwords#edit
           user_password PATCH    /auth/password(.:format)               devise_token_auth/passwords#update
                         PUT      /auth/password(.:format)               devise_token_auth/passwords#update
                         POST     /auth/password(.:format)               devise_token_auth/passwords#create
cancel_user_registration GET      /auth/cancel(.:format)                 devise_token_auth/registrations#cancel
   new_user_registration GET      /auth/sign_up(.:format)                devise_token_auth/registrations#new
  edit_user_registration GET      /auth/edit(.:format)                   devise_token_auth/registrations#edit
       user_registration PATCH    /auth(.:format)                        devise_token_auth/registrations#update
                         PUT      /auth(.:format)                        devise_token_auth/registrations#update
                         DELETE   /auth(.:format)                        devise_token_auth/registrations#destroy
                         POST     /auth(.:format)                        devise_token_auth/registrations#create
     auth_validate_token GET      /auth/validate_token(.:format)         devise_token_auth/token_validations#validate_token
            auth_failure GET      /auth/failure(.:format)                devise_token_auth/omniauth_callbacks#omniauth_failure
                         GET      /auth/:provider/callback(.:format)     devise_token_auth/omniauth_callbacks#omniauth_success
                         GET|POST /omniauth/:provider/callback(.:format) devise_token_auth/omniauth_callbacks#redirect_callbacks
        omniauth_failure GET|POST /omniauth/failure(.:format)            devise_token_auth/omniauth_callbacks#omniauth_failure
                         GET      /auth/:provider(.:format)              redirect(301)

Do I have to add separate devise here. Please let me know your thoughts.

A: Best way to achieve this will be to mount normal devise routes to one scope, and API devise_token_auth routes to separate scope.
Rails.application.routes.draw do

  # standard devise routes at /users
  devise_for :users

  # token auth routes available at /api/auth/
  namespace :api, defaults: { format: :json } do
    scope module: :v1 do
      mount_devise_token_auth_for 'User', at: 'auth'
    end
  end
end

A: new_user_registration GET      /auth/sign_up(.:format)                devise_token_auth/registrations#new

which does not lead to anything, because in the GEM controller devise_token_auth/registrations_controller there is no new action.
1 - change the routing so that the http GET request is rooted to your controller#new action.
2 - create the controller#new action
3 - have the form in new.html.erb call the following action
POST     /auth(.:format)                        devise_token_auth/registrations#create

4 - To create a user, you just need to make an HTTP POST request to the following URL
POST     /auth(.:format)                        devise_token_auth/registrations#create

with the parameters that you need to pass to this controller action
def create
  @resource            = resource_class.new(sign_up_params)
  @resource.provider   = "email"

  # honor devise configuration for case_insensitive_keys
  if resource_class.case_insensitive_keys.include?(:email)
    @resource.email = sign_up_params[:email].try :downcase
  else
    @resource.email = sign_up_params[:email]
  end

  # give redirect value from params priority
  @redirect_url = params[:confirm_success_url]

  # fall back to default value if provided
  @redirect_url ||= DeviseTokenAuth.default_confirm_success_url

  # success redirect url is required
  if resource_class.devise_modules.include?(:confirmable) && !@redirect_url
    return render_create_error_missing_confirm_success_url
  end

  # if whitelist is set, validate redirect_url against whitelist
  if DeviseTokenAuth.redirect_whitelist
    unless DeviseTokenAuth::Url.whitelisted?(@redirect_url)
      return render_create_error_redirect_url_not_allowed
    end
  end

  begin
    # override email confirmation, must be sent manually from ctrl
    resource_class.set_callback("create", :after, :send_on_create_confirmation_instructions)
    resource_class.skip_callback("create", :after, :send_on_create_confirmation_instructions)
    if @resource.save
      yield @resource if block_given?

      unless @resource.confirmed?
        # user will require email authentication
        @resource.send_confirmation_instructions({
          client_config: params[:config_name],
          redirect_url: @redirect_url
        })

      else
        # email auth has been bypassed, authenticate user
        @client_id = SecureRandom.urlsafe_base64(nil, false)
        @token     = SecureRandom.urlsafe_base64(nil, false)

        @resource.tokens[@client_id] = {
          token: BCrypt::Password.create(@token),
          expiry: (Time.now + DeviseTokenAuth.token_lifespan).to_i
        }

        @resource.save!

        update_auth_header
      end
      render_create_success
    else
      clean_up_passwords @resource
      render_create_error
    end
  rescue ActiveRecord::RecordNotUnique
    clean_up_passwords @resource
    render_create_error_email_already_exists
  end
end

This way the user will be created, but it is not a good approach. You are using an api when you should just be using devise


text:
Q: What is $.Deferred() and .resolve in jquery What exactly .deferred do what is its work and where and when we should use .deferred with resolve. In below function I have two .done callbacks. I want to set two different callback msg. fiddle
var deferred = $.Deferred();
deferred.done(function(value) {
    alert(value);
}).done(function(id){
alert(id)
});

console.log(deferred)

deferred.resolve("hello world");

A: jQuery.Deferred is the main tool of jQuery's implementation of the promise pattern.
Here are a few links, worth reading :

*

*[SO] Implement promises pattern

*[jQuery doc] Deferred

*[wikipedia] Futures and Promises
As for your specific need : you should use .then() (read the docs for .done() and .then()).
var deferred = $.Deferred();

deferred.then(function(value) {
    alert(value);
    return 42;
}).then(function(id){
    alert('The answer : ' + id);
});

console.log(deferred)

deferred.resolve("hello world");

fiddle

A: Would this do what you want?
var deferred = $.Deferred();
deferred.done(function(value) {
    alert(value[0]);
}).done(function(value){
    alert(value[1]);
});

deferred.resolve(["hello world", "goodbye, cruel world"]);


text:
Q: javascript function to search all OpenLayers vector features covering a pixel I have an OpenLayers map that draws features in a vector layer. The features are selectable and have a popup on select. Unfortunately in a lot of cases the features overlap so it can be impossible to select some features. I think that what I need to do to fix this is change my select control so that it uses a click handler and searches the map for features at this point. What sort of function do i need to write? are there any examples of this being implemented before?
This is how the features are drawn:
var vector_Layer = new OpenLayers.Layer.Vector();

function GetFeaturesFromKMLString (strKML) {
    var format = new OpenLayers.Format.KML({
    'internalProjection': new OpenLayers.Projection("EPSG:900913"),
    'extranalProjection': new OpenLayers.Projection("EPSG:4326")
    });
    return format.read(strKML);
};

vector_Layer.addFeatures(GetFeaturesFromKMLString('$newkml'));

And this is how Layers are currently selected:
var select = new OpenLayers.Control.SelectFeature(vector_Layer, {clickout: true});
        vector_Layer.events.on({
            "featureselected": onFeatureSelect,
            "featureunselected": onFeatureUnselect});

        map.addControl(select);
        select.activate();

        select.handlers['feature'].stopDown = false;
        select.handlers['feature'].stopUp = false;

here is the click event listener I was planning on using:
OpenLayers.Control.Click = OpenLayers.Class(OpenLayers.Control, {
            defaultHandlerOptions: {
                'single': true,
                'double': false,
                'pixelTolerance': 0,
                'stopSingle': false,
                'stopDouble': false
            },

            initialize: function(options) {
                this.handlerOptions = OpenLayers.Util.extend(
                    {}, this.defaultHandlerOptions
                );
                OpenLayers.Control.prototype.initialize.apply(
                    this, arguments
                );
                this.handler = new OpenLayers.Handler.Click(
                    this, {
                        'click': this.onClick,
                        'dblclick': this.onDblclick
                    }, this.handlerOptions
                );
            },

            onClick: function(evt) {
                //function that seachers for and selectas features at this point
            },

A: I've had this this situation, and came up with a novel solution: use the WMSGetFeatureInfo instead of the SelectFeature control, because it is able to return multiple features associated with a click event. Even though the WMSGetFeatureInfo is not supposed to be used with vector layers, it is possible to trick OpenLayers into thinking it is interacting with a WMS layer by adding WMS properties to the vector layer, and hacking some layer methods.
var lyrJobs = new OpenLayers.Layer.Vector(
"User Jobs",
{
    strategies: [
            new OpenLayers.Strategy.BBOX({ resFactor: 1 }) //Force bb to refresh on every zoom.
    ],
    url: wmsServerAddress + '?',
    protocol: new OpenLayers.Protocol.WFS({
        version: '1.1.0',
        srsName: map.getProjection(),
        url: wfsServerAddress,
        featureType: 'MyLayerName',
        featureNS: 'MyNameSpace', //URI
        geometryName: 'Geom'
    }),
    //Add WMS-style properties to allow WMSGetFeatureInfo protocol to be used.
    params: {
        FORMAT: 'image/png',
        VERSION: '1.1.1',
        STYLES: '',
        LAYERS: 'myNameSpace' + layerName
    }
}
);

lyrJobs.reverseAxisOrder = function ()
{
    return (parseFloat(this.params.VERSION) >= 1.3 &&
    !!this.yx[map.getProjectionObject().getCode()]);
}

It's perhaps a bit weird, but it works extremely well. When you get a response from the control, you can check if it returned a single features or multiple features, and display a popup accordingly.

A: One observation first: if you have vector features of a same group overlapping on your map, you might want to look into some clustering implementation first. One reason for this is that rendering vector graphics in a browser is expensive. Running into performance issues nowadays is less of a problem, but depending on the number of vector points and the browser-machine rendering them, you could still run into problems, especially on mobile platforms. Let say that it is good practice to keep the vector features (and the DOM elements)  in your page as lower as possible. Openlayers has its own clustering strategy implemented in its API, but if you do not like it you could still plugin a third party one or roll your own.
Having pointed this out, one possible route I would suggest is to try having a look at what OpenLayers.Geometry has to offer and especially this example. I have never tried this, but depending on needs, you could even think at creating a temporary circle on click (all within OpenLayers) and then intersect your vector points with this circle...
Hope this can be of some help.

A: you might want something like leatlet's spiderfy https://github.com/jawj/OverlappingMarkerSpiderfier-Leaflet.
here is a demo http://jawj.github.io/OverlappingMarkerSpiderfier-Leaflet/demo.html


text:
Q: Ocultar y mostrar hojas de excel desde python Estoy intentando ocultar y mostrar algunas hojas de excel usando openpyxl, pero no encuentro documentación en español sobre el particular.
Existe un método dentro de openpyxl que permita hacer lo anterior, o tal vez usando alguna otra librería.

A: Sobre la hoja que se requiere ocultar o mostrar existe el método ".sheet_state", al usarlo sobre la hoja respectiva se tiene que asignar el valor 'hidden' o 'visible' para ocultar o mostrar respectivamente.
Aquí una pequeña implementación mostrando su uso
from openpyxl import Workbook
import openpyxl

libro = "libroOcultarHojas.xlsx"
# se crea un archivo que al final se salvará
miLibro = Workbook()

# o si ya se tiene el archivo
# indicar la ruta también
# si este script no se encuentra en
# la misma carpeta
# -----------------------------------------
# miLibro = openpyxl.load_workbook(libro)
# -----------------------------------------

print(miLibro.sheetnames)
#['Sheet'] o las hojas si el archivo ya existe

# Se renombra 'Sheet' por 'miHoja1'
miLibro.active.title = 'miHoja1'

# Se crea 3 hojas más
for i in range(2, 5):
    miLibro.create_sheet("miHoja" + str(i))

# muestra el total de hojas contenidas en el libro
print(miLibro.sheetnames)
#['miHoja1', 'miHoja2', 'miHoja3', 'miHoja4']

# se emplea el método "sheet_state"
# sobre miHoja2 de miLibro y se le dice 'hidden'
# ocultar
miLibro['miHoja2'].sheet_state = 'hidden'

# se verifica
for hoja in miLibro.sheetnames:
    print(hoja,":",miLibro[hoja].sheet_state)
# miHoja1 : visible
# miHoja2 : hidden
# miHoja3 : visible
# miHoja4 : visible

miLibro['miHoja3'].sheet_state = 'hidden'  # ocultar
miLibro['miHoja3'].sheet_state = 'visible' # visible

# se guarda
miLibro.save(libro)

El resultado final:


text:
Q: 32-bit JVM maximum memory size on 64-bit Windows not as large as expected I've been having a tough time memory mapping a 550MB file. I understand that 32-bit JVM can allocate a maximum memory size of around 1.4G, so I need to map a large file by parts. However, this is a 550MB file but I still cannot map it all into memory. The best I can do is a buffer size of around 333MB.
Below is my test code:
void testMap() throws IOException{
    long buffer = 500000000; // CAUSES ERROR. best I can do is 350000000
    RandomAccessFile srcFile = new RandomAccessFile("550MBFile", "r");
    ByteBuffer srcbb = srcFile.getChannel().map(MapMode.READ_ONLY, 0, buffer);
}

And the error is as following:
Exception in thread "main" java.io.IOException: Map failed
    at sun.nio.ch.FileChannelImpl.map(Unknown Source)
    at TestSpliter.testMap(TestSpliter.java:22)
    at TestSpliter.main(TestSpliter.java:14)
Caused by: java.lang.OutOfMemoryError: Map failed
...
JVM argument: -Xms1024m
Can anyone explain why I can only use 300MB out of 1.4GB? Thanks.
Note that this is not a duplicate question with those ones asking about the maximum heap size for 32-bit JVM.

A: Most likely, your address space is fragmented and there isn't more than 550MB available of contiguous address space. If you need to memory map large files, you need to be able to map them in segments if that becomes necessary.


text:
Q: How to determine if an entity has been continually active across multiple database records? Example data set where each row records the active time period of a stint of a unique person/major combination
Note: All records belonging to each of the following person_IDs are shown in this example data set
Note2: A termination date of 9999/12/31 just means the person is currently enrolled in that major.
TBL_MAJORS

Person_ID   Major         Effective_Date   Termination_Date
76          Biology       2016/8/1         2017/2/24
76          Accounting    2017/2/25        2017/4/15
76          Math          2017/4/16        9999/12/31
102         Physics       2016/8/1         2018/7/21
58          Literature    2016/8/1         2017/5/13
94          Art History   2016/8/1         2017/8/30
94          Comp Sci      2018/3/1         9999/12/31

End goal data set with a new column indicating whether each person was continuously enrolled in a major throughout the year of 2017
TBL_MAJORS_2

Person_ID   Major         Effective_Date   Termination_Date   Active_Throughout_2017
76          Biology       2016/8/1         2017/2/24          1
76          Accounting    2017/2/25        2017/4/15          1
76          Math          2017/4/16        9999/12/31         1
102         Physics       2016/8/1         2018/7/21          1
58          Literature    2016/8/1         2017/5/13          0
94          Art History   2016/8/1         2017/8/30          0
94          Comp Sci      2018/3/1         9999/12/31         0

A bit more explanation
So, for example, person 76 had three different majors spanning continuously from 2016/8/1 to 9999/12/31 (i.e they're currently enrolled), so they were continuously enrolled throughout 2017.
On the other hand, person 94 had two different majors, but there was a gap in activity from 2017/8/31 to 2018/2/28, so they weren't continuously enrolled throughout 2017.
Can anyone help me achieve this? Bonus kudos if you can make it perform well... I'm thinking that maybe this would involve some sort of window/analytic function, but I'm honestly stumped.

A: This can be done like so:
WITH tbl_majors AS (SELECT 76 person_id, 'Biology' major, to_date('01/08/2016', 'dd/mm/yyyy') effective_date, to_date('24/02/2017', 'dd/mm/yyyy') termination_date FROM dual UNION ALL
                    SELECT 76 person_id, 'Accounting' major, to_date('25/02/2017', 'dd/mm/yyyy') effective_date, to_date('15/04/2017', 'dd/mm/yyyy') termination_date FROM dual UNION ALL
                    SELECT 76 person_id, 'Math' major, to_date('16/04/2017', 'dd/mm/yyyy') effective_date, to_date('31/12/9999', 'dd/mm/yyyy') termination_date FROM dual UNION ALL
                    SELECT 102 person_id, 'Physics' major, to_date('01/08/2016', 'dd/mm/yyyy') effective_date, to_date('21/07/2018', 'dd/mm/yyyy') termination_date FROM dual UNION ALL
                    SELECT 58 person_id, 'Literature' major, to_date('01/08/2016', 'dd/mm/yyyy') effective_date, to_date('13/05/2017', 'dd/mm/yyyy') termination_date FROM dual UNION ALL
                    SELECT 94 person_id, 'Art History' major, to_date('01/08/2016', 'dd/mm/yyyy') effective_date, to_date('30/08/2017', 'dd/mm/yyyy') termination_date FROM dual UNION ALL
                    SELECT 94 person_id, 'Comp Sci' major, to_date('01/03/2018', 'dd/mm/yyyy') effective_date, to_date('31/12/9999', 'dd/mm/yyyy') termination_date FROM dual)
SELECT person_id,
       major,
       effective_date,
       termination_date,
       CASE WHEN to_date('01/01/2017', 'dd/mm/yyyy') >= MIN(effective_date) OVER (PARTITION BY person_id, grp)
                 AND to_date('31/12/2017', 'dd/mm/yyyy') <= MAX(termination_date) OVER (PARTITION BY person_id, grp)
                 THEN 1
            ELSE 0
       END active_throughout_2017
FROM   (SELECT person_id,
               major,
               effective_date,
               termination_date,
               SUM(new_grp_start) OVER (PARTITION BY person_id ORDER BY effective_date) grp
        FROM   (SELECT person_id,
                       major,
                       effective_date,
                       termination_date,
                       CASE WHEN effective_date = LAG(termination_date) OVER (PARTITION BY person_id ORDER BY effective_date) + 1 THEN 0 ELSE 1 END new_grp_start
                FROM   tbl_majors));

 PERSON_ID MAJOR       EFFECTIVE_DATE TERMINATION_DATE ACTIVE_THROUGHOUT_2017
---------- ----------- -------------- ---------------- ----------------------
        58 Literature  01/08/2016     13/05/2017                            0
        76 Accounting  25/02/2017     15/04/2017                            1
        76 Biology     01/08/2016     24/02/2017                            1
        76 Math        16/04/2017     31/12/9999                            1
        94 Art History 01/08/2016     30/08/2017                            0
        94 Comp Sci    01/03/2018     31/12/9999                            0
       102 Physics     01/08/2016     21/07/2018                            1

This works by first working out if the current row and previous row are consecutive or not - i.e. whether the current row's effective_date is 1 greater than that of the previous row's termination_date.
Once we know if the previous row was consecutive or not, we know that's the start of a new group. We can then do a cumulative sum on this, meaning that all consecutive rows will get the same number, and the number increases each time a new group of rows is started.
Then it's a simple matter of working out the min effective_date and max termination_date for each person and group, and then doing an overlaps comparison with the first and last days in 2017.

ETA: Here's a solution based on GSazheniuk's suggestion:
WITH tbl_majors AS (SELECT 76 person_id, 'Biology' major, to_date('01/08/2016', 'dd/mm/yyyy') effective_date, to_date('24/02/2017', 'dd/mm/yyyy') termination_date FROM dual UNION ALL
                    SELECT 76 person_id, 'Accounting' major, to_date('25/02/2017', 'dd/mm/yyyy') effective_date, to_date('15/04/2017', 'dd/mm/yyyy') termination_date FROM dual UNION ALL
                    SELECT 76 person_id, 'Math' major, to_date('16/04/2017', 'dd/mm/yyyy') effective_date, to_date('31/12/9999', 'dd/mm/yyyy') termination_date FROM dual UNION ALL
                    SELECT 102 person_id, 'Physics' major, to_date('01/08/2016', 'dd/mm/yyyy') effective_date, to_date('21/07/2018', 'dd/mm/yyyy') termination_date FROM dual UNION ALL
                    SELECT 58 person_id, 'Literature' major, to_date('01/08/2016', 'dd/mm/yyyy') effective_date, to_date('13/05/2017', 'dd/mm/yyyy') termination_date FROM dual UNION ALL
                    SELECT 94 person_id, 'Art History' major, to_date('01/08/2016', 'dd/mm/yyyy') effective_date, to_date('30/08/2017', 'dd/mm/yyyy') termination_date FROM dual UNION ALL
                    SELECT 94 person_id, 'Comp Sci' major, to_date('01/03/2018', 'dd/mm/yyyy') effective_date, to_date('31/12/9999', 'dd/mm/yyyy') termination_date FROM dual)
SELECT person_id,
       major,
       effective_date,
       termination_date,
       CASE WHEN SUM(LEAST(to_date('31/12/2017', 'dd/mm/yyyy'), termination_date) + 1 - GREATEST(to_date('01/01/2017', 'dd/mm/yyyy'), effective_date)) OVER (PARTITION BY person_id)
                   = to_date('31/12/2017', 'dd/mm/yyyy') + 1 - to_date('01/01/2017', 'dd/mm/yyyy')
                 THEN 1
            ELSE 0
       END active_throughout_2017
FROM   tbl_majors;

As you can see, it's a lot more elegant than my original solution. You should test both to see which one is more performant for your data, etc.
Both solutions assume that there won't be an overlap (i.e. a student will only ever have one major at any one moment in time); you'd have to adjust them accordingly to cater for cases when someone might have more than one major at a time.


text:
Q: change for loop in foreach I'm new to php.I'm reading a RSS feed and store in my database table.
for this I'm using
$num = count($movies->channel->item);
for ($i=0; $i<=$num-1; $i++){
    $tittle= $movies->channel->item[$i]->title."
";
    $link=$movies->channel->item[$i]->link."
";
    $image=$movies->channel->item[$i]->medium_image_url."
";
    $des=$movies->channel->item[$i]->description."
";
    $city=$movies->channel->item[$i]->city;
}

how can display all data with foreach loop?

A: You can just echo out the result of your statements (I've also changed it to a foreach as requested):
foreach ($movies->channel->item as $item) {
  $tittle= $item->title."
";
  $link=$item->link."
";
  $image=$item->medium_image_url."
";
  $des=$item->description."
";
  $city=$item->city;

  echo $tittle.$link.$image.$des.$city;
}

A:  foreach($movies->channel->item as $opt){
     echo $tittle= $opt->title."
";
     echo $link=$opt->link."
";
     echo $image=$opt->medium_image_url."
";
     echo $des=$opt->description."
";
     echo $city=$opt->city;
 }

A: foreach ($movies->channel->item as $item) {
  echo $item->title.'
';
  echo $item->link.'
';
  echo $item->medium_image_url.'
';
  echo $item->description.'
';
  echo $item->city;
}

I have echoed them because I think this is what you are wanting to do - your code reassigns variables on each iteration but does nothing with them. They are overwritten each time, so they will only hold the values from the last iteration at the end.
EDIT
You can easily modify this to insert rows into your database by doing something like this:
foreach ($movies->channel->item as $item) {
  echo $item->title.'
';
  echo $item->link.'
';
  echo $item->medium_image_url.'
';
  echo $item->description.'
';
  echo $item->city.'
';

  // Build the query - change the names of your table and columns as appropriate
  $query = "INSERT INTO `tablename`
              (`title`,`link`,`medium_image_url`,`description`,`city`)
            VALUES
              ('$item->title','$item->link','$item->medium_image_url','$item->description','$item->city')";
  // Do the query - do NOT show the output of mysql_error() in a production environment!
  if (!mysql_query($query)) echo 'Oh no! Something went wrong with the query: '.mysql_error();
}

Alternatively, you can turn it all into one query, to minimise database traffic:
$rows = array();
foreach ($movies->channel->item as $item) {
  echo $item->title.'
';
  echo $item->link.'
';
  echo $item->medium_image_url.'
';
  echo $item->description.'
';
  echo $item->city.'
';
  // Add this entry to $rows
  $rows[] = "('$item->title','$item->link','$item->medium_image_url','$item->description','$item->city')";
}

// Build the query - change the names of your table and columns as appropriate
$query = "INSERT INTO `tablename`
            (`title`,`link`,`medium_image_url`,`description`,`city`)
          VALUES ".implode(', ',$rows);
// Do the query - do NOT show the output of mysql_error() in a production environment!
if (!mysql_query($query)) echo 'Oh no! Something went wrong with the query: '.mysql_error();

A: This should work:
foreach ($movies as $movie)
    $tittle = $movie->title."
";
    $link = $movies->link."
";
    $image = $movie->medium_image_url."
";
    $des = $movie->description."
";
    $city = $movie->city;
}


text:
Q: Hyper-V and Drobo Pro I'm considering getting a fully loaded Drobo Pro and using it to store VHDs that would run our on a pair of Hyper-V host machines.  The host machines would connect to the Drobo Pro via iScsi.
Anyone have experience with the Drobo Pro and Hyper-V?  My main questions/concern is about speed - is the Drobo fast enough to handle say a dozen VHDs all running concurrently?

A: Over a gigabit ethernet connection, you're only going to get a maximum of 120MB/sec.  And that's best-case, you'll probably top out at 100, and that's even if the Drobo can keep up with that (though I've heard it can).
I've used iSCSI from an EMC Celerra over the same transport - it did relatively well for 10 or so low-usage hosts, 1 SQL server doing maybe 250-500tps and a Clearcase server doing probably triple that.

A: Personally until there's more information out there on the Drobo Pro's I would avoid them.  The regular Drobo is not enterprise grade equipment and has lackluster performance.  I would have to be convinced that the Pro is up to enterprise grade before deploying it in a production environment.
I know a while back on the Xen mailing list there was at least one thread with a user trying to use a Drobo Pro for the storage for Xen Virtual Machines.  And they were running into IO errors with it.  So you may or may not run into the same or similar issues with Hyper-V.  So be prepared to do some testing.

A: I am on the Product Marketing team at Data Robotics, so I'm hoping I can shed some light on the questions around the DroboPro, performance, and virtualization.
Regarding DroboPro performance, there are a few independent reviews that have posted performance numbers. One is GeekBrief.tv and the other is the LA Final Cut Pro User Group.
Here is the LAFCPUG review and the Geekbrief one can easily be found at Geekbrief.tv
http://www.lafcpug.org/reviews/review_drobopro.html
Feel free to check out the full reviews. In terms of iSCSI performance, LAFCPUG used a tool called Blackmagic and saw ~80MB/s read and ~70MB/s write. GeekBrief.tv used a tool called AJA and saw ~74MB/s read and ~79MB/s write. Burst speeds will certainly be higher as darthcoder alluded in his post, but 80MB/s is close to the limit in terms of sustained throughput on a single GbE.
One thing to note in the Geekbrief.tv review is that there was no mention of attaching the DroboPro directly to a switch which is very easy to do by simply assigning a fixed IP via the USB management port prior to attaching the switch. The latest version of our Dashboard management software has support for multi-host and up to 16 x 16TB virtual volumes.
Regarding virtualization, Data Robotics is in the process of certifying the DroboPro with VMware ESX which is the top priority due to market share. Having said that, we will be doing similar certifications with Microsoft Hyper-V and Citrix XenServer once the VMware certification is complete. While we have not yet officially performed testing with Hyper-V or Xenserver, we are aware of several customers that are successfully using Drobo and DroboPro with VMware, Hyper-V, and Xen.
In regards to your question of whether or not DroboPro is fast enough to handle a dozen VHDs all running concurrently, it should work just fine, but it really depends on the workload.
Hope that helps clarify things.

A: I can second Michael's statement that the DroboPro works well with Windows hosts and am seeing the good file copy numbers he is seeing.
The bad news is that we are trying to use the DroboPro to house VMWare ESXi 3.5 datastores and are seeing poor performance in that use case.  We've configured the DroboPro per the VMWare best practices whitepaper, have it filled with 8x750 Gb 32 meg cache 7200 rpm Samsung drives with double parity on the storage and are getting substandard VMWare performance. We haven't been able to get much more than 10 MB/second despite the direct connect 1Gbps full duplex network connecting the DroboPro to our Dell PowerEdge 2900 ESXi server.
After 10 days of troubleshooting with support the answer we were given was "In regards to the performance issue, this will require a firmware update on DroboPro. This is currently being worked on and we hope to release jan/feb. time frame."

A: I bought a 4TB Drobo Pro to run hyper-v for some of my development boxes. I'm using the iSCSI interface, and carved the drives up into 3 1GB partitions. I get good performance copying to and from the drobo, but as others had said the hyper-v performance is quite bad if you have a heavy IO load. I've been able to make it usable by moving some of the .vhd files to the different partitions.

A: Just to add my 2c to an already well answered question, if you are looking at storage for VMs it's a really good idea to think about each VM as an individual, with it's own storage needs, rather than being just part of a clump of VMs.  For this reason, it may be fine to consolidate your VM system boot files on one volume of SATA drives, but if you're after performance and running a SQL database then it's best to have separate heads for data, logs, temp and so on.  Similar scenarios would apply to media streaming, backup servers, anything were there are sizeable amounts of IO.
I've not used Drobo, but I appreciate they offer a simple solution to SMBs and to those developers who are hardware/sysadmin averse (i.e. most developers in my experience).  There are so many good iSCSI solutions around at the moment, and standalone iSCSI target software is getting really good.  If I were to build an iSCSI system now, I would probably look on ebay for a mid-range DAS shelf with about 12 SAS disks and couple it with a rack server that has a good raid card (or two) and is running an iSCSI target (Windows Storage Server 2008 r2 would be perfect in your case).  It won't be as pretty as a Drobo (or nearly as quiet), but it will be flexible, adaptable and if you configure it well, you'll get better performance.


text:
Q: Different instance methods generate the same object of inner class Here's a question about python. Apologies in advance if this is too basic.
Consider the following:
class H:
    pass

class D:
    def f(self):
        h = H()
        print("h:", h)

class C:
    def __init__(self):
        d1 = D()
        d2 = D()
        print("d1:", d1)
        print("d2:", d2)
        d1.f()
        d2.f()

c = C()

The output is the following:
d1: <__main__.D object at 0x1010fa6d8>
d2: <__main__.D object at 0x1010fa710>
h: <__main__.H object at 0x1010fa748>
h: <__main__.H object at 0x1010fa748>

Why is the H object being created the same, since it's being generated from two different instances of class D?
How can I create a different instance of H for each instance of D?


text:
Q: How to undo quick formatted linux partition from windows? I accidentally formatted my Linux(centos) root partition from windows.
How can I undo this?

A: You could retrieve the partition with TestDisk.
Testdisk is a console tool to recover missing partitions and files. It depends how much the disk has been overwritten, but I had good results regardless.
How to
Taken from here

*

*Start the program.

*Select the Create Log option.

*Select the disk that had the partition in the next screen. If You have more than one disk, this might be hard if You don't recognize the disks. Otherwise there will be only one option.

*Select the partition table (Intel/PC for MBR).

*Select analyze and Quick Search. Wait for the program to complete.

*If the partition is not found or the partition doesn't correspond with the expected size, then You can try a deep scan, which could take hours to complete depending on the disk size.

*If the partition was found, then select the Write option.


text:
Q: Client Certificate on iOS: Best Practices I am developing an application that will use a personal client certificate to verify the user's identity. The user will be issued the certificate from their company/organization, and will then have to install it on the phone somehow.
So my question is this: is it better for them to install it in the phone's built in storage, and the app would pull this cert from the OS, OR have the user add the cert to the application's doc folder via iTunes and load it from there?
The advantage of the cert being in the doc folder is that it's easy to locate an load into the app, but I'm not sure if that is considered "best practice."
Is there anyone out there who has actually done client certificates who can offer their input on the matter?

A: Through my research I have discovered that Apple does not support client certificates/PKI at this time. However if someone finds a work around, or if Apple adds this feature, please post your information here.


text:
Q: Why are DateTime Strings 0-padded On One Windows 10 System, but Not On Most Others? The following code on several machines sets a SQL Server date time string from "NOW" to the same date but at midnight.
DateTime deleteDateThreshold = DateTime.Now;
string deleteDateThresholdS = DateTime.Now.ToString();
deleteDateThresholdS = deleteDateThresholdS.Substring(0, 10) + " " + "00:00:00 AM";

Come to think of it, I could have probably subtracted back to midnight, but I thought this was a faster way.
Then the string gets parsed into a DateTime; and has one day subtracted from it. One one system, the parse blows up, because the Substring encounters an extra character, value of 2, because the date string is not zero-padded (03/04/2020). I finally was able to capture the offending date time; and it's not a DateTime, so the exception should occur.
Here is the code that parses.
deleteDateThreshold = DateTime.Parse(deleteDateThresholdS, us);
deleteDateThreshold = deleteDateThreshold.AddDays(-1);

on most systems, the date string looks like this
"03/04/2020 00:00:00 AM"

However, on the system that throws the exception, the dates are not 0-padded, and the string looks like this:
"3/4/2020 2 00:00:00"

Why is there a 2 in this string, and why are the month and day not 0-padded?

A:
Come to think of it, I could have probably subtracted back to midnight, but I thought this was a faster way.

I'd say that <somedate>.Date or DateTime.Today (thanks, @ckuri) is probably the easiest way to get to the (local) midnight for somedate/today. (Perhaps consider using UtcNow throughout all your systems though)
What the true nature of your problem is, I'm not sure at this point but I'm near certain it wouldn't happen if you kept your dates as dates and didn't convert in and out of strings to manipulate them; SQL Server has date datatypes, that map to CLR datatypes - there shouldn't be any need at all to store, process, transit or manipulate a date as a string in this system at all


text:
Q: Change StatusBar color and show ActionMode at the same time I change status bar color whenever action mode is shown using this piece of code:
override fun onActionModeStarted(mode: ActionMode?) {
    super.onActionModeStarted(mode)
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
        window?.statusBarColor = colorBlue
    }
}

The problem is action mode shows up with an animation while window.statusBarColo = changes status bar color immediately and as a result status bar color is changed a little bit sooner than action mode being displayed and it is so unpleasant to see. Do you guys have any solution for this?