问:
How Whatsapp attachment's window can override keyboard?
I'm working on a similiar problem developing my chat and I was checking on how whatsapp solves it to get an idea to work on it.

On mobile and inside a conversation, when your keyboard is up on the screen and you click on attachments, the attachments window overrides the keboard like the image below. It also look likes the activity under it freezes ( you can look at the  slash "|" on the EditText, it seems that is freeze ).

I was wondering how WP could override the keyboard and why it looks like the activity under it is freezing, thanks in advance!

答:
      /Use the below code Snipet without using any library/

```<code>   action_attach.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            openDialog();
        }
    });

  private void openDialog() {
    LayoutInflater layoutInflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    // inflate the custom popup layout
    final View inflatedView;

    inflatedView = layoutInflater.inflate(R.layout.custom_dialog_options_menu, null, false);

    LinearLayout layoutGallery;
   layoutGallery = (LinearLayout) inflatedView.findViewById(R.id.layoutGallery);
    layoutGallery.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            FloatingView.dismissWindow();
        }
    });

    FloatingView.onShowPopup(this, inflatedView);
  }

 /**Sample Layout for Pop Up window ie: custom_dialog_options_menu
    and change layout according to your choice***/

 <?xml version="1.0" encoding="utf-8"?>
 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
   android:layout_width="match_parent"
   android:layout_height="wrap_content"
   android:orientation="vertical"
   android:paddingTop="82dp">

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="#FFF"
    android:orientation="horizontal">

    <LinearLayout
        android:id="@+id/layoutGallery"
        android:layout_width="0dp"
        android:layout_marginTop="18dp"
        android:layout_height="wrap_content"
        android:layout_marginLeft="40dp"
        android:layout_weight="1"
        android:orientation="vertical">

        <ImageView
            android:layout_width="60dp"
            android:layout_height="60dp"
            android:layout_gravity="center"
            android:src="@drawable/gallery_attach_icon_selector"/>

        <TextView
            android:id="@+id/tvGallery"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center_horizontal"
            android:text="Gallery"
            android:layout_marginTop="10dp"
            android:textSize="16sp"
            android:textColor="#4d4747"/>

    </LinearLayout>

    <LinearLayout
        android:id="@+id/layoutPhoto"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:layout_marginTop="18dp"
        android:orientation="vertical">

        <ImageView
            android:layout_width="60dp"
            android:layout_height="60dp"
            android:layout_gravity="center"
            android:src="@drawable/camera_attach_icon_selector"/>

        <TextView
            android:id="@+id/tvPhoto"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center_horizontal"
            android:text="Camera"
            android:layout_marginTop="10dp"
            android:textSize="16sp"
            android:textColor="#4d4747"/>

    </LinearLayout>

    <LinearLayout
        android:id="@+id/layoutVideo"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginRight="40dp"
        android:layout_weight="1"
        android:layout_marginTop="18dp"
        android:orientation="vertical">

        <ImageView
            android:layout_width="60dp"
            android:layout_height="60dp"
            android:layout_gravity="center"
            android:src="@drawable/video_attach_icon_selector"/>

        <TextView
            android:id="@+id/tvVideo"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center_horizontal"
            android:text="Video"
            android:layout_marginTop="10dp"
            android:textSize="16sp"
            android:textColor="#4d4747"/>

    </LinearLayout>

</LinearLayout>

</LinearLayout>

/**FloatingView Class**/

public class FloatingView
{
/* Floating view is used to display a custom view for attachments in the chat screen */

import android.app.Activity;
import android.graphics.Point;
import android.view.Display;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.PopupWindow;

private static PopupWindow popWindow;

private FloatingView() {
}

public static void onShowPopup(Activity activity, View inflatedView) {

    // get device size
    Display display = activity.getWindowManager().getDefaultDisplay();
    final Point size = new Point();
    display.getSize(size);
    // fill the data to the list items
    // set height depends on the device size
    popWindow = new PopupWindow(inflatedView, size.x, ViewGroup.LayoutParams.WRAP_CONTENT,
            true);
    // set a background drawable with rounders corners
    popWindow.setBackgroundDrawable(activity.getResources().getDrawable(
            R.drawable.comment_popup_bg));
    // make it focusable to show the keyboard to enter in `EditText`
    popWindow.setFocusable(true);
    // make it outside touchable to dismiss the popup window
    popWindow.setOutsideTouchable(true);

    popWindow.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN);
    // show the popup at bottom of the screen and set some margin at
    // bottom ie,

    popWindow.showAtLocation(activity.getCurrentFocus(), Gravity.BOTTOM, 0,
            0);
}

public static void dismissWindow() {

    popWindow.dismiss();
}
</code>```

Body:
      /Use the below code Snipet without using any library/

   action_attach.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            openDialog();
        }
    });

  private void openDialog() {
    LayoutInflater layoutInflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    // inflate the custom popup layout
    final View inflatedView;

    inflatedView = layoutInflater.inflate(R.layout.custom_dialog_options_menu, null, false);

    LinearLayout layoutGallery;
   layoutGallery = (LinearLayout) inflatedView.findViewById(R.id.layoutGallery);
    layoutGallery.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            FloatingView.dismissWindow();
        }
    });

    FloatingView.onShowPopup(this, inflatedView);
  }

 /**Sample Layout for Pop Up window ie: custom_dialog_options_menu
    and change layout according to your choice***/

 <?xml version="1.0" encoding="utf-8"?>
 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
   android:layout_width="match_parent"
   android:layout_height="wrap_content"
   android:orientation="vertical"
   android:paddingTop="82dp">

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="#FFF"
    android:orientation="horizontal">

    <LinearLayout
        android:id="@+id/layoutGallery"
        android:layout_width="0dp"
        android:layout_marginTop="18dp"
        android:layout_height="wrap_content"
        android:layout_marginLeft="40dp"
        android:layout_weight="1"
        android:orientation="vertical">

        <ImageView
            android:layout_width="60dp"
            android:layout_height="60dp"
            android:layout_gravity="center"
            android:src="@drawable/gallery_attach_icon_selector"/>

        <TextView
            android:id="@+id/tvGallery"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center_horizontal"
            android:text="Gallery"
            android:layout_marginTop="10dp"
            android:textSize="16sp"
            android:textColor="#4d4747"/>

    </LinearLayout>

    <LinearLayout
        android:id="@+id/layoutPhoto"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:layout_marginTop="18dp"
        android:orientation="vertical">

        <ImageView
            android:layout_width="60dp"
            android:layout_height="60dp"
            android:layout_gravity="center"
            android:src="@drawable/camera_attach_icon_selector"/>

        <TextView
            android:id="@+id/tvPhoto"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center_horizontal"
            android:text="Camera"
            android:layout_marginTop="10dp"
            android:textSize="16sp"
            android:textColor="#4d4747"/>

    </LinearLayout>

    <LinearLayout
        android:id="@+id/layoutVideo"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginRight="40dp"
        android:layout_weight="1"
        android:layout_marginTop="18dp"
        android:orientation="vertical">

        <ImageView
            android:layout_width="60dp"
            android:layout_height="60dp"
            android:layout_gravity="center"
            android:src="@drawable/video_attach_icon_selector"/>

        <TextView
            android:id="@+id/tvVideo"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center_horizontal"
            android:text="Video"
            android:layout_marginTop="10dp"
            android:textSize="16sp"
            android:textColor="#4d4747"/>

    </LinearLayout>

</LinearLayout>

</LinearLayout>

/**FloatingView Class**/

public class FloatingView
{
/* Floating view is used to display a custom view for attachments in the chat screen */

import android.app.Activity;
import android.graphics.Point;
import android.view.Display;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.PopupWindow;

private static PopupWindow popWindow;

private FloatingView() {
}

public static void onShowPopup(Activity activity, View inflatedView) {

    // get device size
    Display display = activity.getWindowManager().getDefaultDisplay();
    final Point size = new Point();
    display.getSize(size);
    // fill the data to the list items
    // set height depends on the device size
    popWindow = new PopupWindow(inflatedView, size.x, ViewGroup.LayoutParams.WRAP_CONTENT,
            true);
    // set a background drawable with rounders corners
    popWindow.setBackgroundDrawable(activity.getResources().getDrawable(
            R.drawable.comment_popup_bg));
    // make it focusable to show the keyboard to enter in `EditText`
    popWindow.setFocusable(true);
    // make it outside touchable to dismiss the popup window
    popWindow.setOutsideTouchable(true);

    popWindow.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN);
    // show the popup at bottom of the screen and set some margin at
    // bottom ie,

    popWindow.showAtLocation(activity.getCurrentFocus(), Gravity.BOTTOM, 0,
            0);
}

public static void dismissWindow() {

    popWindow.dismiss();
}


来源: stackexchange

问:
Excel vba runtime error 424 Object required when assigning Range variable
I have this code that consists of a function and subroutine that uses that function. Function takes a column as an argument and alters each of that column cell's content.

```<code>Function testFunc(aCol As Range)
    Dim i As Integer
    i = 0
    For Each cell In aCol
        cell.Value = i
        i = i + 1
    Next
End Function

Sub testSub()
    Dim aRange As Range
    Set aRange = ThisWorkbook.Sheets("Sheet1").Range("A1:A16")

    testFunc (ThisWorkbook.Sheets("Sheet2").Range("A1:A16"))   '<--- this works fine
    testFunc (aRange)    '<---- error
End Sub
</code>```

The Runtime error '424' Object required"| arises on linetestFunc (aRange)`. I'm not sure what's wrong, I assign variable through 'Set' and it's supposed to work fine.

Also, I tried passing the range directly to the function, without storing it in the variable first and it workes perfectly. Why?

答:
Your code woubl to be lik this.</p>

```<code>Sub testFunc(aCol As Range)
    Dim i As Integer
    i = 0
    For Each cell In aCol
        cell.Value = i
        i = i + 1
    Next
End Sub

Sub testSub()
    Dim aRange As Range
    Set aRange = ThisWorkbook.Sheets("Sheet1").Range("A1:A16")

    testFunc aRange    '<---- error
End Sub
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have this code that consists of a function and subroutine that uses that function. Function takes a column as an argument and alters each of that column cell's content.

Function testFunc(aCol As Range)
    Dim i As Integer
    i = 0
    For Each cell In aCol
        cell.Value = i
        i = i + 1
    Next
End Function

Sub testSub()
    Dim aRange As Range
    Set aRange = ThisWorkbook.Sheets("Sheet1").Range("A1:A16")

    testFunc (ThisWorkbook.Sheets("Sheet2").Range("A1:A16"))   '<--- this works fine
    testFunc (aRange)    '<---- error
End Sub

The Runtime error '424' Object required"| arises on linetestFunc (aRange)`. I'm not sure what's wrong, I assign variable through 'Set' and it's supposed to work fine.

Also, I tried passing the range directly to the function, without storing it in the variable first and it workes perfectly. Why?

Body:
Your code woubl to be lik this.

Sub testFunc(aCol As Range)
    Dim i As Integer
    i = 0
    For Each cell In aCol
        cell.Value = i
        i = i + 1
    Next
End Sub

Sub testSub()
    Dim aRange As Range
    Set aRange = ThisWorkbook.Sheets("Sheet1").Range("A1:A16")

    testFunc aRange    '<---- error
End Sub


问:
Python 2.7 GUI using Tkinter
I'm totally new to Python and GUI. I am trying to create a simple GUI using Tkinter which has two file browser options and a command button.

When I try to click on the first browse button and select the file, the file name is displayed in both text boxes. Similarly, when I click on the second button, the new file name is displayed in both text boxes. Please correct me where I'm going wrong. I tried much to fix but in vein. Also, Please pour in suggestions to improve my coding to reduce the LOC for such a simple GUI.

Issue Sceenshot

```<code>import os
import Tkinter
import tkFileDialog
from tkFileDialog import askopenfilename
from Tkinter import *

file_path_1 = ''
file_path_2 = ''

#~~~~ FUNCTIONS~~~~

def open_rules_file():
  global file_path_1
  filename1 = askopenfilename()
  file_path_1 = os.path.abspath(filename1)
  print file_path_1
  entry1.delete(0, END)
  entry1.insert(0, file_path_1)

def open_src_file():
  global file_path_2
  filename2 = askopenfilename()
  file_path_2 = os.path.abspath(filename2)
  print file_path_2
  entry2.delete(0, END)
  entry2.insert(0, file_path_2)

#~~~~~~ GUI ~~~~~~~~

root = Tk()
root.title('MY GUI')
root.geometry("1000x300+250+100")

mf = Frame(root)
mf.pack()
f1 = Frame(mf, width=600, height=250)
f1.pack(fill=X)
f2 = Frame(mf, width=600, height=250)
f2.pack()
f3 = Frame(mf, width=600, height=250)
f3.pack()

file_path_1 = StringVar
file_path_2 = StringVar

Label(f1,text="Select Rules Sheet (xls)").grid(row=1, column=0, sticky='e')
entry1 = Entry(f1, width=70, textvariable=file_path_1)
entry1.grid(row=1,column=1,padx=2,pady=2,sticky='we',columnspan=25)
Button(f1, text="Browse1", command=open_rules_file).grid(row=1, column=27, sticky='ew', padx=8, pady=4)

Label(f2,text="Select COBOL Source   ").grid(row=2, column=0, sticky='e')
entry2 = Entry(f2, width=70, textvariable=file_path_2)
entry2.grid(row=2,column=1,padx=2,pady=2,sticky='we',columnspan=25)
Button(f2, text="Browse2", command=open_src_file).grid(row=2, column=27, sticky='ew', padx=8, pady=4)

Button(f3, text='Quit', command=f3.quit).grid(row=3, column=0, sticky=W, pady=4)
root.mainloop()
</code>```

答:
Instead of creating object of StringVar class you have just assigned class to those variable</p>

```<code>import os
import Tkinter
import tkFileDialog
from tkFileDialog import askopenfilename
from Tkinter import *

file_path_1 = ''
file_path_2 = ''

#~~~~ FUNCTIONS~~~~

def open_rules_file():
  global file_path_1
  filename1 = askopenfilename()
  file_path_1 = os.path.abspath(filename1)
  print file_path_1
  entry1.delete(0, END)
  entry1.insert(0, file_path_1)

def open_src_file():
  global file_path_2
  filename2 = askopenfilename()
  file_path_2 = os.path.abspath(filename2)
  print file_path_2
  entry2.delete(0, END)
  entry2.insert(0, file_path_2)

#~~~~~~ GUI ~~~~~~~~

root = Tk()
root.title('MY GUI')
root.geometry("1000x300+250+100")

mf = Frame(root)
mf.pack()
f1 = Frame(mf, width=600, height=250)
f1.pack(fill=X)
f2 = Frame(mf, width=600, height=250)
f2.pack()
f3 = Frame(mf, width=600, height=250)
f3.pack()

##Instead of creating object of that class you have just assigned class to those variable
file_path_1 = StringVar()
file_path_2 = StringVar()

Label(f1,text="Select Rules Sheet (xls)").grid(row=1, column=0, sticky='e')
entry1 = Entry(f1, width=70, textvariable=file_path_1)
entry1.grid(row=1,column=1,padx=2,pady=2,sticky='we',columnspan=25)
Button(f1, text="Browse1", command=open_rules_file).grid(row=1, column=27, sticky='ew', padx=8, pady=4)

Label(f2,text="Select COBOL Source   ").grid(row=2, column=0, sticky='e')
entry2 = Entry(f2, width=70, textvariable=file_path_2)
entry2.grid(row=2,column=1,padx=2,pady=2,sticky='we',columnspan=25)
Button(f2, text="Browse2", command=open_src_file).grid(row=2, column=27, sticky='ew', padx=8, pady=4)

Button(f3, text='Quit', command=f3.quit).grid(row=3, column=0, sticky=W, pady=4)
root.mainloop()
</code>```

Title: Python 2.7 GUI using Tkinter

Body:
I'm totally new to Python and GUI. I am trying to create a simple GUI using Tkinter which has two file browser options and a command button.

When I try to click on the first browse button and select the file, the file name is displayed in both text boxes. Similarly, when I click on the second button, the new file name is displayed in both text boxes. Please correct me where I'm going wrong. I tried much to fix but in vein. Also, Please pour in suggestions to improve my coding to reduce the LOC for such a simple GUI.

Issue Sceenshot

import os
import Tkinter
import tkFileDialog
from tkFileDialog import askopenfilename
from Tkinter import *

file_path_1 = ''
file_path_2 = ''

#~~~~ FUNCTIONS~~~~

def open_rules_file():
  global file_path_1
  filename1 = askopenfilename()
  file_path_1 = os.path.abspath(filename1)
  print file_path_1
  entry1.delete(0, END)
  entry1.insert(0, file_path_1)

def open_src_file():
  global file_path_2
  filename2 = askopenfilename()
  file_path_2 = os.path.abspath(filename2)
  print file_path_2
  entry2.delete(0, END)
  entry2.insert(0, file_path_2)

#~~~~~~ GUI ~~~~~~~~

root = Tk()
root.title('MY GUI')
root.geometry("1000x300+250+100")

mf = Frame(root)
mf.pack()
f1 = Frame(mf, width=600, height=250)
f1.pack(fill=X)
f2 = Frame(mf, width=600, height=250)
f2.pack()
f3 = Frame(mf, width=600, height=250)
f3.pack()

file_path_1 = StringVar
file_path_2 = StringVar

Label(f1,text="Select Rules Sheet (xls)").grid(row=1, column=0, sticky='e')
entry1 = Entry(f1, width=70, textvariable=file_path_1)
entry1.grid(row=1,column=1,padx=2,pady=2,sticky='we',columnspan=25)
Button(f1, text="Browse1", command=open_rules_file).grid(row=1, column=27, sticky='ew', padx=8, pady=4)

Label(f2,text="Select COBOL Source   ").grid(row=2, column=0, sticky='e')
entry2 = Entry(f2, width=70, textvariable=file_path_2)
entry2.grid(row=2,column=1,padx=2,pady=2,sticky='we',columnspan=25)
Button(f2, text="Browse2", command=open_src_file).grid(row=2, column=27, sticky='ew', padx=8, pady=4)

Button(f3, text='Quit', command=f3.quit).grid(row=3, column=0, sticky=W, pady=4)
root.mainloop()

Body:
Instead of creating object of StringVar class you have just assigned class to those variable

import os
import Tkinter
import tkFileDialog
from tkFileDialog import askopenfilename
from Tkinter import *

file_path_1 = ''
file_path_2 = ''

#~~~~ FUNCTIONS~~~~

def open_rules_file():
  global file_path_1
  filename1 = askopenfilename()
  file_path_1 = os.path.abspath(filename1)
  print file_path_1
  entry1.delete(0, END)
  entry1.insert(0, file_path_1)

def open_src_file():
  global file_path_2
  filename2 = askopenfilename()
  file_path_2 = os.path.abspath(filename2)
  print file_path_2
  entry2.delete(0, END)
  entry2.insert(0, file_path_2)

#~~~~~~ GUI ~~~~~~~~

root = Tk()
root.title('MY GUI')
root.geometry("1000x300+250+100")

mf = Frame(root)
mf.pack()
f1 = Frame(mf, width=600, height=250)
f1.pack(fill=X)
f2 = Frame(mf, width=600, height=250)
f2.pack()
f3 = Frame(mf, width=600, height=250)
f3.pack()

##Instead of creating object of that class you have just assigned class to those variable
file_path_1 = StringVar()
file_path_2 = StringVar()

Label(f1,text="Select Rules Sheet (xls)").grid(row=1, column=0, sticky='e')
entry1 = Entry(f1, width=70, textvariable=file_path_1)
entry1.grid(row=1,column=1,padx=2,pady=2,sticky='we',columnspan=25)
Button(f1, text="Browse1", command=open_rules_file).grid(row=1, column=27, sticky='ew', padx=8, pady=4)

Label(f2,text="Select COBOL Source   ").grid(row=2, column=0, sticky='e')
entry2 = Entry(f2, width=70, textvariable=file_path_2)
entry2.grid(row=2,column=1,padx=2,pady=2,sticky='we',columnspan=25)
Button(f2, text="Browse2", command=open_src_file).grid(row=2, column=27, sticky='ew', padx=8, pady=4)

Button(f3, text='Quit', command=f3.quit).grid(row=3, column=0, sticky=W, pady=4)
root.mainloop()


问:
Magento reports an install error: "Database server does not support the InnoDB storage engine"
While installing Magento on server I got the following error

```<code>Database server does not support the InnoDB storage engine.

Database connection error.
</code>```

How can I overcome this?

答:
Depends on the hosting company.

if you have SSH, Login into you VPS with SSH and root

Open the following file (nano /etc/my.cnf)

Find the following line and comment it out. (skip-inndob) remove the #
[mysqld]
#skip-inndob

Now login into your WHM, Go to "Restart Services" and click on: SQL Server (MySQL), Then confirm the process with a “Yes”

All of these steps should activate the InnoDB module, you can test it by going into your phpMyAdmin > SQL
Enter: show engines; command into the empty field and press
It should give the output:

ContentLicense: CC BY-SA 4.0

Body:
While installing Magento on server I got the following error

Database server does not support the InnoDB storage engine.

Database connection error.

How can I overcome this?


问:
How to properly insert an @Entity when there is an @Embeddable ID
Here is my code

User class

```<code>@Entity
public class User implements Serializable{

    /**
     *
     */
    private static final long serialVersionUID = 1L;

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

    @Column
    private String username;

    @OneToMany(fetch=FetchType.EAGER)
    @JoinColumn(name="APP_USER_ID", referencedColumnName="id")
    private List<UserRole> roles;

    @Column
    private String email;

    @Column
    private String password;

    protected User(){

    }

    public User(String username, String email, String password, List<UserRole> roles){
        this.username = username;
        this.email= email;
        this.password= password;
        this.roles= roles;
    }
</code>```

UserRole Class

```<code>@Entity
@Table(name = "user_role")
public class UserRole {
    @Embeddable
    public static class Id implements Serializable {
        private static final long serialVersionUID = 1322120000551624359L;

        @Column(name = "APP_USER_ID")
        protected Integer userId;

        @Enumerated(EnumType.STRING)
        @Column(name = "ROLE")
        protected Role role;

        public Id() { }

        public Id(Integer userId, Role role) {
            this.userId = userId;
            this.role = role;
        }
    }

    @EmbeddedId
    Id id = new Id();

    @Enumerated(EnumType.STRING)
    @Column(name = "ROLE", insertable=false, updatable=false)
    protected Role role;

    public Role getRole() {
        return role;
    }
}
</code>```

These are the tables in the database

user Table ->
| id | email | password | username |

user_role Table ->
| ROLE | APP_USER_ID |

In this project one user can have many roles.
In my service class i'm trying to save the user like this (The code below is not working,it is more like a pseudo code, but according to my current understanding i feel like i should follow this kind of an approach),

```<code>return userRepository.save(new User(username, email, encoder.encode(password)),
            new List<UserRole>(){{
                add(//create a new UserRole...);
            }}));
</code>```

I'm some what new to spring/hibernate and i cannot figure out how to insert a user properly to the database with hibernate.

答: The UserRole class doesn't have any constructor that takes any arguments so you can't write this: new UserRole(USERID,"ADMIN"), however you want to create a userId by the inner class Id so probably you need to write it like this: new UserRole.Id(USERID,"ADMIN").

Body:
Here is my code

User class

@Entity
public class User implements Serializable{

    /**
     *
     */
    private static final long serialVersionUID = 1L;

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

    @Column
    private String username;

    @OneToMany(fetch=FetchType.EAGER)
    @JoinColumn(name="APP_USER_ID", referencedColumnName="id")
    private List<UserRole> roles;

    @Column
    private String email;

    @Column
    private String password;

    protected User(){

    }

    public User(String username, String email, String password, List<UserRole> roles){
        this.username = username;
        this.email= email;
        this.password= password;
        this.roles= roles;
    }

UserRole Class

@Entity
@Table(name = "user_role")
public class UserRole {
    @Embeddable
    public static class Id implements Serializable {
        private static final long serialVersionUID = 1322120000551624359L;

        @Column(name = "APP_USER_ID")
        protected Integer userId;

        @Enumerated(EnumType.STRING)
        @Column(name = "ROLE")
        protected Role role;

        public Id() { }

        public Id(Integer userId, Role role) {
            this.userId = userId;
            this.role = role;
        }
    }

    @EmbeddedId
    Id id = new Id();

    @Enumerated(EnumType.STRING)
    @Column(name = "ROLE", insertable=false, updatable=false)
    protected Role role;

    public Role getRole() {
        return role;
    }
}

These are the tables in the database

user Table ->
| id | email | password | username |

user_role Table ->
| ROLE | APP_USER_ID |

In this project one user can have many roles.
In my service class i'm trying to save the user like this (The code below is not working,it is more like a pseudo code, but according to my current understanding i feel like i should follow this kind of an approach),

return userRepository.save(new User(username, email, encoder.encode(password)),
            new List<UserRole>(){{
                add(//create a new UserRole...);
            }}));

I'm some what new to spring/hibernate and i cannot figure out how to insert a user properly to the database with hibernate.


问:
express node.js making a get request to another server from node route
So the client makes a get request using a button on the index page. This sends some information to a route which has been set up as follows:

app.js

```<code>var route = require('./routes/index');
var button = require('./routes/button');
app.use('/', index);
app.use('/button', button);
</code>```

The request is sent from a client-side directory to the node framework whenever someone presses the button. If the request is sent to 'localhost:port/button', then the button.js file mentioned above will receive the request. So in the button.js file we have something like the following:

```<code>var express = require('express');
var router = express.Router();
var someData = '';

router.get('/', function (req, res, next) {
    //make a get request here such that someData
    //receives whatever the request returns from another
    //set up framework(i.e. Spring...)
    someData = getRequest('some other URL');
    res.send(someData);
};
module.exports = router;
</code>```

The problem here is that the getRequest('some other URL') within the router get request never receives any information.

Also (as a side-note), I cannot seem to find in the express API as to why we have

```<code>router.get('/')...
</code>```

instead of

```<code>router.get('/button')...
</code>```

to access and make requests to the button page.

Any help would be very much appreciated!

答:
I guess you are confusing what is server code and client code or do I´m missing something?

I´ll try to explain the way it works:

Server code:

```<code>var express = require('express');
var router = express.Router();
var someData = '';

router.get('/yearStations/:id', function (req, res, next) {
    //make a get request here such that someData
    //receives whatever -the id parameter- the request returns from another
    //This is express.js
    someData = getYourDataFromDataBase(req.params.id);
    res.send(someData);
};
module.exports = router;
</code>```

Client code:

JS (angular.js)

```<code>$scope.getInfo = function() { //here you make the GET call to the server
    $http.get("http://localhost:XXXX/yearStations/Spring").then(
      function(success){
        alert(success.data);//this should be your data
      });
};
</code>```

HTML

```<code><button ng-click="getInfo()">getInfo</button>
</code>```

Body:
So the client makes a get request using a button on the index page. This sends some information to a route which has been set up as follows:

app.js

var route = require('./routes/index');
var button = require('./routes/button');
app.use('/', index);
app.use('/button', button);

The request is sent from a client-side directory to the node framework whenever someone presses the button. If the request is sent to 'localhost:port/button', then the button.js file mentioned above will receive the request. So in the button.js file we have something like the following:

var express = require('express');
var router = express.Router();
var someData = '';

router.get('/', function (req, res, next) {
    //make a get request here such that someData
    //receives whatever the request returns from another
    //set up framework(i.e. Spring...)
    someData = getRequest('some other URL');
    res.send(someData);
};
module.exports = router;

The problem here is that the getRequest('some other URL') within the router get request never receives any information.

Also (as a side-note), I cannot seem to find in the express API as to why we have

router.get('/')...

instead of

router.get('/button')...

to access and make requests to the button page.

Any help would be very much appreciated!

Body:
I guess you are confusing what is server code and client code or do I´m missing something?

I´ll try to explain the way it works:

Server code:

var express = require('express');
var router = express.Router();
var someData = '';

router.get('/yearStations/:id', function (req, res, next) {
    //make a get request here such that someData
    //receives whatever -the id parameter- the request returns from another
    //This is express.js
    someData = getYourDataFromDataBase(req.params.id);
    res.send(someData);
};
module.exports = router;

Client code:

JS (angular.js)

$scope.getInfo = function() { //here you make the GET call to the server
    $http.get("http://localhost:XXXX/yearStations/Spring").then(
      function(success){
        alert(success.data);//this should be your data
      });
};

HTML

<button ng-click="getInfo()">getInfo</button>


问:
Response to class
i have http get request like

```<code>{"meta":{"code":200,"requestId":"595cc7784c1f67701d721227"},"response":{"venues":[{"id":"5564370c498e52484ec3249f","name":"Aras Döner & Kokoreç","contact":{},"location":{"lat":41.187417726573926,"lng":27.76829713785891,"labeledLatLngs":[{"label":"display","lat":41.187417726573926,"lng":27.76829713785891}],"distance":12,"cc":"TR","country":"Türkiye","formattedAddress":["Türkiye"]},"categories":[{"id":"4bf58dd8d48988d16e941735","name":"Fast Food Restoranı","pluralName":"Fast Food Restoranları","shortName":"Fast Food","icon":{"prefix":"https:\/\/ss3.4sqi.net\/img\/categories_v2\/food\/fastfood_","suffix":".png"},"primary":true}],"verified":false,"stats":{"checkinsCount":2038,"usersCount":740,"tipCount":0},"allowMenuUrlEdit":true,"beenHere":{"lastCheckinExpiredAt":0},"specials":{"count":0,"items":[]},"hereNow":{"count":0,"summary":"Burada kimse yok","groups":[]},"referralId":"v-1499252600","venueChains":[],"hasPerk":false}],"confident":false}}
</code>```

How can i print specific attribute like "venues" name=...

答:
you can print the value in the console using console.log()

For example, to print the names of all venues in the response...

```<code>var r = {"meta":{"code":200,"requestId":"595cc7784c1f67701d721227"},"response":{"venues":[{"id":"5564370c498e52484ec3249f","name":"Aras Döner & Kokoreç","contact":{},"location":{"lat":41.187417726573926,"lng":27.76829713785891,"labeledLatLngs":[{"label":"display","lat":41.187417726573926,"lng":27.76829713785891}],"distance":12,"cc":"TR","country":"Türkiye","formattedAddress":["Türkiye"]},"categories":[{"id":"4bf58dd8d48988d16e941735","name":"Fast Food Restoranı","pluralName":"Fast Food Restoranları","shortName":"Fast Food","icon":{"prefix":"https:\/\/ss3.4sqi.net\/img\/categories_v2\/food\/fastfood_","suffix":".png"},"primary":true}],"verified":false,"stats":{"checkinsCount":2038,"usersCount":740,"tipCount":0},"allowMenuUrlEdit":true,"beenHere":{"lastCheckinExpiredAt":0},"specials":{"count":0,"items":[]},"hereNow":{"count":0,"summary":"Burada kimse yok","groups":[]},"referralId":"v-1499252600","venueChains":[],"hasPerk":false}],"confident":false}};
var venues = r.response.venues;
for (i = 0; i < venues.length; i++) {
    console.log(venues[i].name)
}
</code>```

Title: Response to class

Body:
i have http get request like

{"meta":{"code":200,"requestId":"595cc7784c1f67701d721227"},"response":{"venues":[{"id":"5564370c498e52484ec3249f","name":"Aras Döner & Kokoreç","contact":{},"location":{"lat":41.187417726573926,"lng":27.76829713785891,"labeledLatLngs":[{"label":"display","lat":41.187417726573926,"lng":27.76829713785891}],"distance":12,"cc":"TR","country":"Türkiye","formattedAddress":["Türkiye"]},"categories":[{"id":"4bf58dd8d48988d16e941735","name":"Fast Food Restoranı","pluralName":"Fast Food Restoranları","shortName":"Fast Food","icon":{"prefix":"https:\/\/ss3.4sqi.net\/img\/categories_v2\/food\/fastfood_","suffix":".png"},"primary":true}],"verified":false,"stats":{"checkinsCount":2038,"usersCount":740,"tipCount":0},"allowMenuUrlEdit":true,"beenHere":{"lastCheckinExpiredAt":0},"specials":{"count":0,"items":[]},"hereNow":{"count":0,"summary":"Burada kimse yok","groups":[]},"referralId":"v-1499252600","venueChains":[],"hasPerk":false}],"confident":false}}

How can i print specific attribute like "venues" name=...

Body:
you can print the value in the console using console.log()

For example, to print the names of all venues in the response...

var r = {"meta":{"code":200,"requestId":"595cc7784c1f67701d721227"},"response":{"venues":[{"id":"5564370c498e52484ec3249f","name":"Aras Döner & Kokoreç","contact":{},"location":{"lat":41.187417726573926,"lng":27.76829713785891,"labeledLatLngs":[{"label":"display","lat":41.187417726573926,"lng":27.76829713785891}],"distance":12,"cc":"TR","country":"Türkiye","formattedAddress":["Türkiye"]},"categories":[{"id":"4bf58dd8d48988d16e941735","name":"Fast Food Restoranı","pluralName":"Fast Food Restoranları","shortName":"Fast Food","icon":{"prefix":"https:\/\/ss3.4sqi.net\/img\/categories_v2\/food\/fastfood_","suffix":".png"},"primary":true}],"verified":false,"stats":{"checkinsCount":2038,"usersCount":740,"tipCount":0},"allowMenuUrlEdit":true,"beenHere":{"lastCheckinExpiredAt":0},"specials":{"count":0,"items":[]},"hereNow":{"count":0,"summary":"Burada kimse yok","groups":[]},"referralId":"v-1499252600","venueChains":[],"hasPerk":false}],"confident":false}};
var venues = r.response.venues;
for (i = 0; i < venues.length; i++) {
    console.log(venues[i].name)
}


问:
Any way to replace characters on Swift String?
I am looking for a way to replace characters in a Swift String.

Example: "This is my string"

I would like to replace " " with "+" to get "This+is+my+string".

How can I achieve this?

答:
Here's an extension for an in-place occurrences replace method on String, that doesn't no an unnecessary copy and do everything in place:

```<code>extension String {
    mutating func replaceOccurrences<Target: StringProtocol, Replacement: StringProtocol>(of target: Target, with replacement: Replacement, options: String.CompareOptions = [], locale: Locale? = nil) {
        var range: Range<Index>?
        repeat {
            range = self.range(of: target, options: options, range: range.map { self.index($0.lowerBound, offsetBy: replacement.count)..<self.endIndex }, locale: locale)
            if let range = range {
                self.replaceSubrange(range, with: replacement)
            }
        } while range != nil
    }
}
</code>```

(The method signature also mimics the signature of the built-in String.replacingOccurrences() method)

May be used in the following way:

```<code>var string = "this is a string"
string.replaceOccurrences(of: " ", with: "_")
print(string) // "this_is_a_string"
</code>```

Body:
Here's an extension for an in-place occurrences replace method on String, that doesn't no an unnecessary copy and do everything in place:

extension String {
    mutating func replaceOccurrences<Target: StringProtocol, Replacement: StringProtocol>(of target: Target, with replacement: Replacement, options: String.CompareOptions = [], locale: Locale? = nil) {
        var range: Range<Index>?
        repeat {
            range = self.range(of: target, options: options, range: range.map { self.index($0.lowerBound, offsetBy: replacement.count)..<self.endIndex }, locale: locale)
            if let range = range {
                self.replaceSubrange(range, with: replacement)
            }
        } while range != nil
    }
}

(The method signature also mimics the signature of the built-in String.replacingOccurrences() method)

May be used in the following way:

var string = "this is a string"
string.replaceOccurrences(of: " ", with: "_")
print(string) // "this_is_a_string"


问:
I have daily tables on BigQuery. How to query the "newest" one?
I create daily tables. How to query the "newest" one?

For example GitHubArchive now publishes daily tables - instead of a monolithic one (see /r/bigquery/.../github_archive_changes_monthly_and_daily_tables/).

答:
Felipe's answer uses Legacy SQL. Here's a solution in Standard SQL.

If your table names have a predictable suffix like GitHub's example in your link (which uses a YYYYMMDD suffix for each day), you can use wildcard tables and TABLE_SUFFIX:

```<code>SELECT COUNT(*)
FROM `githubarchive.day.events_*`
WHERE _TABLE_SUFFIX = (
  SELECT MAX(SUBSTR(table_id, -8))
  FROM `githubarchive.day.__TABLES_SUMMARY__`
  WHERE REGEXP_CONTAINS(table_id, "events_\\d{8}")
)
</code>```

If you want to rely on BigQuery's metadata about creation time instead of the prefix, you can do:

```<code>SELECT COUNT(*)
FROM `githubarchive.day.*`
WHERE _TABLE_SUFFIX = (
  SELECT table_id
  FROM `githubarchive.day.__TABLES_SUMMARY__`
  ORDER BY creation_time DESC
  LIMIT 1
)
</code>```

Note that if you have tables with different schemas in your project, the latter syntax is dangerous, since the query will use the schema of the first table it sees in the wildcard.

If you're trying to create tables that are partitioned by date, there's a BigQuery feature called date-partitioned tables that does just that, and makes it easier to query afterwards.

Body:
Felipe's answer uses Legacy SQL. Here's a solution in Standard SQL.

If your table names have a predictable suffix like GitHub's example in your link (which uses a YYYYMMDD suffix for each day), you can use wildcard tables and TABLE_SUFFIX:

SELECT COUNT(*)
FROM `githubarchive.day.events_*`
WHERE _TABLE_SUFFIX = (
  SELECT MAX(SUBSTR(table_id, -8))
  FROM `githubarchive.day.__TABLES_SUMMARY__`
  WHERE REGEXP_CONTAINS(table_id, "events_\\d{8}")
)

If you want to rely on BigQuery's metadata about creation time instead of the prefix, you can do:

SELECT COUNT(*)
FROM `githubarchive.day.*`
WHERE _TABLE_SUFFIX = (
  SELECT table_id
  FROM `githubarchive.day.__TABLES_SUMMARY__`
  ORDER BY creation_time DESC
  LIMIT 1
)

Note that if you have tables with different schemas in your project, the latter syntax is dangerous, since the query will use the schema of the first table it sees in the wildcard.

If you're trying to create tables that are partitioned by date, there's a BigQuery feature called date-partitioned tables that does just that, and makes it easier to query afterwards.


问:
How to get an hourly average number of unique persons using Hive?
I have this data in a table my_table:

```<code>camera_id     person_id         datetime
1             1                 2017-03-02 18:06:20
1             1                 2017-03-02 18:05:10
1             1                 2017-04-01 18:04:09
2             1                 2017-03-02 19:06:50
2             2                 2017-03-02 19:07:22
2             2                 2017-03-02 19:09:15
2             3                 2017-05-03 19:07:05
2             4                 2017-05-03 19:19:08
2             5                 2017-05-03 19:20:18
</code>```

I need to count an hourly average number of UNIQUE persons detected by each camera.

For example let's take camera 2 and a time window from 19:00 to 20:00. The camera determined 2 unique visits on 2017-03-02 and 3 unique visits on 2017-05-03. So, the answer is (2+3)/2 = 2.5

Expected result:

```<code>camera_id   HOUR   HOURLY_AVG_COUNT
1           18     1
2           19     2.5
</code>```

答:
```<code>select      camera_id
           ,hour(datetime)                                                                                as hour
           ,count(distinct person_id,date(datetime),hour(datetime)) /
                count(distinct date(datetime),hour(datetime))    as hourly_avg_count

from        my_table

group by    camera_id
           ,hour(datetime)

order by    camera_id
;
</code>```

```<code>+-----------+------+------------------+
| camera_id | hour | hourly_avg_count |
+-----------+------+------------------+
|         1 |   18 | 1                |
|         2 |   19 | 2.5              |
+-----------+------+------------------+
</code>```

P.s.

date(datetime),hour(datetime) can be also replaced by one of the following:

substr(cast(datetimeas string),1,13)

date_format(datetime,'yyyy-MM-dd HH')

Body:
I have this data in a table my_table:

camera_id     person_id         datetime
1             1                 2017-03-02 18:06:20
1             1                 2017-03-02 18:05:10
1             1                 2017-04-01 18:04:09
2             1                 2017-03-02 19:06:50
2             2                 2017-03-02 19:07:22
2             2                 2017-03-02 19:09:15
2             3                 2017-05-03 19:07:05
2             4                 2017-05-03 19:19:08
2             5                 2017-05-03 19:20:18

I need to count an hourly average number of UNIQUE persons detected by each camera.

For example let's take camera 2 and a time window from 19:00 to 20:00. The camera determined 2 unique visits on 2017-03-02 and 3 unique visits on 2017-05-03. So, the answer is (2+3)/2 = 2.5

Expected result:

camera_id   HOUR   HOURLY_AVG_COUNT
1           18     1
2           19     2.5

Body:
select      camera_id
           ,hour(datetime)                                                                                as hour
           ,count(distinct person_id,date(datetime),hour(datetime)) /
                count(distinct date(datetime),hour(datetime))    as hourly_avg_count

from        my_table

group by    camera_id
           ,hour(datetime)

order by    camera_id
;

+-----------+------+------------------+
| camera_id | hour | hourly_avg_count |
+-----------+------+------------------+
|         1 |   18 | 1                |
|         2 |   19 | 2.5              |
+-----------+------+------------------+

P.s.

date(datetime),hour(datetime) can be also replaced by one of the following:

substr(cast(datetimeas string),1,13)

date_format(datetime,'yyyy-MM-dd HH')


问:
Change text of button when pressing it ReactJS
I want to change the text of a button when I press it.

This is what I want to achieve: https://codepen.io/gaearon/pen/xEmzGg?editors=0010 , but I can't get my code to work (newbie).

```<code>class ObjectKeyDisplay extends Component {
  constructor(props) {
    super(props)
    this.state = {
      open: false
    }
    this.handleClick = this.handleClick.bind(this)
  }

  handleClick() {
    this.setState(prevState => ({
      open: prevState.open
    }))
  }

  renderInner() {
      if (!this.props.value) return <td className = "inactive" > < /td>
      if (!this.state.open && this.props.schema.type === 'belongs_to')
      return <td onClick={(e) => this.setState({open: !this.state.open})}>
        <button onClick={this.handleCLick}>
          {this.state.open ? 'OFF' : 'ON'}
        </button>
      </td>
}
</code>```

Here's my code and as you might have seen I want to toggle the text OFF and ON when pressing the button. I can add more code if needed. Really grateful for all the support I can get.

答:
Here is what you are looking for:</p>

```<code>handleClick() {
    const open = !this.state.open;
    this.setState({open})
}
</code>```

Body:
I want to change the text of a button when I press it.

This is what I want to achieve: https://codepen.io/gaearon/pen/xEmzGg?editors=0010 , but I can't get my code to work (newbie).

class ObjectKeyDisplay extends Component {
  constructor(props) {
    super(props)
    this.state = {
      open: false
    }
    this.handleClick = this.handleClick.bind(this)
  }

  handleClick() {
    this.setState(prevState => ({
      open: prevState.open
    }))
  }

  renderInner() {
      if (!this.props.value) return
      if (!this.state.open && this.props.schema.type === 'belongs_to')
      return  this.setState({open: !this.state.open})}>
        <button onClick={this.handleCLick}>
          {this.state.open ? 'OFF' : 'ON'}
        </button>

}

Here's my code and as you might have seen I want to toggle the text OFF and ON when pressing the button. I can add more code if needed. Really grateful for all the support I can get.

Body:
Here is what you are looking for:

handleClick() {
    const open = !this.state.open;
    this.setState({open})
}


问:
Align text on the side and top of other text css
How can I achieve this using css?

This is what I've tried:

R$
    54.133
    48```

答:
label{
  font-size:20px;
}

label sup{
  font-size: 12px;
  vertical-align: top
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><label><sup>R$</sup>54.133<sup>73</sup></label></code>```

Use superscript tag

```<code><label><sup>R$</sup>54.133<sup>73</sup></label>
</code>```

https://www.w3schools.com/tags/tag_sup.asp

Body:
label{
  font-size:20px;
}

label sup{
  font-size: 12px;
  vertical-align: top
}

<label><sup>R$</sup>54.133<sup>73</sup></label>

Use superscript tag

<label><sup>R$</sup>54.133<sup>73</sup></label>

https://www.w3schools.com/tags/tag_sup.asp


问:
How to use summernote in vueJS? Error:summernote is not a function
I am trying to use summernote in vueJS. Under Laravel framework. In blade.php document, I have set an id of summernot_div:

```<code><input type="text" v-model="articleForChange.article_body" class="form-control" id="summernote_div" placeholder="Article Content">
</code>```

Then, in the corresponding vueJS document, within the created() method:

```<code>$('#summernote_div').summernote({
  height: 300, // set editor height
  minHeight: null, // set minimum height of editor
  maxHeight: null, // set maximum height of editor
  focus: true // set focus to editable area after initializing summernote
});
console.log(summernote);
</code>```

But the page just response:

Uncaught TypeError: $(...).summernote is not a function.

Is there anything I miss to do?

答:
I had the same problem,

Make sure that you added source. (CDN or Downloaded File)

```<code><!-- include libraries(jQuery, bootstrap) -->
<link href="http://netdna.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.css" rel="stylesheet">
<script src="http://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.4/jquery.js"></script>
<script src="http://netdna.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.js"></script>

<!-- include summernote css/js-->
<link href="http://cdnjs.cloudflare.com/ajax/libs/summernote/0.8.4/summernote.css" rel="stylesheet">
<script src="http://cdnjs.cloudflare.com/ajax/libs/summernote/0.8.4/summernote.js"></script>
</code>```

Then wrap your javascript code in         (function ($) { //your code gooes here })(jQuery);

Like:

```<code>(function ($) {
$('#summernote_div').summernote({
  height: 300, // set editor height
  minHeight: null, // set minimum height of editor
  maxHeight: null, // set maximum height of editor
  focus: true // set focus to editable area after initializing summernote
});
})(jQuery);
</code>```

This solve my problem.

Body:
I am trying to use summernote in vueJS. Under Laravel framework. In blade.php document, I have set an id of summernot_div:

<input type="text" v-model="articleForChange.article_body" class="form-control" id="summernote_div" placeholder="Article Content">

Then, in the corresponding vueJS document, within the created() method:

$('#summernote_div').summernote({
  height: 300, // set editor height
  minHeight: null, // set minimum height of editor
  maxHeight: null, // set maximum height of editor
  focus: true // set focus to editable area after initializing summernote
});
console.log(summernote);

But the page just response:

Uncaught TypeError: $(...).summernote is not a function.

Is there anything I miss to do?

Body:
I had the same problem,

Make sure that you added source. (CDN or Downloaded File)

<!-- include libraries(jQuery, bootstrap) -->
<link href="http://netdna.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.css" rel="stylesheet">
<script src="http://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.4/jquery.js"></script>
<script src="http://netdna.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.js"></script>

<!-- include summernote css/js-->
<link href="http://cdnjs.cloudflare.com/ajax/libs/summernote/0.8.4/summernote.css" rel="stylesheet">
<script src="http://cdnjs.cloudflare.com/ajax/libs/summernote/0.8.4/summernote.js"></script>

Then wrap your javascript code in         (function ($) { //your code gooes here })(jQuery);

Like:

(function ($) {
$('#summernote_div').summernote({
  height: 300, // set editor height
  minHeight: null, // set minimum height of editor
  maxHeight: null, // set maximum height of editor
  focus: true // set focus to editable area after initializing summernote
});
})(jQuery);

This solve my problem.


问:
How to Get/Check The Internet Connection Strength in Android Studio
How to get/check internet connection strength in android studio?We can check whether internet is there or not ? But because of less internet strength developed android apps may crash

Thanks in advance

答:
Check out this article:
https://developer.android.com/training/monitoring-device-state/connectivity-monitoring.html

It's about connectivity status and type, from connectivity type you can assume a quality of service, like in this answer: https://stackoverflow.com/a/11088823


问:
Why mySQL table won't export properly as HTML table
I use bootstrap 3 template and connect to a mysql database, sort the table and export some datas as HTML table in order to display it on bootstrap webpage.

Here is the mySQL look like :

The following code won't get expected results:

```<code><div class="well">

<?php

//MySQL Database Connect
include '/includes/dbconnect.php';

$result = mysqli_query($conn,"SELECT * FROM webpilot ORDER BY NEXT_EVENT ASC");

if(mysqli_num_rows($result) >= 1) {

    echo '<table class="table table-striped table-bordered table-hover">';
    echo "<tr><th>ID</th><th>NAME:</th><th>EPOCH</th></tr>";
    while($row = mysqli_fetch_array($results)) {
        echo "<tr><td>";
        echo $row['ID'];
        echo "</td><td>";
        echo $row['NAME'];
        echo "</td><td>";
        echo $row['NEXT_EVENT'];
        echo "</td></tr>";
    }
    echo "</table>";
}
?>
</div>  <!-- well -->
</code>```

dbconnect.php :

```<code><?php

$localhost="xxx.xx.xxx.com";
$username="dboxxxxxxx";
$password="xxxxxx";
$database="dbxxxxxx";

$conn = mysqli_connect($localhost,$username,$password,$database);

//test if connection failed
if(mysqli_connect_errno()){
    die("connection failed: "
        . mysqli_connect_error()
        . " (" . mysqli_connect_errno()
        . ")");
}
?>
</code>```

original page link can be found here : http://s529471052.onlinehome.fr/bs3/gpio/dyntable.htm

答:
```<code>$result = mysqli_query($conn,"SELECT ID, NAME, NEXT_EVENT  FROM webpilot ORDER BY NEXT_EVENT ASC");

$table = '<table>
            <tr>
                <th>ID</th>
                <th>NAME</th>
                <th>EPOCH</th>
            </tr>';
if($result ) {
    while ($row = mysqli_fetch_assoc($result)) {
        $table .= '<tr>
                    <td>'. $row['ID'] .'</td>
                    <td>'. $row['NAME'] .'</td>
                    <td>'. $row['NEXT_EVENT'] .'</td>
                   </tr>';
    }
} else {
    $table .= '<tr><td colspan="3">No date found</td></tr>';
}
$table .= '</table>';
echo $table;
</code>```

Try this, This will help for your requirement.

Body:
I use bootstrap 3 template and connect to a mysql database, sort the table and export some datas as HTML table in order to display it on bootstrap webpage.

Here is the mySQL look like :

The following code won't get expected results:

<?php

//MySQL Database Connect
include '/includes/dbconnect.php';

$result = mysqli_query($conn,"SELECT * FROM webpilot ORDER BY NEXT_EVENT ASC");

if(mysqli_num_rows($result) >= 1) {

    echo '
';
    echo "
ID	NAME:	EPOCH
";
    while($row = mysqli_fetch_array($results)) {
        echo "
";
        echo $row['ID'];
        echo "	";
        echo $row['NAME'];
        echo "	";
        echo $row['NEXT_EVENT'];
        echo "
";
    }
    echo "
";
}
?>

dbconnect.php :

<?php

$localhost="xxx.xx.xxx.com";
$username="dboxxxxxxx";
$password="xxxxxx";
$database="dbxxxxxx";

$conn = mysqli_connect($localhost,$username,$password,$database);

//test if connection failed
if(mysqli_connect_errno()){
    die("connection failed: "
        . mysqli_connect_error()
        . " (" . mysqli_connect_errno()
        . ")");
}
?>

original page link can be found here : http://s529471052.onlinehome.fr/bs3/gpio/dyntable.htm

Body:
$result = mysqli_query($conn,"SELECT ID, NAME, NEXT_EVENT  FROM webpilot ORDER BY NEXT_EVENT ASC");

$table = '<table>
            <tr>
                <th>ID</th>
                <th>NAME</th>
                <th>EPOCH</th>
            </tr>';
if($result ) {
    while ($row = mysqli_fetch_assoc($result)) {
        $table .= '<tr>
                    <td>'. $row['ID'] .'</td>
                    <td>'. $row['NAME'] .'</td>
                    <td>'. $row['NEXT_EVENT'] .'</td>
                   </tr>';
    }
} else {
    $table .= '<tr><td colspan="3">No date found</td></tr>';
}
$table .= '</table>';
echo $table;

Try this, This will help for your requirement.


问:
How to install jenkins offline?
I could successfully install the jenkins online over my laptop. But while trying to install the jenkins offline (on my office workstation which cannot be connected to internet) the hell breaks loose.
After running the jenkins.war over command line although the jenkins was successfully installed yet some of the plugins were missing.I managed to get some help from the post How to install a plugin in Jenkins manually?

But then each of the plugins have to be individually downloaded and then copied over to my offline machine. So I had a trick.
I copied all the folders under .jenkins directory (in my online installation machine) and then copied them to my offline machine. Whoa!
It worked!
But I still get one single error:

```<code>Maven Integration Plugin V2.16 .javadoc 1.0 is missing. To fix, install v1.0 or later
</code>```

So is there a way/website/pdf/repository which is a one stop solution/steps to smoothly install (read has all the required dependencies as a zip) Jenkins in offline mode. (If not, to the creators of Jenkins: Would it be a good idea to have one?)

答: You can download the .hpi version of plugins required and paste them in plugins folder at jenkins_home and then restart the jenkins,then you can able to use those plugins. </p>

Title: How to install jenkins offline?

Body:
I could successfully install the jenkins online over my laptop. But while trying to install the jenkins offline (on my office workstation which cannot be connected to internet) the hell breaks loose.
After running the jenkins.war over command line although the jenkins was successfully installed yet some of the plugins were missing.I managed to get some help from the post How to install a plugin in Jenkins manually?

But then each of the plugins have to be individually downloaded and then copied over to my offline machine. So I had a trick.
I copied all the folders under .jenkins directory (in my online installation machine) and then copied them to my offline machine. Whoa!
It worked!
But I still get one single error:

Maven Integration Plugin V2.16 .javadoc 1.0 is missing. To fix, install v1.0 or later

So is there a way/website/pdf/repository which is a one stop solution/steps to smoothly install (read has all the required dependencies as a zip) Jenkins in offline mode. (If not, to the creators of Jenkins: Would it be a good idea to have one?)


问:
What's the difference in how Nhibernate treats .FirstOrDefault vs .SingleOrDefault? possible bug?
Just starting out with NHibernate and using Nhib 3.0's (3.0.0.2001) Linq with following models

```<code>public class Request
{
    public virtual Guid Id { get; set; }
    public virtual State {get;set;}
}
public class State
{
    public virtual Guid Id {get;set;}
}
</code>```

So I'm just trying to retrieve a Request based on it's State Id.

```<code>_session.Query<Request>().Where(x => x.State.Id==someGuidValue).FirstOrDefault();
</code>```

Seems pretty straight forward, but this gets a sql error based on generated sql where it looks like @p0 parameter is missing, though not sure why'd it be included here.

```<code>{"Line 1: Incorrect syntax near '('."}
 select TOP (@p0) requ0_.Id as Id0_
, requ0_.State_id as State8_0_
from [Request] requ0_ where requ0_.State_id=@p1 ]
  Name:p1 - Value:a2e63925-6628-4786-a621-9e5200d5ab71
</code>```

However, using SingleOrDefault works, just fine.

```<code>_session.Query<Request>().Where(x => x.State.Id==someGuidValue).SingleOrDefault();
</code>```

Any insight would be appreciated. Thanks

答:
I believe SingleOrDefault will error when more than one records meets your select criteria. Where FirstOrDefault will just pull the first regardless of how many records are returned.

That's how it works in LINQ-To-SQL

ContentLicense: CC BY-SA 2.5

Body:
Just starting out with NHibernate and using Nhib 3.0's (3.0.0.2001) Linq with following models

public class Request
{
    public virtual Guid Id { get; set; }
    public virtual State {get;set;}
}
public class State
{
    public virtual Guid Id {get;set;}
}

So I'm just trying to retrieve a Request based on it's State Id.

_session.Query<Request>().Where(x => x.State.Id==someGuidValue).FirstOrDefault();

Seems pretty straight forward, but this gets a sql error based on generated sql where it looks like @p0 parameter is missing, though not sure why'd it be included here.

{"Line 1: Incorrect syntax near '('."}
 select TOP (@p0) requ0_.Id as Id0_
, requ0_.State_id as State8_0_
from [Request] requ0_ where requ0_.State_id=@p1 ]
  Name:p1 - Value:a2e63925-6628-4786-a621-9e5200d5ab71

However, using SingleOrDefault works, just fine.

_session.Query<Request>().Where(x => x.State.Id==someGuidValue).SingleOrDefault();

Any insight would be appreciated. Thanks


问:
Angular 2/4 : FIlter a table using PipeTransform
I used an exemple of angular2-table building and I use pipe for filtering the table.. I want to filter the table by name when I choose the "input radio"

My pipe filter :

```<code>import * as _ from "lodash";
import {Pipe, PipeTransform} from "@angular/core";

@Pipe({
    name: "dataFilter"
})
export class DataFilterPipe implements PipeTransform {

    transform(array: any[], query: string): any {
        if (query) {
            return _.filter(array, row=>row.name.indexOf(query) > -1);
        }
        return array;
    }
}
</code>```

This is thne plnkr :
    http://plnkr.co/edit/hhv4e8WliLkmpW2Bmn3A?p=preview

How can I filter the table using input radio ?

答:
If you want the radio buttons to actually display some data you have to use appropriate values for those radio buttons that match the data. For example:

```<code><input type="radio" [(ngModel)]="filterQ" value="Ralph" name="filterQ" /> Ralph
</code>```

For the first radio button the value RAP will not match anything based on how you are using your pipe. Changing it to Ralph will now match one record. Also your code is case sensitive so RALPH will not work.

Body:
I used an exemple of angular2-table building and I use pipe for filtering the table.. I want to filter the table by name when I choose the "input radio"

My pipe filter :

import * as _ from "lodash";
import {Pipe, PipeTransform} from "@angular/core";

@Pipe({
    name: "dataFilter"
})
export class DataFilterPipe implements PipeTransform {

    transform(array: any[], query: string): any {
        if (query) {
            return _.filter(array, row=>row.name.indexOf(query) > -1);
        }
        return array;
    }
}

This is thne plnkr :
    http://plnkr.co/edit/hhv4e8WliLkmpW2Bmn3A?p=preview

How can I filter the table using input radio ?

Body:
If you want the radio buttons to actually display some data you have to use appropriate values for those radio buttons that match the data. For example:

<input type="radio" [(ngModel)]="filterQ" value="Ralph" name="filterQ" /> Ralph

For the first radio button the value RAP will not match anything based on how you are using your pipe. Changing it to Ralph will now match one record. Also your code is case sensitive so RALPH will not work.


问:
How to make copyright box stick to bottom of page
I'm trying to make this HTML container stick to the bottom of the page (not the screen, the page)

i.e. A page that scrolls a fair length and the container is at the bottom, but also a page which does not require scrolling, the container is still at the bottom.

I have this code:

.copyright-container {
  box-sizing: border-box;
  padding-right: 20px;
  padding-left: 20px;
  background-color: black;
  text-align: center;
  position: absolute;
  bottom: 0;
  width: 100%;
  height: 150px;
  color: white;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="copyright-container">
  <div class="vert-align">
    <p class="headline">
      Copyright © 2017 RyanTeaches - All Rights Reserved.</p>
  </div>
</div></code>```

The problem with absolute is that while this works fine on pages with little content, and page where I have to scroll, it scrolls up too - it sits at the bottom of the screen, not the bottom of the page.

I also tried using "fixed" but this meant the container remained on the screen the whole time.

I then tried "relative" and while this worked correctly for the page that needed scrolling, and sat it at the bottom, the page with little content, it sat halfway up the page.

答:
To solve your problem, you need to use javascript:

Put the element normally at the end of the flow and it will be at the bottom of the page like you want: However, when the content is too small, you need to position your element fixed to be at the bottom of the screen. You can do that after the load of the page.

It makes something like that in JQuery:

```<code>$( window ).load(function() {
  if ($(window).height() > $('#content').height() + $('#navigation').height()) {
    $('.copyright-container').css({
      position: 'fixed'
      bottom: 0
    });
  }
});
</code>```

Hope this helps!

Body:
I'm trying to make this HTML container stick to the bottom of the page (not the screen, the page)

i.e. A page that scrolls a fair length and the container is at the bottom, but also a page which does not require scrolling, the container is still at the bottom.

I have this code:

.copyright-container {
  box-sizing: border-box;
  padding-right: 20px;
  padding-left: 20px;
  background-color: black;
  text-align: center;
  position: absolute;
  bottom: 0;
  width: 100%;
  height: 150px;
  color: white;
}

      Copyright © 2017 RyanTeaches - All Rights Reserved.

The problem with absolute is that while this works fine on pages with little content, and page where I have to scroll, it scrolls up too - it sits at the bottom of the screen, not the bottom of the page.

I also tried using "fixed" but this meant the container remained on the screen the whole time.

I then tried "relative" and while this worked correctly for the page that needed scrolling, and sat it at the bottom, the page with little content, it sat halfway up the page.

Body:
To solve your problem, you need to use javascript:

Put the element normally at the end of the flow and it will be at the bottom of the page like you want: However, when the content is too small, you need to position your element fixed to be at the bottom of the screen. You can do that after the load of the page.

It makes something like that in JQuery:

$( window ).load(function() {
  if ($(window).height() > $('#content').height() + $('#navigation').height()) {
    $('.copyright-container').css({
      position: 'fixed'
      bottom: 0
    });
  }
});

Hope this helps!


问:
networked-aframe assign different position to new user
I have a problem in my multiplayer A-Frame environment that I set up with networked-aframe.

I want the first three users that connect to have a different spawn location and any additional user to spawn at the third location, but I can't get it to work. Here's what I have so far in Html:

```<code> <a-entity id="player"
networked="template:#avatar-template;showLocalTemplate:true;"
camera
positioner=""
wasd-controls
look-controls>
<a-cursor></a-cursor>
</a-entity>
</code>```

And here is the JS Component for it:

```<code>AFRAME.registerComponent('positioner', {
init: function() {

        var el = this.el,
            counter = 0;

        if (counter == 0) {
            el.setAttribute('position', {x:-16,  y:6,  z:-10});
            counter++;
        }
        else if(counter == 1) {
            el.setAttribute('position', {x:-10,  y:6,  z:-10});
            counter++;
        }
        else {
            el.setAttribute('position', {x:-5,  y:6,  z:-10});
            counter++;
        }
}
});
</code>```

I found out that I have to sync additional components which I am doing like this:

```<code>var avatarSchema = {
template: '#avatar-template',
components: [
'positioner',
'position',
'rotation',
'scale',
{
  selector: '.head',
  component: 'material'
},
{
  selector: '.hairs',
  component: 'show-child'
}

]
};
       NAF.schemas.add(avatarSchema);
</code>```

It's a big project so there's a lot more code. If you need anything else like the scene setup or the avatar setup let me know and I will add it.

答:
I have a workaround, for I don't fully understand how the component works.

I found there is a player list under the reference NAF.entities.entities

I made a component attached to the scene:

```<code>AFRAME.registerComponent('foo',{
  init:function(){
    setTimeout(function(){
      console.log(Object.keys(NAF.entities.entities));
      console.log(Object.keys(NAF.entities.entities)[0]);
      console.log(Object.keys(NAF.entities.entities).length);
    },5000);
  }
});
</code>```

The first log gives me an array of the players id's.

The second one gives the id of the first element.

The last gives me the number of the players.

You can check for the number of players on load, and depending which player loads, You set his position attribute.

```<code>if(NAF.. == 1) this.el.setAttribute('position',firstPos);
if(NAF.. == 2) this.el.setAttribute('position',secondPos);
if(NAF.. > 2) this.el.setAttribute('position',third);
</code>```

 Working glitch here: glitch.com/edit/#!/sudden-antler

 Of course instead of waiting 5 seconds i should be listening to a loaded event, I'll look into it once im not so busy.

If anyone manages to do this properly with this component, please comment, because i tried to do the position onConnect ( too early, the other players entities are still not loaded ), tried waiting till the scene loads, but the closest i got is by dynamically creating the player when i get the number of players, after a fixed time.

Body:
I have a problem in my multiplayer A-Frame environment that I set up with networked-aframe.

I want the first three users that connect to have a different spawn location and any additional user to spawn at the third location, but I can't get it to work. Here's what I have so far in Html:

And here is the JS Component for it:

AFRAME.registerComponent('positioner', {
init: function() {

        var el = this.el,
            counter = 0;

        if (counter == 0) {
            el.setAttribute('position', {x:-16,  y:6,  z:-10});
            counter++;
        }
        else if(counter == 1) {
            el.setAttribute('position', {x:-10,  y:6,  z:-10});
            counter++;
        }
        else {
            el.setAttribute('position', {x:-5,  y:6,  z:-10});
            counter++;
        }
}
});

I found out that I have to sync additional components which I am doing like this:

var avatarSchema = {
template: '#avatar-template',
components: [
'positioner',
'position',
'rotation',
'scale',
{
  selector: '.head',
  component: 'material'
},
{
  selector: '.hairs',
  component: 'show-child'
}

]
};
       NAF.schemas.add(avatarSchema);

It's a big project so there's a lot more code. If you need anything else like the scene setup or the avatar setup let me know and I will add it.

Body:
I have a workaround, for I don't fully understand how the component works.

I found there is a player list under the reference NAF.entities.entities

I made a component attached to the scene:

AFRAME.registerComponent('foo',{
  init:function(){
    setTimeout(function(){
      console.log(Object.keys(NAF.entities.entities));
      console.log(Object.keys(NAF.entities.entities)[0]);
      console.log(Object.keys(NAF.entities.entities).length);
    },5000);
  }
});

The first log gives me an array of the players id's.

The second one gives the id of the first element.

The last gives me the number of the players.

You can check for the number of players on load, and depending which player loads, You set his position attribute.

if(NAF.. == 1) this.el.setAttribute('position',firstPos);
if(NAF.. == 2) this.el.setAttribute('position',secondPos);
if(NAF.. > 2) this.el.setAttribute('position',third);

 Working glitch here: glitch.com/edit/#!/sudden-antler

 Of course instead of waiting 5 seconds i should be listening to a loaded event, I'll look into it once im not so busy.

If anyone manages to do this properly with this component, please comment, because i tried to do the position onConnect ( too early, the other players entities are still not loaded ), tried waiting till the scene loads, but the closest i got is by dynamically creating the player when i get the number of players, after a fixed time.


问:
Laravel Relationship result can not fetch for same foreign key
My table looks like below,

```<code>donation_requests
---------------------------------------------------------------
| id    name    donation_type_id    donation_request_type_id
|--------------------------------------------------------------
| 1     xyz     1                   3
| 2     pqr     3                   2
| 3     abc     3                   1
| 4     klm     4                   1

donation_types
------------------------
| id    name
-----------------------
| 1     jakat
| 2     sadka
| 3     lillah
| 4     fitra

donation_request_types
------------------------
| id    name
-----------------------
| 1     widow
| 2     masjid
| 3     madresha
</code>```

i want donation_request data with donation_types name and donation_request_types name
In my DonationRequest model code is as below

```<code>public function donation_types()
{
    return $this->belongsTo('App\DonationType','id','donation_type_id');
}

public function donation_request_types()
{
    return $this->belongsTo('App\DonationRequestType','id','donation_request_type_id');
}
</code>```

but in first two row i get proper result but for third row has same donation_type_id as 3 so it give blank and same as in donation_request_type_id

答:
```<code>public function donation_types()
{
    return $this->belongsTo('App\DonationType');
}

public function donation_request_types()
{
    return $this->belongsTo('App\DonationRequestType');
}
</code>```

Body:
My table looks like below,

donation_requests
---------------------------------------------------------------
| id    name    donation_type_id    donation_request_type_id
|--------------------------------------------------------------
| 1     xyz     1                   3
| 2     pqr     3                   2
| 3     abc     3                   1
| 4     klm     4                   1

donation_types
------------------------
| id    name
-----------------------
| 1     jakat
| 2     sadka
| 3     lillah
| 4     fitra

donation_request_types
------------------------
| id    name
-----------------------
| 1     widow
| 2     masjid
| 3     madresha

i want donation_request data with donation_types name and donation_request_types name
In my DonationRequest model code is as below

public function donation_types()
{
    return $this->belongsTo('App\DonationType','id','donation_type_id');
}

public function donation_request_types()
{
    return $this->belongsTo('App\DonationRequestType','id','donation_request_type_id');
}

but in first two row i get proper result but for third row has same donation_type_id as 3 so it give blank and same as in donation_request_type_id


问:
Jquery - How do I extract and calculate numeric values from string
I need some assistance with extracting and calculation numeric values from the the strings based on id assigned to span text tags. For example I need to calculate 5% discount and display correct amount in another field.

```<code>  <span id="discount">5% off<span>
    <span id="price">£2.75</span>/per month</span>

$( document ).ready(function() { {
    var discount= "#discount"; // a string
    discount= discount.replace(/\D/g, ''); // a string of only digits, or the empty string
    var discount= parseInt(discount, 10); // now it's a numeric value

    var price= "#price"; // a string
    price= price.replace(/\D/g, ''); // a string of only digits, or the empty string
    var discount= parseInt(price, 10); // now it's a numeric value

    var discountValue = (discount * price) / 100;
    var newPrice= price + discount;
    $("#price").text(newPrice);
})
</code>```

I am not an experet of Jquery and JavaScript thus please understand my limited knowledge and I do appreciate if someone could explain how to achieve expected solution.
Thanks

答:
Assuming your inputs (Price and Discount) are input based entries, you can extract the numbers from a string using provided Regex (assuming only 1 set of number is present at a time).</p>

```<code>$( document ).ready(function() {
    var discount= $("#discount").text(); // a string
    discount = Regex.Replace(discount, @"[^\d]", ""); // a string of only digits, or the empty string
    discount = parseInt(discount); // now it's a numeric value

    var price= $("#price").text(); // a string
    price = Regex.Replace(price, @"[^\d]", ""); // a string of only digits, or the empty string
    price = parseFloat(price); // now it's a numeric value

    var discountValue = (discount * price) / 100;
    var newPrice = price + discount;
    $("#price").text(newPrice);
})
</code>```

Body:
I need some assistance with extracting and calculation numeric values from the the strings based on id assigned to span text tags. For example I need to calculate 5% discount and display correct amount in another field.

  5% off
    £2.75/per month

$( document ).ready(function() { {
    var discount= "#discount"; // a string
    discount= discount.replace(/\D/g, ''); // a string of only digits, or the empty string
    var discount= parseInt(discount, 10); // now it's a numeric value

    var price= "#price"; // a string
    price= price.replace(/\D/g, ''); // a string of only digits, or the empty string
    var discount= parseInt(price, 10); // now it's a numeric value

    var discountValue = (discount * price) / 100;
    var newPrice= price + discount;
    $("#price").text(newPrice);
})

I am not an experet of Jquery and JavaScript thus please understand my limited knowledge and I do appreciate if someone could explain how to achieve expected solution.
Thanks

Body:
Assuming your inputs (Price and Discount) are input based entries, you can extract the numbers from a string using provided Regex (assuming only 1 set of number is present at a time).

$( document ).ready(function() {
    var discount= $("#discount").text(); // a string
    discount = Regex.Replace(discount, @"[^\d]", ""); // a string of only digits, or the empty string
    discount = parseInt(discount); // now it's a numeric value

    var price= $("#price").text(); // a string
    price = Regex.Replace(price, @"[^\d]", ""); // a string of only digits, or the empty string
    price = parseFloat(price); // now it's a numeric value

    var discountValue = (discount * price) / 100;
    var newPrice = price + discount;
    $("#price").text(newPrice);
})


问:
Gradle setup for project dependencies
I'm a Gradle beginner, yet I inherited a Java project that's using Gradle. That particular project depends on another Java project which is Ant build project on separate disk location.

In order for Gradle to build I have somehow to tell him there's another project which should be considered, but whatever I tried, I failed. This is my current project setup:

```<code>git Folder
|
|
---AntProject
             |
              -src
---GradleProject
                |
                |
                -proper Gradle file / folder structure
</code>```

Now, in my Gradle project in settings.gradle I added this:

```<code>include ':AntProject'
project(':AntProject').projectDir = file("C:\\<absolutePathToBeSure>\\git\\AntProject\\")
</code>```

In build.gradle I have added this:

```<code>dependencies {
    compile project(":AntProject")
}
</code>```

When I try doing "Gradle refresh" I'm getting error:

```<code>project declares a dependency from configuration 'compile' to configuration 'default' which is not declared in descriptor for project :AntProject
</code>```

What should I do?

Notes:

I tried using "\" instead of "\" inside settings.gradle, no help

I can't migrate AntProject to Gradle, move it to another location or influence it, that project is solely maintained by another dev.

答:
If the ant project is not Gradle (it doesn't own the build.gradle script) Gradle will not know what to do with it and adding it to settings.gradle will not help.

You can use ant library in Gradle to do what you wish to do, below are some docs how to use Ant in Gradle. I believe best is to not include it to not confuse Gradle and then create a custom task that will do what you need based on the directory $rootProject/antProject

The import_ant_build section looks promising

```<code>ant.importBuild 'build.xml'
</code>```

https://docs.gradle.org/current/userguide/ant.html

Title: Gradle setup for project dependencies

Body:
I'm a Gradle beginner, yet I inherited a Java project that's using Gradle. That particular project depends on another Java project which is Ant build project on separate disk location.

In order for Gradle to build I have somehow to tell him there's another project which should be considered, but whatever I tried, I failed. This is my current project setup:

git Folder
|
|
---AntProject
             |
              -src
---GradleProject
                |
                |
                -proper Gradle file / folder structure

Now, in my Gradle project in settings.gradle I added this:

include ':AntProject'
project(':AntProject').projectDir = file("C:\\<absolutePathToBeSure>\\git\\AntProject\\")

In build.gradle I have added this:

dependencies {
    compile project(":AntProject")
}

When I try doing "Gradle refresh" I'm getting error:

project declares a dependency from configuration 'compile' to configuration 'default' which is not declared in descriptor for project :AntProject

What should I do?

Notes:

I tried using "\" instead of "\" inside settings.gradle, no help

I can't migrate AntProject to Gradle, move it to another location or influence it, that project is solely maintained by another dev.

Body:
If the ant project is not Gradle (it doesn't own the build.gradle script) Gradle will not know what to do with it and adding it to settings.gradle will not help.

You can use ant library in Gradle to do what you wish to do, below are some docs how to use Ant in Gradle. I believe best is to not include it to not confuse Gradle and then create a custom task that will do what you need based on the directory $rootProject/antProject

The import_ant_build section looks promising

ant.importBuild 'build.xml'

https://docs.gradle.org/current/userguide/ant.html


问:
Is there a way to trigger a JavaScript onclick event on an element that has pointer-events set to none?
I have an element that has pointer events set to none, this is so hover styles for child elements don't show.

However when this element is clicked on I want to do something with JavaScript. Using an onclick event in JavaScript does not seem to work because pointer-events is set to none.

Is there a way around this so that I can have an element with no pointer events that can still trigger a JavaScript event?

```<code>[data-drawer="open"] {
  .site-drawer {
    transform: translateX(0);
    transition: all .2s ease;
  }

  .site-container {
    transform: translateX(-27.5rem);
    // Disabling pointer events disables styles hover styles on below elements
    // But also disables clicking on container to remove it.
    pointer-events: none;
    transition: all .2s ease;
    &:after {
      position: fixed;
      top: 0;
      right: 0;
      bottom: 0;
      left: 0;
      background: rgba(0,0,0,.75);
      content: "";
    }
  }
}
</code>```

JavaScript:

```<code>  this.siteContainer.addEventListener('click', (e) => {
    console.log('site container clicked');
    if(document.body.hasAttribute('data-drawer')) {
      document.body.removeAttribute('data-drawer');
    }
  });
</code>```

Cheers

答:
As I mentioned in the comments, you can achieve this by adding a non-clickable overlay on top of your content using pseudo-elements and z-index

Essentially you have four layers.

the content of the website (white)

the overlay that covers the content of the website while the modal
is open (grey)

the modal (red)

the layer that covers the modal contents. (transparent)

Result: user can't click inside the modal but can click outside anywhere on layer #2

Rough example:

.modal {
  position: fixed;
  top: 0;
  right: 0;
  bottom: 0;
  left: 0;
  opacity: 0;
  pointer-events: none;
  background: rgba(0, 0, 0, .5)
}

.close {
  top: 0;
  right: 0;
  bottom: 0;
  left: 0;
  opacity: 0;
  display: none;
  z-index: 1;
  position: fixed;
  cursor: default;
}

.modal-content:after {
  content: "";
  left: 0;
  position: absolute;
  top: 0;
  width: 100%;
  height: 100%;
  z-index: 2;
}

.modal:target {
  opacity: 1;
  pointer-events: auto;
}

.modal:target>.close {
  display: block;
}

.modal>div {
  width: 300px;
  text-align: center;
  padding: 40px;
  z-index: 2;
  position: relative;
  background: red;
}

.wrap,
.modal {
  display: flex;
  align-items: center;
  justify-content: center
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="wrap">
  <button>You can click me!</button>
  <div id="M" class="modal">
    <div class="modal-content">
      <button>But not me!</button>
    </div>

  </div>
</div></code>```

Body:
I have an element that has pointer events set to none, this is so hover styles for child elements don't show.

However when this element is clicked on I want to do something with JavaScript. Using an onclick event in JavaScript does not seem to work because pointer-events is set to none.

Is there a way around this so that I can have an element with no pointer events that can still trigger a JavaScript event?

[data-drawer="open"] {
  .site-drawer {
    transform: translateX(0);
    transition: all .2s ease;
  }

  .site-container {
    transform: translateX(-27.5rem);
    // Disabling pointer events disables styles hover styles on below elements
    // But also disables clicking on container to remove it.
    pointer-events: none;
    transition: all .2s ease;
    &:after {
      position: fixed;
      top: 0;
      right: 0;
      bottom: 0;
      left: 0;
      background: rgba(0,0,0,.75);
      content: "";
    }
  }
}

JavaScript:

  this.siteContainer.addEventListener('click', (e) => {
    console.log('site container clicked');
    if(document.body.hasAttribute('data-drawer')) {
      document.body.removeAttribute('data-drawer');
    }
  });

Cheers

Body:
As I mentioned in the comments, you can achieve this by adding a non-clickable overlay on top of your content using pseudo-elements and z-index

Essentially you have four layers.

the content of the website (white)

the overlay that covers the content of the website while the modal
is open (grey)

the modal (red)

the layer that covers the modal contents. (transparent)

Result: user can't click inside the modal but can click outside anywhere on layer #2

Rough example:

.modal {
  position: fixed;
  top: 0;
  right: 0;
  bottom: 0;
  left: 0;
  opacity: 0;
  pointer-events: none;
  background: rgba(0, 0, 0, .5)
}

.close {
  top: 0;
  right: 0;
  bottom: 0;
  left: 0;
  opacity: 0;
  display: none;
  z-index: 1;
  position: fixed;
  cursor: default;
}

.modal-content:after {
  content: "";
  left: 0;
  position: absolute;
  top: 0;
  width: 100%;
  height: 100%;
  z-index: 2;
}

.modal:target {
  opacity: 1;
  pointer-events: auto;
}

.modal:target>.close {
  display: block;
}

.modal>div {
  width: 300px;
  text-align: center;
  padding: 40px;
  z-index: 2;
  position: relative;
  background: red;
}

.wrap,
.modal {
  display: flex;
  align-items: center;
  justify-content: center
}

<div class="wrap">
  <a href="#M"><button>You can click me!</button></a>
  <div id="M" class="modal">
    <div class="modal-content">
      <a href="#"><button>But not me!</button></a>
    </div>
    <a href="#" class="close"></a>
  </div>
</div>


问:
Add CSS gradient with javascript - bug in IE7
I am trying to add gradient on only .link.box.gradient but in ie7 it add on .link.box.gradient and .style.box.gradient

```<code><!DOCTYPE html>
<html lang="sv">
    <head>
    <title></title>
        <script src="http://ajax.microsoft.com/ajax/jQuery/jquery-1.4.4.min.js"></script>
        <script>
            jQuery(function ($) {
                $('head').append("<style>.link.box{height:100px;width:100px;}.link.box.gradient{filter:progid:DXImageTransform.Microsoft.gradient(startColorStr='#000000',EndColorStr='#ffffff');}</style>");
            });
        </script>
    </head>
    <body>
        <div class="style box gradient">Gradient (style-tag)</div>
        <div class="link box gradient">Gradient (link-tag)</div>
    </body>
</html>
</code>```

You can see here too, http://jsfiddle.net/Zhvpy/
One strange thing is when i move out .link.box{height:100px;width:100px;} from javascript as you can see here http://jsfiddle.net/Zhvpy/1 it seems to work, but I dont want to move out.

Why is it like this? How can I fix this bug?

Body:
I am trying to add gradient on only .link.box.gradient but in ie7 it add on .link.box.gradient and .style.box.gradient

<!DOCTYPE html>

    <title></title>

Gradient (style-tag)

Gradient (link-tag)

You can see here too, http://jsfiddle.net/Zhvpy/
One strange thing is when i move out .link.box{height:100px;width:100px;} from javascript as you can see here http://jsfiddle.net/Zhvpy/1 it seems to work, but I dont want to move out.

Why is it like this? How can I fix this bug?

Body:
removed original incorrect answer

EDIT 1

Odd - decided it might be the way older versions of IE handle certain elements (like <script />) so tried a non-jQuery solution.
Seems to work!

EDIT 2

Added this to your full script - outputs different results which are more in line with what IE8 outputs

function appendStyle(element, cssObj) {
    //$('#a').append($('<span/>').text(cssObjToText(cssObj)));
    if ($.browser.version == 7) {
        var head = document.getElementsByTagName('head')[0],
            style = document.createElement('style'),
            rules = document.createTextNode(cssObjToText(cssObj));

        style.type = 'text/css';

        head.appendChild(style);

        style.styleSheet.cssText = rules.nodeValue;
    }
    else {
        element.after('<style class="css-finalized">' + cssObjToText(cssObj) + '</style>');
    }
}


答:
I think you dont even need that, just a little bit beautifuler

Origin

$234 07-04

After add style

```<code><p style="font-size: 30px; font-weight: lighter; color: rgba(57, 152, 27, 0.97);"><sup style="font-size: 15px;">$</sup>234<sup style="font-size: 15px;">07-04</sup></p>
</code>```

Please use downbelow style, dont mix html and style, that's terrible

    .normal{
        font-size: 30px;
        font-weight: normal;
        color: rgba(57, 152, 27, 0.97);
    }
    .upper{
        font-weight: lighter;
        font-size: 15px;
    }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><p class="normal">
    <sup class="upper">$</sup>234<sup class="upper">07-04</sup>
</p></code>```

Title: Align text on the side and top of other text css

Body:
How can I achieve this using css?

This is what I've tried:

R$
    54.133
    48

Body:
I think you dont even need that, just a little bit beautifuler

Origin

$234 07-04

After add style

<p style="font-size: 30px; font-weight: lighter; color: rgba(57, 152, 27, 0.97);"><sup style="font-size: 15px;">$</sup>234<sup style="font-size: 15px;">07-04</sup></p>

Please use downbelow style, dont mix html and style, that's terrible

    .normal{
        font-size: 30px;
        font-weight: normal;
        color: rgba(57, 152, 27, 0.97);
    }
    .upper{
        font-weight: lighter;
        font-size: 15px;
    }

<p class="normal">
    <sup class="upper">$</sup>234<sup class="upper">07-04</sup>
</p>


问:
Update...Set...From...Where query is affecting all rows and not specific ones
The below query should only affect the row titled 'F0085'. However, it has affected all the rows. Setting the address to 'test' on every Job_No.

```<code>UPDATE TBTest.dbo.Site
SET Address ='FDAN'
FROM Jobs
WHERE Job_No = 'F0085'
</code>```

This is the first table:

答:
Thank you all. I needed to find the common column (the ID column).

```<code>UPDATE t
SET
t.Address = 'FDAN'
FROM
TBTest.dbo.Site t
INNER JOIN Jobs j
ON t.Site_ID = j.Job_ID
WHERE j.Job_No = 'F0085'
</code>```

I don't fully understand how the aliases work. But it appears to be working fine.

Body:
The below query should only affect the row titled 'F0085'. However, it has affected all the rows. Setting the address to 'test' on every Job_No.

UPDATE TBTest.dbo.Site
SET Address ='FDAN'
FROM Jobs
WHERE Job_No = 'F0085'

This is the first table:

Body:
Thank you all. I needed to find the common column (the ID column).

UPDATE t
SET
t.Address = 'FDAN'
FROM
TBTest.dbo.Site t
INNER JOIN Jobs j
ON t.Site_ID = j.Job_ID
WHERE j.Job_No = 'F0085'

I don't fully understand how the aliases work. But it appears to be working fine.


问:
Is an undefined ng-bind more expensive than an ng-bind and ng-show?
Supposing toShowVar us undefined, which is more expensive?

```<code><span ng-bind="toShowVar" ng-show="toShowVar"></span>
</code>```

or

```<code><span ng-bind="toShowVar"></span>
</code>```

The latter would obviously not print anything on the screen if the variable is undefined.

Body:
Supposing toShowVar us undefined, which is more expensive?

or

The latter would obviously not print anything on the screen if the variable is undefined.

Body:
<span ng-bind="toShowVar" ng-show="toShowVar"></span> seems to be more expensive.because toShowVar will be bound to span even if there is nothing in that.If we use ng-if="toShowVar" , that will be little expensive, since the angular not include this span element to DOM.So giving them in decreasing order

<span ng-bind="toShowVar" ng-show="toShowVar"></span>

<span ng-bind="toShowVar"></span>

<span ng-bind="toShowVar" ng-if="toShowVar"></span>


问:
Using a panel as filter
As an initial note, I don't expect the code for this part of my software, but what I need, and would appreciate, it is a starting point and some ideas.

I have a panel like this:
https://drive.google.com/file/d/0B98UpTa2n4XbZUFuclhDbG9pV1k/view?usp=sharing

I need to use this panel as a date filter (connected with a Data Base). So, in one edge I will have a starting date and the other an ending date. The user must be able to interact with this panel to select the "gap" of dates that he/she would like to apply as a filter to a plotting graph.

Again, I don't expect the code for this part of my tool. I am just kind of lost in how should I start coding, also, I did not find anything specific about this online.

Thank you,

答:
You should use a DateTimePicker control on both sides of the panel (dtpFrom and dtpTo) then use the values to add to a query executed against the database.

On the ValueChange events for both the dtpFrom and toDate, you could validate that the fromDate is less than the toDate and vice versa, then call a function that executes the query and returns the results, or just filters results already in an existing dataset.

Title: Using a panel as filter