问:
How to call an external function inside a view in laravel 5.2
I want to call an external function from my blade view.

I have tried in this way,

```<code>{{ controllername::function name()}}
</code>```

But i get a response like Class 'controllername' not found.

How i can solve this?Looking for a solution.

答:
If you have a function which is being used at multiple places you should define it in helpers file, to do so create one (may be) in app/Http/Helpers folder and name it helpers.php, mention this file in autorun block of your composer.json in following way :

```<code>"autoload": {
    "classmap": [
        "database"
    ],
    "psr-4": {
        "App\\": "app/"
    },
    "files": [
        "app/Http/Helpers/helpers.php"
    ]
},
</code>```

run composer dump-autoload, and then you may call this function from anywhere, let it be controller view or model.

or if you don't need to put in the helpers. You can just simply call it from it's controller. Just make it a  static function. Create.

```<code>public static function funtion_name($args) {}
</code>```

Call.

```<code>\App\Http\Controllers\ControllerName::function_name($args)
</code>```

If you don't like the very long code, you can just make it

```<code>ControllerName::function_name($args)
</code>```

but don't forget to call it from the top of the view page.

```<code>use \App\Http\Controllers\ControllerName;
</code>```

Body:
I want to call an external function from my blade view.

I have tried in this way,

{{ controllername::function name()}}

But i get a response like Class 'controllername' not found.

How i can solve this?Looking for a solution.

Body:
If you have a function which is being used at multiple places you should define it in helpers file, to do so create one (may be) in app/Http/Helpers folder and name it helpers.php, mention this file in autorun block of your composer.json in following way :

"autoload": {
    "classmap": [
        "database"
    ],
    "psr-4": {
        "App\\": "app/"
    },
    "files": [
        "app/Http/Helpers/helpers.php"
    ]
},

run composer dump-autoload, and then you may call this function from anywhere, let it be controller view or model.

or if you don't need to put in the helpers. You can just simply call it from it's controller. Just make it a  static function. Create.

public static function funtion_name($args) {}

Call.

\App\Http\Controllers\ControllerName::function_name($args)

If you don't like the very long code, you can just make it

ControllerName::function_name($args)

but don't forget to call it from the top of the view page.

use \App\Http\Controllers\ControllerName;


来源: stackexchange

问:
Can Unity Framework instantiate a class in a different namespace than a given interface?
I have an interface:

```<code>namespace IF.Model
{
    public interface IAllocationGroupRepository
    {
    }
}
</code>```

and a class the implements that interface:

```<code>using IF.Model;
namespace IF.Repository
{
    public class AllocationGroupRepository : IAllocationGroupRepository
    {
    }
}
</code>```

In a Unity Framework call, I can .RegisterType() in the code for both of them:

```<code> IUnityContainer container = new UnityContainer();
 container.RegisterType<IAllocationItemRepository, AllocationItemRepository>();
 IAllocationItemRepository _allocationItemRepository = container.Resolve<IAllocationItemRepository>();
</code>```

and .Resolve() works and gives me a new AllocationItemRepository object.

BUT, when I try to call Resolve and the mapping lives in the app.config file, I get this error:

"The current type, IF.Model.IAllocationItemRepository, is an interface and cannot be constructed. Are you missing a type mapping?"

Here is what my app.config file looks like:

```<code>    <unity>
        <containers>
            <container>
                <types>
                    <type
                        type="IF.Model.IAllocationGroupRepository, IF.Model"
                        mapTo="IF.Repository.AllocationGroupRepository, IF.Repository" />
                </types>
            </container>
        </containers>
    </unity>
</code>```

here is what the code looks like trying to call .Resolve() using what's in the App.config file:

```<code>IUnityContainer container = new UnityContainer();
UnityConfigurationSection section = (UnityConfigurationSection)ConfigurationManager.GetSection("unity");
section.Containers.Default.Configure(container);
IAllocationItemRepository _allocationItemRepository = container.Resolve<IAllocationItemRepository>();
</code>```

as you can see, this is pretty basic stuff. Given an interface, resolve it to the class. It works when doing it inline, but fails when trying to do it from the app.config file.

What am I missing here?

Thanks,
Mike

答:
I'm assuming you a have unity reference, then you need to define your section name and its library. like so:</p>

```<code><?xml version="1.0"?>
<configuration>
  <configSections>
 <section name="mySectionName" type="Microsoft.Practices.Unity.Configuration.UnityConfigurationSection, Microsoft.Practices.Unity.Configuration"/>
  </configSections>
  <mySectionName>
    <typeAliases>
     ...
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I have an interface:

namespace IF.Model
{
    public interface IAllocationGroupRepository
    {
    }
}

and a class the implements that interface:

using IF.Model;
namespace IF.Repository
{
    public class AllocationGroupRepository : IAllocationGroupRepository
    {
    }
}

In a Unity Framework call, I can .RegisterType() in the code for both of them:

 IUnityContainer container = new UnityContainer();
 container.RegisterType<IAllocationItemRepository, AllocationItemRepository>();
 IAllocationItemRepository _allocationItemRepository = container.Resolve<IAllocationItemRepository>();

and .Resolve() works and gives me a new AllocationItemRepository object.

BUT, when I try to call Resolve and the mapping lives in the app.config file, I get this error:

"The current type, IF.Model.IAllocationItemRepository, is an interface and cannot be constructed. Are you missing a type mapping?"

Here is what my app.config file looks like:

    <unity>
        <containers>
            <container>
                <types>
                    <type
                        type="IF.Model.IAllocationGroupRepository, IF.Model"
                        mapTo="IF.Repository.AllocationGroupRepository, IF.Repository" />
                </types>
            </container>
        </containers>
    </unity>

here is what the code looks like trying to call .Resolve() using what's in the App.config file:

IUnityContainer container = new UnityContainer();
UnityConfigurationSection section = (UnityConfigurationSection)ConfigurationManager.GetSection("unity");
section.Containers.Default.Configure(container);
IAllocationItemRepository _allocationItemRepository = container.Resolve<IAllocationItemRepository>();

as you can see, this is pretty basic stuff. Given an interface, resolve it to the class. It works when doing it inline, but fails when trying to do it from the app.config file.

What am I missing here?

Thanks,
Mike

Body:
I'm assuming you a have unity reference, then you need to define your section name and its library. like so:

<?xml version="1.0"?>
<configuration>
  <configSections>
 <section name="mySectionName" type="Microsoft.Practices.Unity.Configuration.UnityConfigurationSection, Microsoft.Practices.Unity.Configuration"/>
  </configSections>
  <mySectionName>
    <typeAliases>
     ...

ContentLicense: CC BY-SA 3.0


问:
Spring security oauth2 server - intercept unauthorized denied access
I'd like to intercept below access denied response from a spring cloud oauth2 authorisation server:

```<code><oauth>
<error_description>
Full authentication is required to access this resource
</error_description>
<error>unauthorized</error>
</oauth>
</code>```

I'like to intercept the exception and do some custom redirection or display custom page.

Any hints on how to do that?

Thanks in advance.

答:
Finally solved it by extending ResourceServerConfigurerAdapter and override configure(http) method with this additional code:

```<code>...
http.exceptionHandling().authenticationEntryPoint(unauthorizedEntryPoint());
...

@Bean
    public AuthenticationEntryPoint unauthorizedEntryPoint() {

        return (request, response, authException) -> {
            LOGGER.info("\n!!!!!!!! unauthorized: {} !!!!!!!!!!!!", authException.getMessage());
            String uri = request.getContextPath() + "/login";
            if(loadBalancerClient!=null && loadBalancerClient.choose("API-GATEWAY") != null) {
                uri = loadBalancerClient.choose("API-GATEWAY").getUri().toString();
            }
            response.sendRedirect(uri);
        };
    }
</code>```

Body:
I'd like to intercept below access denied response from a spring cloud oauth2 authorisation server:

<oauth>
<error_description>
Full authentication is required to access this resource
</error_description>
<error>unauthorized</error>
</oauth>

I'like to intercept the exception and do some custom redirection or display custom page.

Any hints on how to do that?

Thanks in advance.

Body:
Finally solved it by extending ResourceServerConfigurerAdapter and override configure(http) method with this additional code:

...
http.exceptionHandling().authenticationEntryPoint(unauthorizedEntryPoint());
...

@Bean
    public AuthenticationEntryPoint unauthorizedEntryPoint() {

        return (request, response, authException) -> {
            LOGGER.info("\n!!!!!!!! unauthorized: {} !!!!!!!!!!!!", authException.getMessage());
            String uri = request.getContextPath() + "/login";
            if(loadBalancerClient!=null && loadBalancerClient.choose("API-GATEWAY") != null) {
                uri = loadBalancerClient.choose("API-GATEWAY").getUri().toString();
            }
            response.sendRedirect(uri);
        };
    }


问:
EditText multiline not working
I have this XML:

```<code><EditText
    android:id="@+id/textchat"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentBottom="true"
    android:layout_alignParentLeft="true"
    android:ems="10"
    android:inputType="textMultiLine" />
</code>```

But, when I start to write on it, it stops after a number of characters. I would like to remove completely the character limit. Somebody knows how? Thanks.

EDIT: Complete XML

```<code><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".ChatActivity" >

<ImageView
    android:id="@+id/imageView1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentLeft="true"
    android:layout_alignParentTop="true"
    android:src="@drawable/logotipo_high_density_vinceri_movil" />

<ImageView
    android:id="@+id/imageView2"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentTop="true"
    android:layout_toRightOf="@+id/imageView1"
    android:src="@drawable/home_high_density_vinceri_movil" />

<ImageView
    android:id="@+id/imageView3"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentTop="true"
    android:layout_toRightOf="@+id/imageView2"
    android:src="@drawable/alertas_high_density_vinceri_movil" />

<ListView
    android:id="@+id/android:list"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_above="@+id/textchat"
    android:layout_alignParentLeft="true"
    android:layout_below="@+id/imageView1"
    android:background="@drawable/fondo_chat_cuerpo_high_density_vinceri_movil"
    android:divider="@null"
    android:stackFromBottom="true"
    android:transcriptMode="normal"
    >

</ListView>

<EditText
    android:id="@+id/textchat"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentBottom="true"
    android:layout_alignParentLeft="true"
    android:ems="10"
    android:inputType="textMultiLine"
    android:maxLength="1000"/>

<Button
    android:id="@+id/chatbutton"
    android:layout_width="wrap_content"
    android:layout_height="40dp"
    android:layout_alignParentBottom="true"
    android:layout_alignParentRight="true"
    android:layout_toRightOf="@+id/textchat"
    android:background="@drawable/chat_btn_enviar_high_density_vinceri_movil" />

</RelativeLayout>
</code>```

答:
As suggested by david m lee It's worked:

```<code>android:inputType="textMultiLine"
</code>```

Title: EditText multiline not working

Body:
I have this XML:

<EditText
    android:id="@+id/textchat"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentBottom="true"
    android:layout_alignParentLeft="true"
    android:ems="10"
    android:inputType="textMultiLine" />

But, when I start to write on it, it stops after a number of characters. I would like to remove completely the character limit. Somebody knows how? Thanks.

EDIT: Complete XML

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".ChatActivity" >

<ImageView
    android:id="@+id/imageView1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentLeft="true"
    android:layout_alignParentTop="true"
    android:src="@drawable/logotipo_high_density_vinceri_movil" />

<ImageView
    android:id="@+id/imageView2"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentTop="true"
    android:layout_toRightOf="@+id/imageView1"
    android:src="@drawable/home_high_density_vinceri_movil" />

<ImageView
    android:id="@+id/imageView3"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentTop="true"
    android:layout_toRightOf="@+id/imageView2"
    android:src="@drawable/alertas_high_density_vinceri_movil" />

<ListView
    android:id="@+id/android:list"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_above="@+id/textchat"
    android:layout_alignParentLeft="true"
    android:layout_below="@+id/imageView1"
    android:background="@drawable/fondo_chat_cuerpo_high_density_vinceri_movil"
    android:divider="@null"
    android:stackFromBottom="true"
    android:transcriptMode="normal"
    >

</ListView>

<EditText
    android:id="@+id/textchat"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentBottom="true"
    android:layout_alignParentLeft="true"
    android:ems="10"
    android:inputType="textMultiLine"
    android:maxLength="1000"/>

<Button
    android:id="@+id/chatbutton"
    android:layout_width="wrap_content"
    android:layout_height="40dp"
    android:layout_alignParentBottom="true"
    android:layout_alignParentRight="true"
    android:layout_toRightOf="@+id/textchat"
    android:background="@drawable/chat_btn_enviar_high_density_vinceri_movil" />

</RelativeLayout>

Body:
As suggested by david m lee It's worked:

android:inputType="textMultiLine"


问:
Java: duplicate method signature in nested class
Hopefully this question hasn't already been asked. I've had a look around but haven't found a similar post.

Experimenting in Java I've noticed that there is no restriction on having duplicate method signatures in a nested class, which seems counter-intuitive.

For example, if I create class A containing a method with the signature int x() and later add a nested class B containing an identical method, the compiler seems to have no problem with it. My initial assumption was that it would complain that x is already defined. Perhaps I'm missing something obvious that explains why this is allowed?

```<code>class A {
    int x() {
        return 1;
    }

    class B {
        int x() {
            return 2;
        }
    }
}
</code>```

Subsequently, is there any way to access class A's method x from within the scope of class B, or is it permanently hidden by the method x of the local scope?

Edit: I appreciate that the core of the question is the same as this post, however, I was more interested in understanding why this behaviour is allowed as it wasn't immediately clear to me.

答:
B is nested inside A. According to scope rules we can do the following:

```<code>class A {
    int x() {
        return 1;
    }

    class B {
        int x() {
            return 2;
        }

        int xOfA(){
            return A.this.x();
        }
    }

    public static void main(String[] args) {
        final A objA = new A();
        final B objB = objA.new B();
        System.out.println(objA.x());
        System.out.println(objB.x());
        System.out.println(objB.xOfA());
    }
}
</code>```

that is because B is visible from an instance of A.
Moreover B can reference methods in the containing class through their full paths.

Body:
Hopefully this question hasn't already been asked. I've had a look around but haven't found a similar post.

Experimenting in Java I've noticed that there is no restriction on having duplicate method signatures in a nested class, which seems counter-intuitive.

For example, if I create class A containing a method with the signature int x() and later add a nested class B containing an identical method, the compiler seems to have no problem with it. My initial assumption was that it would complain that x is already defined. Perhaps I'm missing something obvious that explains why this is allowed?

class A {
    int x() {
        return 1;
    }

    class B {
        int x() {
            return 2;
        }
    }
}

Subsequently, is there any way to access class A's method x from within the scope of class B, or is it permanently hidden by the method x of the local scope?

Edit: I appreciate that the core of the question is the same as this post, however, I was more interested in understanding why this behaviour is allowed as it wasn't immediately clear to me.

Body:
B is nested inside A. According to scope rules we can do the following:

class A {
    int x() {
        return 1;
    }

    class B {
        int x() {
            return 2;
        }

        int xOfA(){
            return A.this.x();
        }
    }

    public static void main(String[] args) {
        final A objA = new A();
        final B objB = objA.new B();
        System.out.println(objA.x());
        System.out.println(objB.x());
        System.out.println(objB.xOfA());
    }
}

that is because B is visible from an instance of A.
Moreover B can reference methods in the containing class through their full paths.


问:
Removing array from multidimensional array based off array values
I am currently attempting to create a add to cart and remove from cart function for my website. Currently, I am storing the user's information in a session variable name shopping cart. print_r that session variable as the following format was returned to me:

```<code>Array
(
    [0] => Array
        (
            [productID] => 3
            [productTitle] => Life Without Limits
            [productAuthor] => Nick Vujicic
            [productImg] => nickvujicic/lifewithoutlimits
            [productPrice] => 38.00
        )

    [1] => Array
        (
            [productID] => 4
            [productTitle] => Stand Strong
            [productAuthor] => Nick Vujicic
            [productImg] => nickvujicic/standstrong
            [productPrice] => 25.00
        )
)
</code>```

I was able to get the add to cart function working, but I'm currently stuck at the remove from cart function. When a user clicks on the remove button, that particular productID will be sent via ajax to my php file, and from there I would like to remove the product array from the shopping cart array. For example, if I want to remove a product with productID = 3, the shopping cart array should only return:

```<code>Array
(
    [0] => Array
        (
            [productID] => 4
            [productTitle] => Stand Strong
            [productAuthor] => Nick Vujicic
            [productImg] => nickvujicic/standstrong
            [productPrice] => 25.00
        )
)
</code>```

How do I go about achieving this? Thank you for your help in advance!

答:
It's not tested

```<code>foreach ($arr as $k => $item) {
    if ($item['productID'] == $productID) {
          unset($arr[$k]);
          break;
    }
}
</code>```

If you want to restore indexes after removing item

```<code>$arr = array_values($arr);
</code>```

Body:
I am currently attempting to create a add to cart and remove from cart function for my website. Currently, I am storing the user's information in a session variable name shopping cart. print_r that session variable as the following format was returned to me:

Array
(
    [0] => Array
        (
            [productID] => 3
            [productTitle] => Life Without Limits
            [productAuthor] => Nick Vujicic
            [productImg] => nickvujicic/lifewithoutlimits
            [productPrice] => 38.00
        )

    [1] => Array
        (
            [productID] => 4
            [productTitle] => Stand Strong
            [productAuthor] => Nick Vujicic
            [productImg] => nickvujicic/standstrong
            [productPrice] => 25.00
        )
)

I was able to get the add to cart function working, but I'm currently stuck at the remove from cart function. When a user clicks on the remove button, that particular productID will be sent via ajax to my php file, and from there I would like to remove the product array from the shopping cart array. For example, if I want to remove a product with productID = 3, the shopping cart array should only return:

Array
(
    [0] => Array
        (
            [productID] => 4
            [productTitle] => Stand Strong
            [productAuthor] => Nick Vujicic
            [productImg] => nickvujicic/standstrong
            [productPrice] => 25.00
        )
)

How do I go about achieving this? Thank you for your help in advance!

Body:
It's not tested

foreach ($arr as $k => $item) {
    if ($item['productID'] == $productID) {
          unset($arr[$k]);
          break;
    }
}

If you want to restore indexes after removing item

$arr = array_values($arr);


问:
Sum and Average gives incorrect output
I have this code for calculating sum and average, but it gives me wrong calculations. Do you have any idea why?</p>

```<code>import java.util.Scanner;

public class SumAndAverage {
   public static void main(String args[]) {
       Scanner input = new Scanner(System.in);

       System.out.print("Enter a lower bound then an upper bound:");

       double sum = 0;
       double average;
       int lowerbound = input.nextInt();
       int upperbound = input.nextInt();

       System.out.println("The upper bound " + upperbound);

       for(int number = lowerbound; number <= upperbound; number++) {
           sum += number;
       }

       average = sum/upperbound;
       System.out.println("The sum is " +sum);
       System.out.println("The average is " + average);
   }
}
</code>```

答:
To get the sum you should just add the two numbers. No for loop is needed. This makes your code work even if the lowerbound is larger than the upperbound.

To get the average of two numbers you should divide them by their count not their upper bound.

Example:

```<code>package foo;

import java.util.Scanner;

public class SumAndAverage {

    public static void main(String args[]) {
        Scanner input = new Scanner(System.in);

        System.out.print("Enter a lower bound then an upper bound:");

        double sum = 0;
        double average;
        int lowerbound = input.nextInt();
        int upperbound = input.nextInt();

        System.out.println("The upper bound " + upperbound);

        sum = lowerbound + upperbound;
        // for (int number = lowerbound; number <= upperbound; number++) {
    //
    // sum += number;
    //
    // }

    average = sum / 2;
    System.out.println("The sum is " + sum);
    System.out.println("The average is " + average);

 }
}
</code>```

Title: Sum and Average gives incorrect output

Body:
I have this code for calculating sum and average, but it gives me wrong calculations. Do you have any idea why?

import java.util.Scanner;

public class SumAndAverage {
   public static void main(String args[]) {
       Scanner input = new Scanner(System.in);

       System.out.print("Enter a lower bound then an upper bound:");

       double sum = 0;
       double average;
       int lowerbound = input.nextInt();
       int upperbound = input.nextInt();

       System.out.println("The upper bound " + upperbound);

       for(int number = lowerbound; number <= upperbound; number++) {
           sum += number;
       }

       average = sum/upperbound;
       System.out.println("The sum is " +sum);
       System.out.println("The average is " + average);
   }
}

Body:
To get the sum you should just add the two numbers. No for loop is needed. This makes your code work even if the lowerbound is larger than the upperbound.

To get the average of two numbers you should divide them by their count not their upper bound.

Example:

package foo;

import java.util.Scanner;

public class SumAndAverage {

    public static void main(String args[]) {
        Scanner input = new Scanner(System.in);

        System.out.print("Enter a lower bound then an upper bound:");

        double sum = 0;
        double average;
        int lowerbound = input.nextInt();
        int upperbound = input.nextInt();

        System.out.println("The upper bound " + upperbound);

        sum = lowerbound + upperbound;
        // for (int number = lowerbound; number <= upperbound; number++) {
    //
    // sum += number;
    //
    // }

    average = sum / 2;
    System.out.println("The sum is " + sum);
    System.out.println("The average is " + average);

 }
}


问:
How to annotate MYSQL autoincrement field with JPA annotations
Straight to the point, problem is saving the object Operator into MySQL DB.
Prior to save, I try to select from this table and it works, so is connection to db.

Here is my Operator object:

```<code>@Entity
public class Operator{

   @Id
   @GeneratedValue
   private Long id;

   private String username;

   private String password;

   private Integer active;

   //Getters and setters...
}
</code>```

To save I use JPA EntityManager’s persist method.

Here is some log:

```<code>Hibernate: insert into Operator (active, password, username, id) values (?, ?, ?, ?)
com.mysql.jdbc.JDBC4PreparedStatement@15724a0: insert into Operator (active,password, username, id) values (0, 'pass', 'user', ** NOT SPECIFIED **)
</code>```

The way I see it, problem is configuration with auto increment but I can't figure out where.

Tried some tricks I've seen here:
Hibernate not respecting MySQL auto_increment primary key field But nothing of that worked

If any other configuration files needed I will provide them.

DDL:

```<code>CREATE TABLE `operator` (
`id` INT(10) NOT NULL AUTO_INCREMENT,
`first_name` VARCHAR(40) NOT NULL,
`last_name` VARCHAR(40) NOT NULL,
`username` VARCHAR(50) NOT NULL,
`password` VARCHAR(50) NOT NULL,
`active` INT(1) NOT NULL,
PRIMARY KEY (`id`)
)
</code>```

答:
Please make sure that id datatype is Long instead of String, if that
  will be string then @GeneratedValue annotation will not work and the
  sql generating for

```<code>@Id @GeneratedValue(strategy=GenerationType.IDENTITY)
private String id;

create table VMS_AUDIT_RECORDS (id **varchar(255)** not null auto_increment primary key (id))
</code>```

that  needs to be

```<code>create table VMS_AUDIT_RECORDS (id **bigint** not null auto_increment primary key (id))
</code>```

Body:
Straight to the point, problem is saving the object Operator into MySQL DB.
Prior to save, I try to select from this table and it works, so is connection to db.

Here is my Operator object:

@Entity
public class Operator{

   @Id
   @GeneratedValue
   private Long id;

   private String username;

   private String password;

   private Integer active;

   //Getters and setters...
}

To save I use JPA EntityManager’s persist method.

Here is some log:

Hibernate: insert into Operator (active, password, username, id) values (?, ?, ?, ?)
com.mysql.jdbc.JDBC4PreparedStatement@15724a0: insert into Operator (active,password, username, id) values (0, 'pass', 'user', ** NOT SPECIFIED **)

The way I see it, problem is configuration with auto increment but I can't figure out where.

Tried some tricks I've seen here:
Hibernate not respecting MySQL auto_increment primary key field But nothing of that worked

If any other configuration files needed I will provide them.

DDL:

CREATE TABLE `operator` (
`id` INT(10) NOT NULL AUTO_INCREMENT,
`first_name` VARCHAR(40) NOT NULL,
`last_name` VARCHAR(40) NOT NULL,
`username` VARCHAR(50) NOT NULL,
`password` VARCHAR(50) NOT NULL,
`active` INT(1) NOT NULL,
PRIMARY KEY (`id`)
)

Body:
Please make sure that id datatype is Long instead of String, if that
  will be string then @GeneratedValue annotation will not work and the
  sql generating for

@Id @GeneratedValue(strategy=GenerationType.IDENTITY)
private String id;

create table VMS_AUDIT_RECORDS (id **varchar(255)** not null auto_increment primary key (id))

that  needs to be

create table VMS_AUDIT_RECORDS (id **bigint** not null auto_increment primary key (id))


问:
Pointer to variable inside a struct
I have a struct like this:

```<code>typedef struct{
    char *lexema;
    int comp_lexico;
    union{
        double v;
        double (*fnctptr)();
    } valor;
}tipoelem;

struct celda {
    tipoelem info;
    struct celda *izq, *der;
};

typedef struct celda * abb;
</code>```

Then I define a global variable abb, which has a global scope. If I get somehow the memory direction of the field info of celda, would I be able to modify it safely or It is better to define the field as a tipoelem pointer such as (tipoelem *info)?

The thing is, is it safe to edit the tipoelem info field with a tipoelem *pointerToInfo from other part of the prrogram or it is better to declare it as a pointer tipoelem *info in the struct celda?

Edited with more information:
The way I want to modify tipoelem info is the next one, and I do not know if it is safe.

```<code>abb a;
int main(){
    tipoelem *ptr = a->info;
    ptr->comp_lexico = 2;
}
</code>```

答:
I define a global variable abb,

It is not a variable, it is a type.

As an answer to the question after the edit:-

Now you can use abb, as a type similar to struct celda*.

After the edit the answer is simply what the problem demands.

For example:

if each instance of the struct celda is needed to contain a block information then it is better to allow a pointer to it inside the structure. That is a better thing in terms of design where closely related data are kept closely.

And another thing is suppose you keep a pointer to tipoelem outside of the structure variable. Then suppose after some time you will need another pointer to tipoelem then these two pointer to tipoelem is different in meaning. That's why it's better to keep in structure.

Title: Pointer to variable inside a struct

Body:
I have a struct like this:

typedef struct{
    char *lexema;
    int comp_lexico;
    union{
        double v;
        double (*fnctptr)();
    } valor;
}tipoelem;

struct celda {
    tipoelem info;
    struct celda *izq, *der;
};

typedef struct celda * abb;

Then I define a global variable abb, which has a global scope. If I get somehow the memory direction of the field info of celda, would I be able to modify it safely or It is better to define the field as a tipoelem pointer such as (tipoelem *info)?

The thing is, is it safe to edit the tipoelem info field with a tipoelem *pointerToInfo from other part of the prrogram or it is better to declare it as a pointer tipoelem *info in the struct celda?

Edited with more information:
The way I want to modify tipoelem info is the next one, and I do not know if it is safe.

abb a;
int main(){
    tipoelem *ptr = a->info;
    ptr->comp_lexico = 2;
}


问:
Angular 4 patchValue based on index in FormArray
I am looking to update a formArray after the user adds a value in an empty created control.

Currently when the user selects to add a new item i build onto the formArray with empty values.

```<code>buildItem(item?: any, key?: any): FormGroup {
  // Item will pass undefined for initial buildItem in onLoad and new items
  let itemName: string;
  let keyValue: string;
  if (item === undefined) {
     itemName = ''; key = '' }
  else {
     itemName = item.name; keyValue = key
  };

  /**
   * Builds a single item for form group array in the collectionForm.
   */
   return this.formBuilder.group({
                item: [itemName || '', Validators.required],
                properties: { item, key: key } || {} });
}
</code>```

This works fine for the initial creation and the update of items that are already added. The issue is with new items that are added with empty values. When i add a new item i need to add the return key from firebase in the properties.key

In the method for the save of that new item i added a patchValue

```<code>this.items.patchValue([{
         // item being returned from firebase promise
         item: item.name,
         properties: { item: item.name, key: item.$key' }
}]);
</code>```

However the patchValue is not  working at all. When i try the update that new value, although the values have been saved to firebase i still get a return for the values as empty or the save values set on the initial BuildItem() and not the updated values in the patchValue

I see on the angular FormArray Documentation that

It accepts an array that matches the structure of the control, and will do its best to match the values to the correct controls in the group. REF

Does that mean that it might and might not update that value .. it will just do its best to try? I figure if i can add the index for the value that i want to patch then it should not be a issue at all. like with the removeAt(idx)

So if i can write something like

```<code>this.form.patchValue.atIndex(this.idx,[{
         item: item.name,
         properties: { item: item.name, key: item.$key' }
}];
</code>```

But not sure i can do that .. well pretty sure that it not possible in that form. Is there any way to specifically target the item that gets patched in a formArray or am i maybe not understanding this correctly.

I can sort of get away with this by pushing the new value onto the formArray

```<code>this.items.push(this.buildItem(...));
</code>```

however then i have to add

```<code>this.items.removeAt(this.idx);
</code>```

In order to remove the initial control on the empty build , which does not seem like any sort of good code.

答:
You can do this simply by creating a new FormControl if you want to update the hole array structure:

```<code>this.form.setControl('items',  new FormControl(arrayItemsValue));
</code>```

Or by removing all items before updating them :

```<code>const items = (<FormArray>this.form.get('items'));
 for (let i = 0; i < items.length; i++) {
     items.removeAt(i);
 }
 this.form.get('items').setValue(arrayItemsValue);
</code>```

Body:
I am looking to update a formArray after the user adds a value in an empty created control.

Currently when the user selects to add a new item i build onto the formArray with empty values.

buildItem(item?: any, key?: any): FormGroup {
  // Item will pass undefined for initial buildItem in onLoad and new items
  let itemName: string;
  let keyValue: string;
  if (item === undefined) {
     itemName = ''; key = '' }
  else {
     itemName = item.name; keyValue = key
  };

  /**
   * Builds a single item for form group array in the collectionForm.
   */
   return this.formBuilder.group({
                item: [itemName || '', Validators.required],
                properties: { item, key: key } || {} });
}

This works fine for the initial creation and the update of items that are already added. The issue is with new items that are added with empty values. When i add a new item i need to add the return key from firebase in the properties.key

In the method for the save of that new item i added a patchValue

this.items.patchValue([{
         // item being returned from firebase promise
         item: item.name,
         properties: { item: item.name, key: item.$key' }
}]);

However the patchValue is not  working at all. When i try the update that new value, although the values have been saved to firebase i still get a return for the values as empty or the save values set on the initial BuildItem() and not the updated values in the patchValue

I see on the angular FormArray Documentation that

It accepts an array that matches the structure of the control, and will do its best to match the values to the correct controls in the group. REF

Does that mean that it might and might not update that value .. it will just do its best to try? I figure if i can add the index for the value that i want to patch then it should not be a issue at all. like with the removeAt(idx)

So if i can write something like

this.form.patchValue.atIndex(this.idx,[{
         item: item.name,
         properties: { item: item.name, key: item.$key' }
}];

But not sure i can do that .. well pretty sure that it not possible in that form. Is there any way to specifically target the item that gets patched in a formArray or am i maybe not understanding this correctly.

I can sort of get away with this by pushing the new value onto the formArray

this.items.push(this.buildItem(...));

however then i have to add

this.items.removeAt(this.idx);

In order to remove the initial control on the empty build , which does not seem like any sort of good code.

Body:
You can do this simply by creating a new FormControl if you want to update the hole array structure:

this.form.setControl('items',  new FormControl(arrayItemsValue));

Or by removing all items before updating them :

const items = (<FormArray>this.form.get('items'));
 for (let i = 0; i < items.length; i++) {
     items.removeAt(i);
 }
 this.form.get('items').setValue(arrayItemsValue);


问:
Counter in a loop is not echoed
I have a for loop in a batch file. I get this weird behaviour with the counter variable. I am an experienced programmer, but a beginner in batch files.

```<code>@ECHO OFF
SETLOCAL ENABLEEXTENSIONS

SET list=test1 test2 test3

FOR %%a IN (%list%) DO (
    SET variable=%%a
    ECHO %%a
    ECHO -%variable%-
)
</code>```

I expect the output to be

```<code>test1
-test1-
test2
-test2-
test3
-test3-
</code>```

but it actually is

```<code>test1
-test3-
test2
-test3-
test3
-test3-
</code>```

What am I doing wrong?

答:
The actual expected output is

```<code>test1
--
test2
--
test3
--
</code>```

I would be astonished to get anything else; I definitely cannot reproduce your output.

Variables are expanded only once, when the ( ... ) construction is read. If you want that the assignments inside ( ... ) to take effect within ( ... ) you need to setlocal enabledelayedexpansion and use !variable!. (Or, as some prefer, call a subroutine instead of using ( ... )).

Title: Counter in a loop is not echoed

Body:
I have a for loop in a batch file. I get this weird behaviour with the counter variable. I am an experienced programmer, but a beginner in batch files.

@ECHO OFF
SETLOCAL ENABLEEXTENSIONS

SET list=test1 test2 test3

FOR %%a IN (%list%) DO (
    SET variable=%%a
    ECHO %%a
    ECHO -%variable%-
)

I expect the output to be

test1
-test1-
test2
-test2-
test3
-test3-

but it actually is

test1
-test3-
test2
-test3-
test3
-test3-

What am I doing wrong?

Body:
The actual expected output is

test1
--
test2
--
test3
--

I would be astonished to get anything else; I definitely cannot reproduce your output.

Variables are expanded only once, when the ( ... ) construction is read. If you want that the assignments inside ( ... ) to take effect within ( ... ) you need to setlocal enabledelayedexpansion and use !variable!. (Or, as some prefer, call a subroutine instead of using ( ... )).


问:
akka stream asyncBoundary vs mapAsync
I am trying to understand the difference between asyncBoundary and mapAsync. From the glance, I guess they should be same. However, when I run the code, it looks like that the performance of asyncBoundary is quicker than mapAsync

Here is the code

```<code>implicit val system = ActorSystem("sourceDemo")
implicit val materializer = ActorMaterializer()

Source(1 to 100).mapAsync(100)(t => Future {t + 1}).mapAsync(100)(t => Future {t * 2}).map(println).to(Sink.ignore).run()
Source(1 to 100).map(_ + 1).withAttributes(Attributes.asyncBoundary).map(_ * 2).map(t => println("async boundary", t)).to(Sink.ignore).run()
</code>```

The output:
async boundary is always finished quicker than mayAsync.

From the document described about asyncBoundary (https://doc.akka.io/docs/akka-stream-and-http-experimental/current/scala/stream-flows-and-basics.html), I can see it is running on different CPU, but mapAsync is multi-threaded by using Future. Future is also asynchronous.

May I ask more clarification about this two APIs ?

答:
Async

As you correctly point out this forces the insertion of an asynchronous boundary between two stages. In your example

```<code>Source(1 to 100).map(_ + 1).withAttributes(Attributes.asyncBoundary).map(_ * 2).map(t => println("async boundary", t)).to(Sink.ignore).run()
</code>```

this practically means that the + 1 operation and the * 2 operation will be run by separated actors. This enables pipelining, as whilst an element moves on to the * 2 stage, at the same time another element can be brought in for the + 1 stage. If you don't force an async boundary there, the same actor will sequentialise the operations and will perform the operations on one element, before requesting a new one from upstream.

By the way, your example can be rewritten in a shorter format, using the async combinator:

```<code>Source(1 to 100).map(_ + 1).async.map(_ * 2).map(t => println("async boundary", t)).to(Sink.ignore).run()
</code>```

mapAsync

This is a stage to parallelise execution of asynchronous operations. The parallelism factor allows you to specify the maximum number of parallel actors to spin up to serve incoming elements. The results of the parallel computations are tracked and emitted in order by the mapAsync stage.

In your example

```<code>Source(1 to 100).mapAsync(100)(t => Future {t + 1}).mapAsync(100)(t => Future {t * 2}).map(println).to(Sink.ignore).run()
</code>```

potentially up to 100 + 1 operations (i.e. all of them) could be run in parallel, and the results collected in order. Subsequently, up to 100 * 2 operations could be run in parallel, and again the results collected in order and emitted downstream.

In your example you are running CPU-bound, quick operations that don't justify using mapAsync, as most likely the infrastructure needed by this stage is much more expensive than the advantage of running 100 of these operations in parallel. mapAsync is particularly useful when dealing with IO-bound, slow operations, where parallelisation is quite convenient.

For a comprehensive read on this topic, check out this blogpost.

Title: akka stream asyncBoundary vs mapAsync

Body:
I am trying to understand the difference between asyncBoundary and mapAsync. From the glance, I guess they should be same. However, when I run the code, it looks like that the performance of asyncBoundary is quicker than mapAsync

Here is the code

implicit val system = ActorSystem("sourceDemo")
implicit val materializer = ActorMaterializer()

Source(1 to 100).mapAsync(100)(t => Future {t + 1}).mapAsync(100)(t => Future {t * 2}).map(println).to(Sink.ignore).run()
Source(1 to 100).map(_ + 1).withAttributes(Attributes.asyncBoundary).map(_ * 2).map(t => println("async boundary", t)).to(Sink.ignore).run()

The output:
async boundary is always finished quicker than mayAsync.

From the document described about asyncBoundary (https://doc.akka.io/docs/akka-stream-and-http-experimental/current/scala/stream-flows-and-basics.html), I can see it is running on different CPU, but mapAsync is multi-threaded by using Future. Future is also asynchronous.

May I ask more clarification about this two APIs ?

Body:
Async

As you correctly point out this forces the insertion of an asynchronous boundary between two stages. In your example

Source(1 to 100).map(_ + 1).withAttributes(Attributes.asyncBoundary).map(_ * 2).map(t => println("async boundary", t)).to(Sink.ignore).run()

this practically means that the + 1 operation and the * 2 operation will be run by separated actors. This enables pipelining, as whilst an element moves on to the * 2 stage, at the same time another element can be brought in for the + 1 stage. If you don't force an async boundary there, the same actor will sequentialise the operations and will perform the operations on one element, before requesting a new one from upstream.

By the way, your example can be rewritten in a shorter format, using the async combinator:

Source(1 to 100).map(_ + 1).async.map(_ * 2).map(t => println("async boundary", t)).to(Sink.ignore).run()

mapAsync

This is a stage to parallelise execution of asynchronous operations. The parallelism factor allows you to specify the maximum number of parallel actors to spin up to serve incoming elements. The results of the parallel computations are tracked and emitted in order by the mapAsync stage.

In your example

Source(1 to 100).mapAsync(100)(t => Future {t + 1}).mapAsync(100)(t => Future {t * 2}).map(println).to(Sink.ignore).run()

potentially up to 100 + 1 operations (i.e. all of them) could be run in parallel, and the results collected in order. Subsequently, up to 100 * 2 operations could be run in parallel, and again the results collected in order and emitted downstream.

In your example you are running CPU-bound, quick operations that don't justify using mapAsync, as most likely the infrastructure needed by this stage is much more expensive than the advantage of running 100 of these operations in parallel. mapAsync is particularly useful when dealing with IO-bound, slow operations, where parallelisation is quite convenient.

For a comprehensive read on this topic, check out this blogpost.

ContentLicense: CC BY-SA 4.0


问:
Can you delete multiple branches in one command with Git?
I'd like to clean up my local repository, which has a ton of old branches: for example 3.2, 3.2.1, 3.2.2, etc.

I was hoping for a sneaky way to remove a lot of them at once. Since they mostly follow a dot release convention, I thought maybe there was a shortcut to say:

```<code>git branch -D 3.2.*
</code>```

and kill all 3.2.x branches.

I tried that command and it, of course, didn't work.

答:
You can use git branch --list to list the eligible branches, and use git branch -D/-d to remove the eligible branches. </p>

<p>One liner example: </p>

```<code>git branch -d `git branch --list '3.2.*'`
</code>```

Body:
I'd like to clean up my local repository, which has a ton of old branches: for example 3.2, 3.2.1, 3.2.2, etc.

I was hoping for a sneaky way to remove a lot of them at once. Since they mostly follow a dot release convention, I thought maybe there was a shortcut to say:

git branch -D 3.2.*

and kill all 3.2.x branches.

I tried that command and it, of course, didn't work.

Body:
You can use git branch --list to list the eligible branches, and use git branch -D/-d to remove the eligible branches.

One liner example:

git branch -d `git branch --list '3.2.*'`


问:
Dynamic datasource routing - DataSource router not initialized
I'm referring to this article, in which we can use the AbstractRoutingDataSource from Spring Framework to dynamically change the data source used by the application. I'm using Mybatis (3.3.0) with Spring (4.1.6.RELEASE). I want to switch to the backup database if exception occurs while getting data from main db. In this example, i have used hsql and mysql db.

RoutingDataSource:

```<code>public class RoutingDataSource extends AbstractRoutingDataSource {

@Override
protected Object determineCurrentLookupKey() {
    return DataSourceContextHolder.getTargetDataSource();
 }
}
</code>```

DataSourceContextHolder:

```<code>public class DataSourceContextHolder {

private static final ThreadLocal<DataSourceEnum> contextHolder = new ThreadLocal<DataSourceEnum>();

public static void setTargetDataSource(DataSourceEnum targetDataSource) {
    contextHolder.set(targetDataSource);
}

public static DataSourceEnum getTargetDataSource() {
    return (DataSourceEnum) contextHolder.get();
}

public static void resetDefaultDataSource() {
    contextHolder.remove();
 }
}
</code>```

ApplicationDataConfig:

```<code>@Configuration
@MapperScan(basePackages = "com.sample.mapper")
@ComponentScan("com.sample.config")
@PropertySource(value = {"classpath:app.properties"},
                ignoreResourceNotFound = true)
public class ApplicationDataConfig {

@Bean
public static PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer() {
    PropertySourcesPlaceholderConfigurer configurer =
        new PropertySourcesPlaceholderConfigurer();
    return configurer;
}

@Bean
public SqlSessionFactoryBean sqlSessionFactoryBean() throws Exception {
    SqlSessionFactoryBean sessionFactory = new SqlSessionFactoryBean();
    RoutingDataSource routingDataSource = new RoutingDataSource();
    routingDataSource.setDefaultTargetDataSource(dataSource1());
    Map<Object, Object> targetDataSource = new HashMap<Object, Object>();
    targetDataSource.put(DataSourceEnum.HSQL, dataSource1());
    targetDataSource.put(DataSourceEnum.BACKUP, dataSource2());
    routingDataSource.setTargetDataSources(targetDataSource);
    sessionFactory.setDataSource(routingDataSource);
    sessionFactory.setTypeAliasesPackage("com.sample.common.domain");

    sessionFactory.setMapperLocations(
        new PathMatchingResourcePatternResolver()
            .getResources("classpath*:com/sample/mapper/**/*.xml"));

    return sessionFactory;
}

@Bean
public DataSource dataSource1() {
    return new EmbeddedDatabaseBuilder().setType(EmbeddedDatabaseType.HSQL).addScript(
            "classpath:database/app-hsqldb-schema.sql").addScript(
            "classpath:database/app-hsqldb-datascript.sql").build();
}

@Bean
public DataSource dataSource2() {
    PooledDataSourceFactory pooledDataSourceFactory = new PooledDataSourceFactory();
    pooledDataSourceFactory.setProperties(jdbcProperties());
    return pooledDataSourceFactory.getDataSource();
}

@Bean
protected Properties jdbcProperties() {
    //Get the data from properties file
    Properties jdbcProperties = new Properties();
    jdbcProperties.setProperty("url", datasourceUrl);
    jdbcProperties.setProperty("driver", datasourceDriver);
    jdbcProperties.setProperty("username", datasourceUsername);
    jdbcProperties.setProperty("password", datasourcePassword);
    jdbcProperties.setProperty("poolMaximumIdleConnections", maxConnectionPoolSize);
    jdbcProperties.setProperty("poolMaximumActiveConnections", minConnectionPoolSize);

    return jdbcProperties;
}
}
</code>```

Client:

```<code> @Autowired
 private ApplicationMapper appMapper;

public MyObject getObjectById(String Id) {
    MyObject myObj = null;
    try{
        DataSourceContextHolder.setTargetDataSource(DataSourceEnum.HSQL);
        myObj = appMapper.getObjectById(Id);
    }catch(Throwable e){
        DataSourceContextHolder.setTargetDataSource(DataSourceEnum.BACKUP);
        myObj = appMapper.getObjectById(Id);
    }finally{
        DataSourceContextHolder.resetDefaultDataSource();
    }
    return getObjectDetails(myObj);
}
</code>```

I'm getting the following exception

```<code>### Error querying database.  Cause: java.lang.IllegalArgumentException: DataSource router not initialized
</code>```

However i'm able to get things working if i'm using only one db at a time, this means there is no issue with data source configuration.

答:
I got the same issue and found a solution using the SchemaExport class of hibernate.
For each DataSourceEnum you can manually initialize the datasource.

here is my detailed answer to my own issue discription

Body:
I'm referring to this article, in which we can use the AbstractRoutingDataSource from Spring Framework to dynamically change the data source used by the application. I'm using Mybatis (3.3.0) with Spring (4.1.6.RELEASE). I want to switch to the backup database if exception occurs while getting data from main db. In this example, i have used hsql and mysql db.

RoutingDataSource:

public class RoutingDataSource extends AbstractRoutingDataSource {

@Override
protected Object determineCurrentLookupKey() {
    return DataSourceContextHolder.getTargetDataSource();
 }
}

DataSourceContextHolder:

public class DataSourceContextHolder {

private static final ThreadLocal<DataSourceEnum> contextHolder = new ThreadLocal<DataSourceEnum>();

public static void setTargetDataSource(DataSourceEnum targetDataSource) {
    contextHolder.set(targetDataSource);
}

public static DataSourceEnum getTargetDataSource() {
    return (DataSourceEnum) contextHolder.get();
}

public static void resetDefaultDataSource() {
    contextHolder.remove();
 }
}

ApplicationDataConfig:

@Configuration
@MapperScan(basePackages = "com.sample.mapper")
@ComponentScan("com.sample.config")
@PropertySource(value = {"classpath:app.properties"},
                ignoreResourceNotFound = true)
public class ApplicationDataConfig {

@Bean
public static PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer() {
    PropertySourcesPlaceholderConfigurer configurer =
        new PropertySourcesPlaceholderConfigurer();
    return configurer;
}

@Bean
public SqlSessionFactoryBean sqlSessionFactoryBean() throws Exception {
    SqlSessionFactoryBean sessionFactory = new SqlSessionFactoryBean();
    RoutingDataSource routingDataSource = new RoutingDataSource();
    routingDataSource.setDefaultTargetDataSource(dataSource1());
    Map<Object, Object> targetDataSource = new HashMap<Object, Object>();
    targetDataSource.put(DataSourceEnum.HSQL, dataSource1());
    targetDataSource.put(DataSourceEnum.BACKUP, dataSource2());
    routingDataSource.setTargetDataSources(targetDataSource);
    sessionFactory.setDataSource(routingDataSource);
    sessionFactory.setTypeAliasesPackage("com.sample.common.domain");

    sessionFactory.setMapperLocations(
        new PathMatchingResourcePatternResolver()
            .getResources("classpath*:com/sample/mapper/**/*.xml"));

    return sessionFactory;
}

@Bean
public DataSource dataSource1() {
    return new EmbeddedDatabaseBuilder().setType(EmbeddedDatabaseType.HSQL).addScript(
            "classpath:database/app-hsqldb-schema.sql").addScript(
            "classpath:database/app-hsqldb-datascript.sql").build();
}

@Bean
public DataSource dataSource2() {
    PooledDataSourceFactory pooledDataSourceFactory = new PooledDataSourceFactory();
    pooledDataSourceFactory.setProperties(jdbcProperties());
    return pooledDataSourceFactory.getDataSource();
}

@Bean
protected Properties jdbcProperties() {
    //Get the data from properties file
    Properties jdbcProperties = new Properties();
    jdbcProperties.setProperty("url", datasourceUrl);
    jdbcProperties.setProperty("driver", datasourceDriver);
    jdbcProperties.setProperty("username", datasourceUsername);
    jdbcProperties.setProperty("password", datasourcePassword);
    jdbcProperties.setProperty("poolMaximumIdleConnections", maxConnectionPoolSize);
    jdbcProperties.setProperty("poolMaximumActiveConnections", minConnectionPoolSize);

    return jdbcProperties;
}
}

Client:

 @Autowired
 private ApplicationMapper appMapper;

public MyObject getObjectById(String Id) {
    MyObject myObj = null;
    try{
        DataSourceContextHolder.setTargetDataSource(DataSourceEnum.HSQL);
        myObj = appMapper.getObjectById(Id);
    }catch(Throwable e){
        DataSourceContextHolder.setTargetDataSource(DataSourceEnum.BACKUP);
        myObj = appMapper.getObjectById(Id);
    }finally{
        DataSourceContextHolder.resetDefaultDataSource();
    }
    return getObjectDetails(myObj);
}

I'm getting the following exception

### Error querying database.  Cause: java.lang.IllegalArgumentException: DataSource router not initialized

However i'm able to get things working if i'm using only one db at a time, this means there is no issue with data source configuration.


问:
How can I remove a commit on GitHub?
I "accidentally" pushed a commit to GitHub.

Is it possible to remove this commit?

I want to revert my GitHub repository as it was before this commit.

答:
if you want to remove do interactive rebase,

git rebase -i HEAD~4

4 represents total number of commits to display count your commit andchange it accordingly

and delete commit you want from list...

save changes by Ctrl+X(ubuntu) or :wq(centos)

2nd method, do revert,

```<code>git revert 29f4a2 #your commit ID
</code>```

this will revert specific commit

OwnerDisplayName: hectorsq

Title: How can I remove a commit on GitHub?

Body:
if you want to remove do interactive rebase,

git rebase -i HEAD~4

4 represents total number of commits to display count your commit andchange it accordingly

and delete commit you want from list...

save changes by Ctrl+X(ubuntu) or :wq(centos)

2nd method, do revert,

git revert 29f4a2 #your commit ID

this will revert specific commit


问:
What exactly Java EE6 and do I have choice not to include some of features?
When I looked into Java EE6 doc and some other articles, Java EE6 is a platform.

To me, platform is just Java with bunch of API/framework available like JSF, JPA, Web services  like REST. (more like bunch of jars maybe?)

So anyway I got Netbean6.9/Java EE6/GlassFish v3 bundle but figured I don't need JSF at all.

Is there a way to remove JSF from Java EE6 so that I can save some disc space on my server?

Sorry if my statement doesn't make sense because I'm not fully understand what exactly Java EE6 by reading documentation.. (or this JSF is bundled with Netbean6.9...)

Update:

I'm building REST web app so far using JAX-RS and JPA (toplink essential) and for UI side, JSF was going to be used but we decided not to, so wondering if things that won't get used can be removed. (after reading comments I think removing JSF is not good idea though)

答: Regarding JavaEE, you don't need any jar file, but only a compliant application server, Glassfish in your case. And no, you can't remove features you don't need. But you don't have to use them if you don't want to... ;-)</p>


问:
Why R+G+B is not equal white color?
I am trying to implement colors calibration feature. It captures using camera a TV screen playing calibration footage (white, then red, then green the blue).
I find points with max intensity of each color, so I got:

White (209, 209, 208)

Red   (130,2,1)

Green (0,190,2)

Blue  (0,1,95)

I disabled all automatic features in camera. I think, I should get something like these values:

Red   (209,2,1)

Green (0,209,2)

Blue  (0,1,208)

I know that camera has non linear characteristics of spectrum sensitivity, but I set gain of each channel manually to get a pure white and it should  also affect to separate RGB channels.
Any ideas why it happen and how to compensate it?

答:
If you think about it it makes total sense.

Let me try to explain:

Your display has three kinds of elements. red, green and blue ones.

Let R,G and B be the "amount of light" emitted by each of those elements.

When you display a white image the amount of light emitted is W = R + G + B

So a red, green or blue image can never be as bright as a white image.

The differences between R, G and B are caused by the difference in emitter brightness and camera sensitivity.

Also your display will most likely change color gains when displaying white so don't expect the sum of R G and B to equal W

Title: Why R+G+B is not equal white color?


问:
Angular 4 return value in undefined
This is my current code. How can I return rowData value in this case?

```<code>private createRowData() {
const rowData: any[] = [];

this.http
  .get(`/assets/json/payment.json`)
  .toPromise()
  .then(response => response.json())
  .then(data => {
    data.items.map(elem => {
      rowData.push({
        id: elem.id,
        total_amount: elem.total_amount,
        status: elem.status,
        sent: elem.sent,
      });
    });
  });
return rowData;}
</code>```

I had tried to console rowData before return and it gave me undefine.

答:
Your method should return a promise of the transformed data. In the last then callback, you should return the transformed response. You can rely on the implicit return of arrow function  to do that. You don't need the variable rowData because array.proptype.map returns a new array which each value in it is transformed. All you have to do is:

private createRowData() {
   return this.http    // Return the promise
    .get(`/assets/json/payment.json`)
    .toPromise()
    .then(response => response.json())
    .then(data => data.items.map(elem => ({   // Return the transformed data by the then callback
        id: elem.id,
        total_amount: elem.total_amount,
        status: elem.status,
        sent: elem.sent,
     })));
}
```

<p>Then you can use this methode like below:</p>

```this.createRowData().then(rowData => console.log(rowData))
```

Title: Angular 4 return value in undefined

Body:
This is my current code. How can I return rowData value in this case?

private createRowData() {
const rowData: any[] = [];

this.http
  .get(`/assets/json/payment.json`)
  .toPromise()
  .then(response => response.json())
  .then(data => {
    data.items.map(elem => {
      rowData.push({
        id: elem.id,
        total_amount: elem.total_amount,
        status: elem.status,
        sent: elem.sent,
      });
    });
  });
return rowData;}

I had tried to console rowData before return and it gave me undefine.

Body:
Your method should return a promise of the transformed data. In the last then callback, you should return the transformed response. You can rely on the implicit return of arrow function  to do that. You don't need the variable rowData because array.proptype.map returns a new array which each value in it is transformed. All you have to do is:

private createRowData() {
   return this.http    // Return the promise
    .get(`/assets/json/payment.json`)
    .toPromise()
    .then(response => response.json())
    .then(data => data.items.map(elem => ({   // Return the transformed data by the then callback
        id: elem.id,
        total_amount: elem.total_amount,
        status: elem.status,
        sent: elem.sent,
     })));
}

Then you can use this methode like below:

this.createRowData().then(rowData => console.log(rowData))


问:
Flow Testing for Cash Contract
I am trying to create a simple flow test which involves the CashV1 contract which I have adapted from the original cash contract in the corda example. The test is to simply reject the flow when one of the constraints in the cash contract are broken. for example when there are zero value transactions.

I keep getting this error:

java.lang.AssertionError: Expected an exception of class
  net.corda.core.contracts.TransactionVerificationException to be
  thrown, but was
  net.corda.core.transactions.MissingContractAttachments: Cannot find
  contract attachments for [com.example.contract.CashV1]

How is it possible to edit the flow or the test to include the attachments?

答:
In V1, you have to tell the mock nodes which additional packages to scan to find the contracts you are referencing (in the future, this will be handled automatically).

See https://github.com/corda/cordapp-example/blob/release-V1/kotlin-source/src/test/kotlin/com/example/flow/IOUFlowTests.kt for an example:

```<code>@Before
fun setup() {
    // Tells the mock nodes to scan the `com.example.contract` package when looking for contract attachments.
    setCordappPackages("com.example.contract")
    ...
}

...

@After
fun tearDown() {
    unsetCordappPackages()
    ...
}
</code>```

Title: Flow Testing for Cash Contract

Body:
In V1, you have to tell the mock nodes which additional packages to scan to find the contracts you are referencing (in the future, this will be handled automatically).

See https://github.com/corda/cordapp-example/blob/release-V1/kotlin-source/src/test/kotlin/com/example/flow/IOUFlowTests.kt for an example:

@Before
fun setup() {
    // Tells the mock nodes to scan the `com.example.contract` package when looking for contract attachments.
    setCordappPackages("com.example.contract")
    ...
}

...

@After
fun tearDown() {
    unsetCordappPackages()
    ...
}


问:
Override the value of an attribute in a derived Ecore-class (EMF)
I'm aware of the fact that I cannot override or redefine attributes as a whole in an ecore-based model when it comes to inheritance. But can I somehow assign a new value to an existing, inherited attribute?

E.g. Class A defines the attribute name which is a string, the default value is set to 'defaultA'. Class B inherits from Class A and name should have the value 'defaultB'.

I tried to just reimplement the attribute with the same name and datatype in Class B, but I cannot create a genmodel from that ("There may not be two features named 'name'").

Isn't it even possible to change the value of an inherited attribute?

答:
This rather hackish alternative is to declare an operation in the subclass with the same name as the feature getter name.

This is a light-weight variation of Viliam Simko's solution.

With this solution you will not have a proper name feature in Class B, but when then name feature in Class A is accessed your getter in Class B will be called instead.

I don't even know if this is really allowed. But it seems to be working with EMF 2.13.0, Xcore 1.5.0.

Example:

class ClassA {
    String name
}

class ClassB extends ClassA {
    op String getName() {
        return "Name B"
    }
}
```


问:
Setting custom UITableViewCells height
I am using a custom UITableViewCell which has some labels, buttons and image views to be displayed. There is one label in the cell whose text is a NSString object and the length of string could be variable. Due to this, I cannot set a constant height to the cell in the UITableView's heightForCellAtIndex method. The cell's height depends on the label's height which can be determined using the NSString's sizeWithFont method. I tried using it, but it looks like I'm going wrong somewhere. How can it be fixed?

Here is the code used for initializing the cell.

```<code>if (self = [super initWithFrame:frame reuseIdentifier:reuseIdentifier])
{
    self.selectionStyle = UITableViewCellSelectionStyleNone;
    UIImage *image = [UIImage imageNamed:@"dot.png"];
    imageView = [[UIImageView alloc] initWithImage:image];
    imageView.frame = CGRectMake(45.0,10.0,10,10);

    headingTxt = [[UILabel alloc] initWithFrame:   CGRectMake(60.0,0.0,150.0,post_hdg_ht)];
    [headingTxt setContentMode: UIViewContentModeCenter];
    headingTxt.text = postData.user_f_name;
    headingTxt.font = [UIFont boldSystemFontOfSize:13];
    headingTxt.textAlignment = UITextAlignmentLeft;
    headingTxt.textColor = [UIColor blackColor];

    dateTxt = [[UILabel alloc] initWithFrame:CGRectMake(55.0,23.0,150.0,post_date_ht)];
    dateTxt.text = postData.created_dtm;
    dateTxt.font = [UIFont italicSystemFontOfSize:11];
    dateTxt.textAlignment = UITextAlignmentLeft;
    dateTxt.textColor = [UIColor grayColor];

    NSString * text1 = postData.post_body;
    NSLog(@"text length = %d",[text1 length]);
    CGRect bounds = [UIScreen mainScreen].bounds;
    CGFloat tableViewWidth;
    CGFloat width = 0;
    tableViewWidth = bounds.size.width/2;
    width = tableViewWidth - 40; //fudge factor
    //CGSize textSize = {width, 20000.0f}; //width and height of text area
    CGSize textSize = {245.0, 20000.0f}; //width and height of text area
    CGSize size1 = [text1 sizeWithFont:[UIFont systemFontOfSize:11.0f]
                        constrainedToSize:textSize lineBreakMode:UILineBreakModeWordWrap];

    CGFloat ht = MAX(size1.height, 28);
    textView = [[UILabel alloc] initWithFrame:CGRectMake(55.0,42.0,245.0,ht)];
    textView.text = postData.post_body;
    textView.font = [UIFont systemFontOfSize:11];
    textView.textAlignment = UITextAlignmentLeft;
    textView.textColor = [UIColor blackColor];
    textView.lineBreakMode = UILineBreakModeWordWrap;
    textView.numberOfLines = 3;
    textView.autoresizesSubviews = YES;

    [self.contentView addSubview:imageView];
    [self.contentView addSubview:textView];
    [self.contentView addSubview:webView];
    [self.contentView addSubview:dateTxt];
    [self.contentView addSubview:headingTxt];
    [self.contentView sizeToFit];

    [imageView release];
    [textView release];
    [webView release];
    [dateTxt release];
    [headingTxt release];
}
</code>```

This is the label whose height and width are going wrong:

```<code>textView = [[UILabel alloc] initWithFrame:CGRectMake(55.0,42.0,245.0,ht)];
</code>```

答:
If all your rows are the same height, just set the rowHeight property of the UITableView rather than implementing the heightForRowAtIndexPath. Apple Docs:

There are performance implications to using tableView:heightForRowAtIndexPath: instead of rowHeight. Every time a table view is displayed, it calls tableView:heightForRowAtIndexPath: on the delegate for each of its rows, which can result in a significant performance problem with table views having a large number of rows (approximately 1000 or more).

OwnerDisplayName: Vijayeta

Title: Setting custom UITableViewCells height

Body:
I am using a custom UITableViewCell which has some labels, buttons and image views to be displayed. There is one label in the cell whose text is a NSString object and the length of string could be variable. Due to this, I cannot set a constant height to the cell in the UITableView's heightForCellAtIndex method. The cell's height depends on the label's height which can be determined using the NSString's sizeWithFont method. I tried using it, but it looks like I'm going wrong somewhere. How can it be fixed?

Here is the code used for initializing the cell.

if (self = [super initWithFrame:frame reuseIdentifier:reuseIdentifier])
{
    self.selectionStyle = UITableViewCellSelectionStyleNone;
    UIImage *image = [UIImage imageNamed:@"dot.png"];
    imageView = [[UIImageView alloc] initWithImage:image];
    imageView.frame = CGRectMake(45.0,10.0,10,10);

    headingTxt = [[UILabel alloc] initWithFrame:   CGRectMake(60.0,0.0,150.0,post_hdg_ht)];
    [headingTxt setContentMode: UIViewContentModeCenter];
    headingTxt.text = postData.user_f_name;
    headingTxt.font = [UIFont boldSystemFontOfSize:13];
    headingTxt.textAlignment = UITextAlignmentLeft;
    headingTxt.textColor = [UIColor blackColor];

    dateTxt = [[UILabel alloc] initWithFrame:CGRectMake(55.0,23.0,150.0,post_date_ht)];
    dateTxt.text = postData.created_dtm;
    dateTxt.font = [UIFont italicSystemFontOfSize:11];
    dateTxt.textAlignment = UITextAlignmentLeft;
    dateTxt.textColor = [UIColor grayColor];

    NSString * text1 = postData.post_body;
    NSLog(@"text length = %d",[text1 length]);
    CGRect bounds = [UIScreen mainScreen].bounds;
    CGFloat tableViewWidth;
    CGFloat width = 0;
    tableViewWidth = bounds.size.width/2;
    width = tableViewWidth - 40; //fudge factor
    //CGSize textSize = {width, 20000.0f}; //width and height of text area
    CGSize textSize = {245.0, 20000.0f}; //width and height of text area
    CGSize size1 = [text1 sizeWithFont:[UIFont systemFontOfSize:11.0f]
                        constrainedToSize:textSize lineBreakMode:UILineBreakModeWordWrap];

    CGFloat ht = MAX(size1.height, 28);
    textView = [[UILabel alloc] initWithFrame:CGRectMake(55.0,42.0,245.0,ht)];
    textView.text = postData.post_body;
    textView.font = [UIFont systemFontOfSize:11];
    textView.textAlignment = UITextAlignmentLeft;
    textView.textColor = [UIColor blackColor];
    textView.lineBreakMode = UILineBreakModeWordWrap;
    textView.numberOfLines = 3;
    textView.autoresizesSubviews = YES;

    [self.contentView addSubview:imageView];
    [self.contentView addSubview:textView];
    [self.contentView addSubview:webView];
    [self.contentView addSubview:dateTxt];
    [self.contentView addSubview:headingTxt];
    [self.contentView sizeToFit];

    [imageView release];
    [textView release];
    [webView release];
    [dateTxt release];
    [headingTxt release];
}

This is the label whose height and width are going wrong:

textView = [[UILabel alloc] initWithFrame:CGRectMake(55.0,42.0,245.0,ht)];

LastEditorDisplayName: Ryan Townshend


问:
PHP ratchet trouble with SSL
I can't seem to connect ratchet now that my website uses https. I even have stunnel installed. Here is my configuration

Demo: https://usyd.chat/react.html (see source code and console)

push-server.php

```<code><?php
require dirname(__DIR__) . '/vendor/autoload.php';

$loop   = React\EventLoop\Factory::create();
$pusher = new Unichat\Pusher;

// Listen for the web server to make a ZeroMQ push after an ajax request
$context = new React\ZMQ\Context($loop);
$pull = $context->getSocket(ZMQ::SOCKET_PULL);
$pull->bind('tcp://103.4.16.217:5555'); // Binding to 127.0.0.1 means the only client that can connect is itself
$pull->on('message', array($pusher, 'onInterfere'));

// Set up our WebSocket server for clients wanting real-time updates
$webSock = new React\Socket\Server($loop);
$webSock->listen(8080, '0.0.0.0'); // Binding to 0.0.0.0 means remotes can connect
$webServer = new Ratchet\Server\IoServer(
    new Ratchet\Http\HttpServer(
        new Ratchet\WebSocket\WsServer(
            new Ratchet\Wamp\WampServer(
                $pusher
            )
        )
    ),
    $webSock
);

$loop->run();
</code>```

Here is how I'm connecting to my web socket

```<code>var conn = new ab.Session('wss://usyd.chat:8080')
</code>```

Finally, my stunnel config

```<code>output = /etc/stunnel/stunnel.log

[websockets]
#cert = /etc/ssl/crt/primary.crt
cert = /etc/stunnel/stunnel.pem
accept = 8443
connect = 8080
</code>```

Nothing happens when I go on the react.html page on the console. In my pusher class, i have

```<code>echo "connected"
</code>```

in the onOpen method too but it doesn't log anything in the console.

Any help would be most appreciated.
Thanks

答:
Take a look at this answer to a similar question: https://stackoverflow.com/a/47200806/3777134

Now you don't need stunnel or a proxy, you can directly handle the secure connexion from the Ratchet server using the React\Socket\SecureServer class.

Title: PHP ratchet trouble with SSL

Body:
I can't seem to connect ratchet now that my website uses https. I even have stunnel installed. Here is my configuration

Demo: https://usyd.chat/react.html (see source code and console)

push-server.php

<?php
require dirname(__DIR__) . '/vendor/autoload.php';

$loop   = React\EventLoop\Factory::create();
$pusher = new Unichat\Pusher;

// Listen for the web server to make a ZeroMQ push after an ajax request
$context = new React\ZMQ\Context($loop);
$pull = $context->getSocket(ZMQ::SOCKET_PULL);
$pull->bind('tcp://103.4.16.217:5555'); // Binding to 127.0.0.1 means the only client that can connect is itself
$pull->on('message', array($pusher, 'onInterfere'));

// Set up our WebSocket server for clients wanting real-time updates
$webSock = new React\Socket\Server($loop);
$webSock->listen(8080, '0.0.0.0'); // Binding to 0.0.0.0 means remotes can connect
$webServer = new Ratchet\Server\IoServer(
    new Ratchet\Http\HttpServer(
        new Ratchet\WebSocket\WsServer(
            new Ratchet\Wamp\WampServer(
                $pusher
            )
        )
    ),
    $webSock
);

$loop->run();

Here is how I'm connecting to my web socket

var conn = new ab.Session('wss://usyd.chat:8080')

Finally, my stunnel config

output = /etc/stunnel/stunnel.log

[websockets]
#cert = /etc/ssl/crt/primary.crt
cert = /etc/stunnel/stunnel.pem
accept = 8443
connect = 8080

Nothing happens when I go on the react.html page on the console. In my pusher class, i have

echo "connected"

in the onOpen method too but it doesn't log anything in the console.

Any help would be most appreciated.
Thanks


问:
Does overflow:hidden applied to  work on iPhone Safari?
Does overflow:hidden applied to  work on iPhone Safari? It seems not.
I can't create a wrapper on the whole website to achieve that...

Do you know the solution?

Example: I have a long page, and simply I want to hide the content that goes underneath the "fold", and it should work on iPhone/iPad.

答:
Its working in Safari browser.</p>

```<code>html,
body {
  overflow: hidden;
  position: fixed
}
</code>```

Title: Does overflow:hidden applied to <body> work on iPhone Safari?

Body:
Its working in Safari browser.

html,
body {
  overflow: hidden;
  position: fixed
}


问:
Dropping multiple columns from Spark dataframe by Iterating through the columns from a Scala List of Column names
I have a dataframe which has columns around 400, I want to drop 100 columns as per my requirement.
So i have created a Scala List of 100 column names.
And then i want to iterate through a for loop to actually drop the column in each for loop iteration.

Below is the code.

```<code>final val dropList: List[String] = List("Col1","Col2",...."Col100”)

def drpColsfunc(inputDF: DataFrame): DataFrame = {
    for (i <- 0 to dropList.length - 1) {
        val returnDF = inputDF.drop(dropList(i))
    }
    return returnDF
}

val test_df = drpColsfunc(input_dataframe)

test_df.show(5)
</code>```

答:
If you just want to do nothing more complex than dropping several named columns, as opposed to selecting them by a particular condition, you can simply do the following: </p>

```<code>df.drop("colA", "colB", "colC")
</code>```

Body:
I have a dataframe which has columns around 400, I want to drop 100 columns as per my requirement.
So i have created a Scala List of 100 column names.
And then i want to iterate through a for loop to actually drop the column in each for loop iteration.

Below is the code.

final val dropList: List[String] = List("Col1","Col2",...."Col100”)

def drpColsfunc(inputDF: DataFrame): DataFrame = {
    for (i <- 0 to dropList.length - 1) {
        val returnDF = inputDF.drop(dropList(i))
    }
    return returnDF
}

val test_df = drpColsfunc(input_dataframe)

test_df.show(5)

Body:
If you just want to do nothing more complex than dropping several named columns, as opposed to selecting them by a particular condition, you can simply do the following:

df.drop("colA", "colB", "colC")


问:
Getting the value of the button from the 1st page and echoing it to the Modal and to the 2nd page
I know some of you this problem is pretty simple to do, but I am working in a week to find it out what are the right codes to function it well.

in the 1stpage.php there is a multiple buttons with different values in it

```<code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a href="#myModal" data-toggle="modal" value="#01" name="btn" class="button2 btn btn-primary model_open" data-btnval = "#01" aria-hidden="true" data-dismiss="modal" >form</a>

<a href="#myModal" data-toggle="modal" value="#02" name="btn" class="button2 btn btn-success model_open" data-btnval = "#02" aria-hidden="true" data-dismiss="modal" >form</a>

<a href="#myModal" data-toggle="modal" value="#03" name="btn" class="button2 btn btn-warning model_open" data-btnval = "#03" aria-hidden="true" data-dismiss="modal" >form</a>
</code>```

that can open the Modal Form inside the page

```<code>  $(document).on("click", ".model_open", function () {
    var btnval = $(this).data('btnval');
   $(".modal-body #btnval").text( btnval );
$('#hiddenid').val(btnval );
});e here
</code>```

on the Modal Form you'll see the current value button echoed on the form, because of the script and this code

```<code><div aria-hidden="true" aria-labelledby="myModalLabel" role="dialog"
tabindex="-1" id="myModal" class="modal fade">
  <div class="modal-dialog">
    <div class="modal-content">
      <div class="modal-header1" style="padding:10px 15px;">
         <button type="button" class="close" data-dismiss="modal" >×
         </button>
    <h4><span class="glyphicon glyphicon-pencil"></span> FORM</h4>
</div>
<div class="modal-body" style="padding:10px 10px;">

<h6 class="sub-heading-2 tiny text-medium text-center-xs">

<?php
    $divName="btnval";
    echo "<div id=$divName></div>"; <!-- echoing the button value -->
?>
 <div class="modal-body">

<form action="2ndpage.php" method="get" enctype="multipart/form-data">

<div class="col-sm-6">
  <div class="form-group">
    <label for="lname">Name</label>
      <input type="text" class="form-control" name="lname" id="lname"
      required="required" placeholder="Name">
  </div>
</div>

<input type="submit" id="btn-next" class="btn btn-success pull-right"
 value="NEXT">
</form>
</code>```

on the Modal form there is NEXT button which will you proceed to the 2ndpage.php to see and double check the information you provided on the form, together with the Value Button you've clicked from the first page.

```<code> <div class="label-field-pair">
<label>Name</label>
<input class="form-control" id='name' name='name' value='<?php echo
$_GET["name"]; ?>'  />
</div>

<div class="label-field-pair">
<label>ID</label>
<input class="form-control" id='id' name='id' value='<?php echo
$_GET["btnval"]; ?>'  />
</div>
</code>```

It seems pretty simple but I can't find a good way to do it. I was tried a much code with the codes from the others to get the name value of the current button to be echo on the 2ndpage.php, but I always got an error.

SOLVED:
1stpage.php

```<code> <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
</code>```

Buttons start

```<code><a href="#myModal" data-toggle="modal" value="#01" name="btn" class="button2 btn btn-primary model_open" data-btnval = "#01" aria-hidden="true" data-dismiss="modal" >form</a>
<a href="#myModal" data-toggle="modal" value="#02" name="btn" class="button2 btn btn-success model_open" data-btnval = "#02" aria-hidden="true" data-dismiss="modal" >form</a>
<a href="#myModal" data-toggle="modal" value="#03" name="btn" class="button2 btn btn-warning model_open" data-btnval = "#03" aria-hidden="true" data-dismiss="modal" >form</a>
</code>```

Getting the current button id by using this script

```<code>$(document).on("click", ".model_open", function () {
            var btnval = $(this).data('btnval');
           $(".modal-body #btnval").text( btnval );
        $('#hiddenid').val(btnval);
        });
</code>```

Modal Form

```<code><div class="modal-body">
<form action="2ndpage.php" method="get" enctype="multipart/form-data">
<h6>
    <?php
            $divName = "btnval";
                echo '<div id="'.$divName.'"></div>';
    ?>
</h6>
<input type="hidden" name="id" value="<?php echo $divName; ?>">
<input type="hidden" id="hiddenid" name="btnval">
<div class="form-group">
    <input type="text" class="form-control" name="name" id="name"
    required="required" placeholder="Name">
</div>
<input type="submit" class="btn btn-success" value="NEXT"></form></div>
</code>```

2ndpage.php

```<code><label>ID</label>
  <input class="form-control" id='id' name='id' value='<?php echo
     $_GET["btnval"]; ?>'/>
</div>
 <div class="label-field-pair">
<label>NAME</label>
  <input class="form-control" id='name' name='name' value='<?php echo
     $_GET["name"]; ?>' />
</div>
</code>```

答:
How about you send a hidden value??

Trigger:

```<code>  <a data-toggle="modal" data-id="#03" title="Add this item" class="button2 btn btn-warning model_open" href="#myModal">test</a>
</code>```

Modal:

```<code><form action="2ndpage.php" method="get" enctype="multipart/form-data">

 <div class="col-sm-6">
  <div class="form-group">
   <label for="lname">Name</label>
    <input type="text" class="form-control" name="lname" id="lname"
    required="required" placeholder="Name">
  </div>
  <input type="hidden" name="whatyouwant" id="whatyouwant" value=""/>
 </div>

 <input type="submit" id="btn-next" class="btn btn-success pull-right" value="NEXT">
</form>
</code>```

jquery:

```<code> $(document).on("click", ".model_open", function () {
    var btnval = $(this).data('id');
    $(".modal-body #whatyouwant").val(btnval);
 });
</code>```

On 2ndpage.php:

Echo Value

```<code><?php
  echo "```";
  print_r($_REQUEST);
  echo "```";
?>
</code>```

Output.

```<code>Array
(
   [lname] => sdsa
   [whatyouwant] => #03
)
</code>```

Body:
I know some of you this problem is pretty simple to do, but I am working in a week to find it out what are the right codes to function it well.

in the 1stpage.php there is a multiple buttons with different values in it

form

form

form

that can open the Modal Form inside the page

  $(document).on("click", ".model_open", function () {
    var btnval = $(this).data('btnval');
   $(".modal-body #btnval").text( btnval );
$('#hiddenid').val(btnval );
});e here

on the Modal Form you'll see the current value button echoed on the form, because of the script and this code

         <button type="button" class="close" data-dismiss="modal" >×
         </button>

 FORM

<?php
    $divName="btnval";
    echo "

";
?>

<form action="2ndpage.php" method="get" enctype="multipart/form-data">

    Name
      <input type="text" class="form-control" name="lname" id="lname"
      required="required" placeholder="Name">

<input type="submit" id="btn-next" class="btn btn-success pull-right"
 value="NEXT">
</form>

on the Modal form there is NEXT button which will you proceed to the 2ndpage.php to see and double check the information you provided on the form, together with the Value Button you've clicked from the first page.

Name
<input class="form-control" id='name' name='name' value='<?php echo
$_GET["name"]; ?>'  />

ID
<input class="form-control" id='id' name='id' value='<?php echo
$_GET["btnval"]; ?>'  />

It seems pretty simple but I can't find a good way to do it. I was tried a much code with the codes from the others to get the name value of the current button to be echo on the 2ndpage.php, but I always got an error.

SOLVED:
1stpage.php

Buttons start

form
form
form

Getting the current button id by using this script

$(document).on("click", ".model_open", function () {
            var btnval = $(this).data('btnval');
           $(".modal-body #btnval").text( btnval );
        $('#hiddenid').val(btnval);
        });

Modal Form

<form action="2ndpage.php" method="get" enctype="multipart/form-data">

    <?php
            $divName = "btnval";
                echo '

';
    ?>

<input type="hidden" name="id" value="<?php echo $divName; ?>">
<input type="hidden" id="hiddenid" name="btnval">

    <input type="text" class="form-control" name="name" id="name"
    required="required" placeholder="Name">

<input type="submit" class="btn btn-success" value="NEXT"></form>

2ndpage.php

ID
  <input class="form-control" id='id' name='id' value='<?php echo
     $_GET["btnval"]; ?>'/>

NAME
  <input class="form-control" id='name' name='name' value='<?php echo
     $_GET["name"]; ?>' />

Body:
How about you send a hidden value??

Trigger:

  <a data-toggle="modal" data-id="#03" title="Add this item" class="button2 btn btn-warning model_open" href="#myModal">test</a>

Modal:

<form action="2ndpage.php" method="get" enctype="multipart/form-data">

 <div class="col-sm-6">
  <div class="form-group">
   <label for="lname">Name</label>
    <input type="text" class="form-control" name="lname" id="lname"
    required="required" placeholder="Name">
  </div>
  <input type="hidden" name="whatyouwant" id="whatyouwant" value=""/>
 </div>

 <input type="submit" id="btn-next" class="btn btn-success pull-right" value="NEXT">
</form>

jquery:

 $(document).on("click", ".model_open", function () {
    var btnval = $(this).data('id');
    $(".modal-body #whatyouwant").val(btnval);
 });

On 2ndpage.php:

Echo Value

<?php
  echo "<pre>";
  print_r($_REQUEST);
  echo "</pre>";
?>

Output.

Array
(
   [lname] => sdsa
   [whatyouwant] => #03
)


问:
Bootstrap 4 beta how to add image after text
I have an issue with adding an image in "menu" section at the last item "Kava so sebou" after the text. (the picture should be center vertically and the row should look like the other items above. Any suggestions? Thank you for your help. I just learn bootstrap and I'm a girl. (hilarious combination)

Custom css

.menu {
  padding: 70px 0px;
}
.menu .block > p {
  color: #9D9D9D;
  font-size: 16px;
  line-height: 26px;
  padding: 40px 133px 0;
  text-align: center;
}
.menu .block .pricing-list {
  padding-top: 5px;
}
.menu .block .pricing-list ul {
  list-style-type: none;
  padding: 0 0 30px;
  margin: 0;
}
.menu .block .pricing-list ul li {
  padding: 21px 0px;
}
.menu .block .pricing-list ul li .item .item-title {
  position: relative;
}
.menu .block .pricing-list ul li .item .item-title h2 {
  display: inline-block;
  position: relative;
  z-index: 99;
  background: #fff;
}
.menu .block .pricing-list ul li .item .item-title .border-bottom {
  position: absolute;
  top: 0;
  width: 100%;
  height: 1px;
  border: 1px dotted #C9C9C9;
  margin-top: 40px;
}
.menu .block .pricing-list ul li .item .item-title .border-bottom-coffee {
  position: absolute;
  top: 50px;
  width: 100%;
  height: 1px;
  border: 1px dotted #C9C9C9;
  margin-top: 30px;
}
.menu .block .pricing-list ul li .item .item-title span {
  float: right;
  color: #938463;
}
.menu .block .pricing-list ul li .item .item-title span {
  float: right;
  color: #938463;
}
.menu .block .pricing-list ul li .item .item-title img {
 padding-bottom: 20px;
}
.menu .block .pricing-list ul li .item p {
  padding: 12px 0 0px;
  color: #949494;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code> <!-- Start Menu list -->
    <section id="menu" class="menu">
     <div class="container">
            <div class="row">
                <div class="col-md-12">
                    <div class="block">
                        <div class="pricing-list">
                            <div class="title">
                             <div class="container">
                             <ul>
                                <li class="wow fadeInUp" data-wow-duration="300ms" data-wow-delay="1100ms" style="visibility: visible; animation-duration: 300ms; animation-delay: 1100ms; animation-name: fadeInUp;">
                                    <div class="item">
                                        <div class="item-title">
                                            <h2>Pivo 10 0.5L</h2>
                                            <div class="border-bottom"></div>
                                            <span>€ 1.20</span>
                                        </div>
                                        <p>Zlatý Bažant, Staropramen</p>
                                    </div>
                                </li>
                                <li class="wow fadeInUp" data-wow-duration="300ms" data-wow-delay="1200ms" style="visibility: visible; animation-duration: 300ms; animation-delay: 1200ms; animation-name: fadeInUp;">
                                    <div class="item">
                                        <div class="item-title">
                                            <h2>Káva so sebou </h2>
                                            <div class="border-bottom"></div>
                                            <span>€ 1.20</span>
                                        </div>
                                        <p>Štrbské Presso</p>
                                    </div>
                                </li>
                            </ul>
                        </div>
                    </div><!-- block close -->
                </div><!-- .col-md-12 close -->
            </div><!-- .row close -->
        </div><!-- .containe close -->
    </section><!-- #price close --></code>```

答:
Thanks for your advice.
This worked for me</p>

```<code><li class="wow fadeInUp" data-wow-duration="300ms" data-wow-delay="1200ms" style="visibility: visible; animation-duration: 300ms; animation-delay: 1200ms; animation-name: fadeInUp;">
  <div class="item">
    <div class="item-title media">
      <h2>
        Káva so sebou
        <p>Štrbské Presso</p>
      </h2>
      <div class="border-bottom"></div>
        <div class="media-object">
          <img class="d-block img-fluid" src="./images/coffee.jpg">
        </div>
        <div class="media-body">
        <span>€ 1.20</span>
      </div>
      </div>
    </div>
</li>
</code>```

Body:
I have an issue with adding an image in "menu" section at the last item "Kava so sebou" after the text. (the picture should be center vertically and the row should look like the other items above. Any suggestions? Thank you for your help. I just learn bootstrap and I'm a girl. (hilarious combination)

Custom css

.menu {
  padding: 70px 0px;
}
.menu .block > p {
  color: #9D9D9D;
  font-size: 16px;
  line-height: 26px;
  padding: 40px 133px 0;
  text-align: center;
}
.menu .block .pricing-list {
  padding-top: 5px;
}
.menu .block .pricing-list ul {
  list-style-type: none;
  padding: 0 0 30px;
  margin: 0;
}
.menu .block .pricing-list ul li {
  padding: 21px 0px;
}
.menu .block .pricing-list ul li .item .item-title {
  position: relative;
}
.menu .block .pricing-list ul li .item .item-title h2 {
  display: inline-block;
  position: relative;
  z-index: 99;
  background: #fff;
}
.menu .block .pricing-list ul li .item .item-title .border-bottom {
  position: absolute;
  top: 0;
  width: 100%;
  height: 1px;
  border: 1px dotted #C9C9C9;
  margin-top: 40px;
}
.menu .block .pricing-list ul li .item .item-title .border-bottom-coffee {
  position: absolute;
  top: 50px;
  width: 100%;
  height: 1px;
  border: 1px dotted #C9C9C9;
  margin-top: 30px;
}
.menu .block .pricing-list ul li .item .item-title span {
  float: right;
  color: #938463;
}
.menu .block .pricing-list ul li .item .item-title span {
  float: right;
  color: #938463;
}
.menu .block .pricing-list ul li .item .item-title img {
 padding-bottom: 20px;
}
.menu .block .pricing-list ul li .item p {
  padding: 12px 0 0px;
  color: #949494;
}

Pivo 10 0.5L

                                            € 1.20

Zlatý Bažant, Staropramen

Káva so sebou

                                            € 1.20

Štrbské Presso

Body:
Thanks for your advice.
This worked for me

<li class="wow fadeInUp" data-wow-duration="300ms" data-wow-delay="1200ms" style="visibility: visible; animation-duration: 300ms; animation-delay: 1200ms; animation-name: fadeInUp;">
  <div class="item">
    <div class="item-title media">
      <h2>
        Káva so sebou
        <p>Štrbské Presso</p>
      </h2>
      <div class="border-bottom"></div>
        <div class="media-object">
          <img class="d-block img-fluid" src="./images/coffee.jpg">
        </div>
        <div class="media-body">
        <span>€ 1.20</span>
      </div>
      </div>
    </div>
</li>


问:
Date is getting converted to number, while making html of datafrane
While converting the data frame to HTML, Date is getting converted to a number.

```<code>library("xtable")
print(xtable(Data), type="html", file="Data.html",timestamp=date())
</code>```

The first column of this data frame is in Date format, which is getting converted to a number.

答:
You could try tableHTML which handles dates. As a quick example:

```<code>library(tableHTML)
Data <- data.frame(a = 1:10, b = as.Date('2017-01-01'))
mytable <- tableHTML(Data, rownames = FALSE)
mytable
</code>```

And to write it in a file, you can use:

```<code>write_tableHTML(mytable, file = 'Data.html')
</code>```

Body:
While converting the data frame to HTML, Date is getting converted to a number.

library("xtable")
print(xtable(Data), type="html", file="Data.html",timestamp=date())

The first column of this data frame is in Date format, which is getting converted to a number.

Body:
You could try tableHTML which handles dates. As a quick example:

library(tableHTML)
Data <- data.frame(a = 1:10, b = as.Date('2017-01-01'))
mytable <- tableHTML(Data, rownames = FALSE)
mytable

And to write it in a file, you can use:

write_tableHTML(mytable, file = 'Data.html')


问:
How to implement offline reading in my app
I would like to implement offline reading for a news application I have been developing on the iphone. I currently use SDURLCache and I can see the content is loaded from the disk but how can I find if there is already something in the cache for the given url without starting a new url connection?

or if there is some other way to do that please let me know.

thx

答:
You might be able to do this:</p>

```<code>NSData* cacheForUrl(NSString *aUrl) {
  SDURLCache *cache = [[SDURLCache alloc] init];
  NSCachedURLResponse *response = [cache cachedResponseForRequest:[NSUrlRequest requestWithURL:aUrl];
  if(!response) {
    return @"URL not in cache";
  } //implicit else

  return [response data];
}
</code>```

Body:
You might be able to do this:

NSData* cacheForUrl(NSString *aUrl) {
  SDURLCache *cache = [[SDURLCache alloc] init];
  NSCachedURLResponse *response = [cache cachedResponseForRequest:[NSUrlRequest requestWithURL:aUrl];
  if(!response) {
    return @"URL not in cache";
  } //implicit else

  return [response data];
}