问:
Running a Python script from a Spring @Service
I need to execute a python script with arguments passed from my user interface and display the results. I know how to do this using ProcessBuilder (below) but I presume that just calling this code from the relevant Spring @Service isn't a good idea (threading issues, too many instances running concurrently, etc). What would be the best approach?

```<code>@Override
public String executeLatestAlgorithm(String json) {

    try {
        ProcessBuilder probuilder = new ProcessBuilder("somescript.py", json);
        Process p = probuilder.start();
        BufferedReader in = new BufferedReader(new InputStreamReader(p.getInputStream()));
        return in.readLine();
    } catch (IOException e) {
        e.printStackTrace();
    }
    return null;
}
</code>```

(crap code without any significant errorhandling - just to illustrate)

Many thanks,

A

答:
Apparently Spring Integration provides support to execute scripts written in Python, JS, Groovy etc.

https://github.com/spring-projects/spring-integration-samples/tree/master/applications/cafe-scripted

Part of the Python related config XML looks as follows

```<code><service-activator input-channel="hotDrinks"
    output-channel="preparedDrinks">
    <script:script lang="python" location="file:scripts/python/barista.py">
        <script:variable name="timeToPrepare" value="5" />
    </script:script>
</service-activator>
</code>```

Body:
I need to execute a python script with arguments passed from my user interface and display the results. I know how to do this using ProcessBuilder (below) but I presume that just calling this code from the relevant Spring @Service isn't a good idea (threading issues, too many instances running concurrently, etc). What would be the best approach?

@Override
public String executeLatestAlgorithm(String json) {

    try {
        ProcessBuilder probuilder = new ProcessBuilder("somescript.py", json);
        Process p = probuilder.start();
        BufferedReader in = new BufferedReader(new InputStreamReader(p.getInputStream()));
        return in.readLine();
    } catch (IOException e) {
        e.printStackTrace();
    }
    return null;
}

(crap code without any significant errorhandling - just to illustrate)

Many thanks,

A

Body:
Apparently Spring Integration provides support to execute scripts written in Python, JS, Groovy etc.

https://github.com/spring-projects/spring-integration-samples/tree/master/applications/cafe-scripted

Part of the Python related config XML looks as follows

<service-activator input-channel="hotDrinks"
    output-channel="preparedDrinks">
    <script:script lang="python" location="file:scripts/python/barista.py">
        <script:variable name="timeToPrepare" value="5" />
    </script:script>
</service-activator>


来源: stackexchange

问:
How to open a html file?
I have been trying to open a htmlfile on clicking help button.   And i need to import the file to source package so after build it wont show errors. I am using netbeans.  When i copied the file to src and tried running the file it showed error in compiling.  I want to know how to add the file to src and how to open by asking the user with a list of browsers installed in the system. Here is the code i have searched and tried..Thanks in advance

```<code>  try
  {
      File htmlFile = new File(this.getClass().getResource("help.html").getFile());
      Desktop.getDesktop().browse(htmlFile.toURI());
  }
  catch (IOException ex)
  {
      System.out.println(ex);
  }
</code>```

答:
I tried with My Desktop html file. now its working fine.
It will be useful for You.(my default browser is chrome)

Try it.

```<code>import java.awt.BorderLayout;
import java.awt.Button;
import java.awt.Desktop;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;

import javax.swing.JFrame;
import javax.swing.JPanel;

public class FileOpenBrowser {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        JFrame frame = new JFrame("FileOpenBrowser"); // set API Name
        JPanel topPanel = new JPanel(new FlowLayout()); // set Panel Layout

        File urlDesktop = new File(
                "C://Documents and Settings/Hariharan/Desktop/help.html");

        Button btn = new Button("Help");
        btn.setBounds(50, 100, 60, 30);
        topPanel.add(btn);

        frame.add(topPanel, BorderLayout.PAGE_START);

        frame.setSize(300, 300);
        frame.setVisible(true);
        frame.setLocationRelativeTo(null);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        btn.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                try {
                    Desktop.getDesktop().open(urlDesktop);
                } catch (Exception e1) {
                    e1.printStackTrace();
                }
            }
        });
    }
}
</code>```

ContentLicense: CC BY-SA 3.0

Title: How to open a html file?

Body:
I have been trying to open a htmlfile on clicking help button.   And i need to import the file to source package so after build it wont show errors. I am using netbeans.  When i copied the file to src and tried running the file it showed error in compiling.  I want to know how to add the file to src and how to open by asking the user with a list of browsers installed in the system. Here is the code i have searched and tried..Thanks in advance

  try
  {
      File htmlFile = new File(this.getClass().getResource("help.html").getFile());
      Desktop.getDesktop().browse(htmlFile.toURI());
  }
  catch (IOException ex)
  {
      System.out.println(ex);
  }

Body:
I tried with My Desktop html file. now its working fine.
It will be useful for You.(my default browser is chrome)

Try it.

import java.awt.BorderLayout;
import java.awt.Button;
import java.awt.Desktop;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;

import javax.swing.JFrame;
import javax.swing.JPanel;

public class FileOpenBrowser {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        JFrame frame = new JFrame("FileOpenBrowser"); // set API Name
        JPanel topPanel = new JPanel(new FlowLayout()); // set Panel Layout

        File urlDesktop = new File(
                "C://Documents and Settings/Hariharan/Desktop/help.html");

        Button btn = new Button("Help");
        btn.setBounds(50, 100, 60, 30);
        topPanel.add(btn);

        frame.add(topPanel, BorderLayout.PAGE_START);

        frame.setSize(300, 300);
        frame.setVisible(true);
        frame.setLocationRelativeTo(null);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        btn.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                try {
                    Desktop.getDesktop().open(urlDesktop);
                } catch (Exception e1) {
                    e1.printStackTrace();
                }
            }
        });
    }
}


问:
Header is not allowing  to align in the same line
I have a css header that is not allowing me to align a text in the same line using . I imagine there is a weird default to the header that doesnt allow me to do this how do i prevent the default or what else can i use instead?

HTML

```<code>h3>Size:</h3>
<?php echo "<span class='sP'>".$pSize ."</span><br>"?>
</code>```

CSS

```<code>h3{
margin-top: 0;
margin-bottom: 0;
color: #7C7C7C;
font-size: 20px;
font-weight: bold;
text-align: left;
font-family: "Lucida Sans Typewriter", "Lucida Console", monaco, "Bitstream Vera Sans Mono", monospace;
}

.sP{
color: #7C7C7C;
font-family: "Lucida Sans Typewriter", "Lucida Console", monaco, "Bitstream Vera Sans Mono", monospace;

}
</code>```

答:
Heading elements (h1-h6) are block level elements so that's why you specifically need to set them display: inline-block in order to display something next to them.

h1 { display: inline-block }
span { display: inline-block }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><h1>Hello, i'm a big fat heading</h1>
<span>Look at me, i'm a little 'ol span</span></code>```

Title: Header is not allowing <span> to align in the same line

Body:
I have a css header that is not allowing me to align a text in the same line using . I imagine there is a weird default to the header that doesnt allow me to do this how do i prevent the default or what else can i use instead?

HTML

h3>Size:

<?php echo "".$pSize ."
"?>

CSS

h3{
margin-top: 0;
margin-bottom: 0;
color: #7C7C7C;
font-size: 20px;
font-weight: bold;
text-align: left;
font-family: "Lucida Sans Typewriter", "Lucida Console", monaco, "Bitstream Vera Sans Mono", monospace;
}

.sP{
color: #7C7C7C;
font-family: "Lucida Sans Typewriter", "Lucida Console", monaco, "Bitstream Vera Sans Mono", monospace;

}

Body:
Heading elements (h1-h6) are block level elements so that's why you specifically need to set them display: inline-block in order to display something next to them.

h1 { display: inline-block }
span { display: inline-block }

<h1>Hello, i'm a big fat heading</h1>
<span>Look at me, i'm a little 'ol span</span>


问:
JS - How to add a button into a div with appendChid
I want to create a sidebar using only JavaScript, but I can't add the close button to the div.
I tried this:

```<code>var sideb = document.createElement("Div");
    sideb.style.height = "100%";
    sideb.style.width = "0px";
    sideb.style.backgroundColor = "rgb(30,30,30)";
    sideb.style.top = "0px";
    sideb.style.right = "0px";
    sideb.style.margin = "0px";
    sideb.style.padding = "0px";
    sideb.style.position = "fixed"

    document.body.appendChild(sideb);

var close = document.createElement("Button");
    close.innerText = "close";
    close.onclick = close;

    document.body.sideb.appendChild(close)
</code>```

But it's not working.

答:
document.body.sideb in this form mean that you call a property called sideb , there is no sideb in your body object so just use sideb.appendChild()</p>

```<code>var sideb = document.createElement("Div");
sideb.style.height = "100%";
sideb.style.width = "0px";
sideb.style.backgroundColor = "rgb(30,30,30)";                 sideb.style.top = "0px";
sideb.style.right = "0px";
sideb.style.margin = "0px";
sideb.style.padding = "0px";
sideb.style.position = "fixed"
document.getElementByTagName('body')[0].appendChild(sideb);
var close = document.createElement("Button");
close.innerText = "close";
close.onclick = close;
sideb.appendChild(close)
</code>```

Body:
I want to create a sidebar using only JavaScript, but I can't add the close button to the div.
I tried this:

var sideb = document.createElement("Div");
    sideb.style.height = "100%";
    sideb.style.width = "0px";
    sideb.style.backgroundColor = "rgb(30,30,30)";
    sideb.style.top = "0px";
    sideb.style.right = "0px";
    sideb.style.margin = "0px";
    sideb.style.padding = "0px";
    sideb.style.position = "fixed"

    document.body.appendChild(sideb);

var close = document.createElement("Button");
    close.innerText = "close";
    close.onclick = close;

    document.body.sideb.appendChild(close)

But it's not working.

Body:
document.body.sideb in this form mean that you call a property called sideb , there is no sideb in your body object so just use sideb.appendChild()

var sideb = document.createElement("Div");
sideb.style.height = "100%";
sideb.style.width = "0px";
sideb.style.backgroundColor = "rgb(30,30,30)";                 sideb.style.top = "0px";
sideb.style.right = "0px";
sideb.style.margin = "0px";
sideb.style.padding = "0px";
sideb.style.position = "fixed"
document.getElementByTagName('body')[0].appendChild(sideb);
var close = document.createElement("Button");
close.innerText = "close";
close.onclick = close;
sideb.appendChild(close)


问:
Jquery next() and removeClass()

if you look in picture aboive. what i want to do is when i click the row, it hides away, the next row become red and click that would hide that away and next becomes available and so on.

$(document).ready(function() {

  $('.start').unbind("click").click(function() {
    $(this).removeClass("start");
    $(this).hide();
    $(this).next().addClass("start");
  });

});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.start {
  color: red;
  border: 2px solid red;
}</code>```

 1

2

3

4

5

```

The first row hide away fine on click. The class "start" gets added to next row. But clicking on that does not work.

How I can remove the red row by clicking and next becomes available.

Thank you in advance

答:
Use a delegate.

$('div.siblings ul').on('click','li.start',function(){
    $(this).removeClass('start').hide().next().addClass('start');
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.start {
    color:red;
    border: 2px solid red;
}</code>```

 1

2

3

4

5

```

Title: Jquery next() and removeClass()

Body:
if you look in picture aboive. what i want to do is when i click the row, it hides away, the next row become red and click that would hide that away and next becomes available and so on.

$(document).ready(function() {

  $('.start').unbind("click").click(function() {
    $(this).removeClass("start");
    $(this).hide();
    $(this).next().addClass("start");
  });

});

.start {
  color: red;
  border: 2px solid red;
}

 1

2

3

4

5

The first row hide away fine on click. The class "start" gets added to next row. But clicking on that does not work.

How I can remove the red row by clicking and next becomes available.

Thank you in advance

Body:
Use a delegate.

$('div.siblings ul').on('click','li.start',function(){
    $(this).removeClass('start').hide().next().addClass('start');
});

.start {
    color:red;
    border: 2px solid red;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<div style="width:500px;" class="siblings">
 <ul>
   <li class="start"> 1</li>
   <li>2</li>
   <li>3</li>
   <li>4</li>
   <li>5</li>
</ul>
</div>


问:
Java & MySQL: Store an Read a 365 position of bitarray. HOW?
I am currently working with Java and MySQL, and I found an issue I don't know how to solve.

I have a class that stores a String of 365 positions that represents a Binary String "010111010010100...", and I would like to be able to store and read that field from the database.
Once it is read, I will perform an AND Logic operation with another bitarray.

I read about the BitSet class, that allows the logical operators (AND, OR, XOR, ...) between them. I tried it, but I didn't like the solutions I got. I could also try to transform the String to a byte array, and then store and read it from the database, in order to later perform the logic AND operation, but not sure if I would need to always create a BitSet, and how performant could it be.

I don't know which is the most performant way to do what I want:

Convert the Binary String in another element.

Store that element in the database (in the case of BitSet I tried to define the Database field as BLOB, but I had a lot of issues transforming the BitSet to BLOB and reading the BLOB to a BitSet).

Read the element from the database (at this point would be great to directly work with the element without making any cast or transformation).

Perform a logic AND with another bitarray and get the result.

I have tried a lot of options, but they didn't work.

Could someone help me with this problem and how to better approach it from the performance point of view?

Thanks!

答:
Storing bit in a string is bit weird, I used long to store a number, and make bitwise operations on that. It won't work for you, since you use much more bits. If it can remain string, maybe you can write a short function to make the AND operator on each byte of the string, somehow like this:

```<code>for (int i = 0; i<366; i++) {
    data .= (stringname[i] == binarystring[i]?"1":"0");
}
</code>```

Go through your string, while checking if it equals binary string (The one you want to AND it), if they equal, concat 1, if not, concat 0;

Body:
Storing bit in a string is bit weird, I used long to store a number, and make bitwise operations on that. It won't work for you, since you use much more bits. If it can remain string, maybe you can write a short function to make the AND operator on each byte of the string, somehow like this:

for (int i = 0; i<366; i++) {
    data .= (stringname[i] == binarystring[i]?"1":"0");
}

Go through your string, while checking if it equals binary string (The one you want to AND it), if they equal, concat 1, if not, concat 0;


问:
Java and Python Together in Single Google App Engine Project
I currently have a Java application running on Google App Engine, but I want to add the features that the Python module's SearchableModel provides (for search features of course).  Is it possible to run python code in the same project as Java code, just under a different version?  If not, could they be two separate apps (current Java app and a new Python-based search app) running against a single datastore, but I don't think that is possible.</p>

答:
Yes, you can write your app in Java and also have a separate version of your app running Python.

However, if the core of your app is already implemented in Java, you might want to look at the SearchableModel Python code, then consider implementing something to accomplish your goal in Java.  The gist is that you could simply build your list of search-words and store them in a multivalued property (ie a list).

You should also check out the Building Scalable, Complex Apps on App Engine video.  Depending on your use-case, moving the search-word list to an 'Index Relation Entity' might offer further improvements.

ContentLicense: CC BY-SA 2.5


问:
Extracting the int from a byte retrieved from a lock in device
I'm trying to get the time constant from a lock in device, I use this code:

```<code>self.ser.write("OFLT?\r\n".encode())
self.ser.write("++read\r\n".encode())
print (self.ser.readline())
</code>```

which prints b'9\n'. I want only the 9 from this, but I can't seem to get it out. I have tried:

```<code>a = self.ser.readline()
print (type(a))
print ("a is: " + a.decode())
</code>```

which results in

```<code><class 'bytes'>
a is:
</code>```

Only giving me a blank space. I tried to separately run this code as

```<code>a = b'9\n'
print ("a is " + a.decode())
</code>```

Which does print

```<code>a is 9
</code>```

答:
I'm guessing your full code looks like this:

```<code>...
print (self.ser.readline())
a = self.ser.readline()
...
</code>```

It seems to be that ser is a file object, so once you've printed out that line, the pointer advances to the next line and you can't read it again.

Try removing that print statement. Also, if you want to remove the trailing newline, you can use a.decode().rstrip().

Body:
I'm trying to get the time constant from a lock in device, I use this code:

self.ser.write("OFLT?\r\n".encode())
self.ser.write("++read\r\n".encode())
print (self.ser.readline())

which prints b'9\n'. I want only the 9 from this, but I can't seem to get it out. I have tried:

a = self.ser.readline()
print (type(a))
print ("a is: " + a.decode())

which results in

<class 'bytes'>
a is:

Only giving me a blank space. I tried to separately run this code as

a = b'9\n'
print ("a is " + a.decode())

Which does print

a is 9

Body:
I'm guessing your full code looks like this:

...
print (self.ser.readline())
a = self.ser.readline()
...

It seems to be that ser is a file object, so once you've printed out that line, the pointer advances to the next line and you can't read it again.

Try removing that print statement. Also, if you want to remove the trailing newline, you can use a.decode().rstrip().


问:
How to fix the last element of LineLayout that it does not go beyond the boundaries of the screen?
I try make layout with two TextView and one Linear Layout:

```<code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="horizontal" android:layout_width="match_parent"
    android:layout_height="match_parent">
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:background="@android:color/holo_orange_dark"
        android:text="testsdddddddddddddddddddddddddddasdsdfsdfsdf"/>
    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="@android:color/holo_red_dark"
        android:maxLines="1"
        android:text="NOT HIDE TEXT"/>
</LinearLayout>
</code>```

But when the first element has many characters second text is hidding.

But I want to do so:

And when first text is short (or second element may not fill all aviliable area):

How i can do it? May be i need use RelativeLayout?
Big thanks for your answers!)

答:
Use a tableLayout and inside that tableRow.Align one view to parent left and other to layout_alignParentRight. If the value of first view is blank the second view will be aligned to left. And if not it will be aligned to the right of first view.</p>

```<code> <TableLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_marginTop="3dp"
                android:shrinkColumns="0">

                <TableRow
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:gravity="center_vertical">

                    <TextView
                        android:id="@+id/tv_description"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:layout_alignParentLeft="true"
                        android:layout_marginLeft="15dp"
                        android:layout_marginTop="1dp"
                        android:layout_toLeftOf="@+id/tv_read"
                        android:ellipsize="end"
                        android:singleLine="true"
                        android:textColor="@android:color/white"
                        android:textSize="15dp"
                        android:visibility="visible" />

                    <TextView
                        android:id="@+id/tv_read"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:layout_alignParentRight="true"
                        android:layout_alignTop="@+id/tv_description"
                        android:layout_marginLeft="15dp"
                        android:layout_marginRight="20dp"
                        android:paddingRight="5dp"
                        android:textColor="@android:color/white"
                        android:textSize="15dp"
                        android:visibility="visible" />
                </TableRow>

            </TableLayout>
</code>```

Body:
I try make layout with two TextView and one Linear Layout:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="horizontal" android:layout_width="match_parent"
    android:layout_height="match_parent">
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:background="@android:color/holo_orange_dark"
        android:text="testsdddddddddddddddddddddddddddasdsdfsdfsdf"/>
    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="@android:color/holo_red_dark"
        android:maxLines="1"
        android:text="NOT HIDE TEXT"/>
</LinearLayout>

But when the first element has many characters second text is hidding.

But I want to do so:

And when first text is short (or second element may not fill all aviliable area):

How i can do it? May be i need use RelativeLayout?
Big thanks for your answers!)

Body:
Use a tableLayout and inside that tableRow.Align one view to parent left and other to layout_alignParentRight. If the value of first view is blank the second view will be aligned to left. And if not it will be aligned to the right of first view.

 <TableLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_marginTop="3dp"
                android:shrinkColumns="0">

                <TableRow
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:gravity="center_vertical">

                    <TextView
                        android:id="@+id/tv_description"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:layout_alignParentLeft="true"
                        android:layout_marginLeft="15dp"
                        android:layout_marginTop="1dp"
                        android:layout_toLeftOf="@+id/tv_read"
                        android:ellipsize="end"
                        android:singleLine="true"
                        android:textColor="@android:color/white"
                        android:textSize="15dp"
                        android:visibility="visible" />

                    <TextView
                        android:id="@+id/tv_read"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:layout_alignParentRight="true"
                        android:layout_alignTop="@+id/tv_description"
                        android:layout_marginLeft="15dp"
                        android:layout_marginRight="20dp"
                        android:paddingRight="5dp"
                        android:textColor="@android:color/white"
                        android:textSize="15dp"
                        android:visibility="visible" />
                </TableRow>

            </TableLayout>


问:
Rake db:migrate error, table already exists
I accidentally create a migration which I did not need so I delete the file, and created a new migration now when I try to run rake db:migrate I keep getting this error. I am the using SQlite3 gem, and Ruby on Rails 4</p>

```<code>StandardError: An error has occurred, this and all later migrations canceled:
SQLite3::SQLException: table "categories" already exists: CREATE TABLE "categories" ("id" INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, "category_name" varchar, "created_at" datetime NOT NULL, "updated_at" datetime NO
T NULL) D:/muse/db/migrate/20150830113519_create_categories.rb:3:in `change'
D:in `migrate'
ActiveRecord::StatementInvalid: SQLite3::SQLException: table "categories" already exists: CREATE TABLE "categories" ("id" INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, "category_name" varchar, "created_at" datetime NO
T NULL, "updated_at" datetime NOT NULL)
D:/muse/db/migrate/20150830113519_create_categories.rb:3:in `change'
D:in `migrate'
SQLite3::SQLException: table "categories" already exists
D:/muse/db/migrate/20150830113519_create_categories.rb:3:in `change'
D:in `migrate'
Tasks: TOP => db:migrate
(See full trace by running task with --trace)
</code>```

答:
This is ocurried with me because I'm trying to do some samples in diferents branchs. So I do this and works:</p>

```<code>rake db:drop
rake db:reset or rake db:setup
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I accidentally create a migration which I did not need so I delete the file, and created a new migration now when I try to run rake db:migrate I keep getting this error. I am the using SQlite3 gem, and Ruby on Rails 4

StandardError: An error has occurred, this and all later migrations canceled:
SQLite3::SQLException: table "categories" already exists: CREATE TABLE "categories" ("id" INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, "category_name" varchar, "created_at" datetime NOT NULL, "updated_at" datetime NO
T NULL) D:/muse/db/migrate/20150830113519_create_categories.rb:3:in `change'
D:in `migrate'
ActiveRecord::StatementInvalid: SQLite3::SQLException: table "categories" already exists: CREATE TABLE "categories" ("id" INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, "category_name" varchar, "created_at" datetime NO
T NULL, "updated_at" datetime NOT NULL)
D:/muse/db/migrate/20150830113519_create_categories.rb:3:in `change'
D:in `migrate'
SQLite3::SQLException: table "categories" already exists
D:/muse/db/migrate/20150830113519_create_categories.rb:3:in `change'
D:in `migrate'
Tasks: TOP => db:migrate
(See full trace by running task with --trace)

Body:
This is ocurried with me because I'm trying to do some samples in diferents branchs. So I do this and works:

rake db:drop
rake db:reset or rake db:setup


问:
How to identify a country from a normalized phone number?
I have a list of international phone numbers and a List of Country calling codes.

I would like to identify the Country from the numbers but I can't find a fast and elegant way to do it.

Any idea? The only I got is to have an hardcoded check (Eg. "look at the first number, look at the second number: if it's X then check for the third number. If the second number is Y then the Country is Foo", etc.).
I'm using PHP and a DB (MySQL) for the lists, but I think that any pseudocode will help.

答: The hard-coded check can be turned into a decision tree generated automatically from the list of calling codes. Each node of the tree defines the 'current' character, the list of possible following characters (tree nodes) or a country in case it's a terminal node. The root node will be for the leading '+' sign.</p>


问:
How can I select the minimum price per item from my database?
I want to select minimum price per item from my MySQL database, but I'm not sure how to write the query.

Here is an example table.

```<code>  id |  price | quantity
    1|   $200 |      200
    2|  $1000 |       10
    3|     $5 |        1
</code>```

In this case the price/item for id 1 would be $1 (200/200), for id 2 it's $100 (1000/10), for id 3 it's $5 (5/1) and the query would return $1, because it is the minimum price/item.

So how can it be translated to SQL? I thought about:

```<code>SELECT MIN(price)/200 WHERE quantity=200
</code>```

but it only works with a hard coded quantity and I must write the quantity for each id and would be impossible with 1000+ different prices and quantities. So I would need something flexible with variables or something, like:

```<code>SELECT MIN(price)/quantity
</code>```

but that's not correct syntax. (or it just doesn't work for me)

What is the correct way to write it in MySQL?

答:
```<code>select min(Price/Quantity) from tbl
</code>```

tbl is the table where you have your Price and quantity Data. This will work

Body:
I want to select minimum price per item from my MySQL database, but I'm not sure how to write the query.

Here is an example table.

  id |  price | quantity
    1|   $200 |      200
    2|  $1000 |       10
    3|     $5 |        1

In this case the price/item for id 1 would be $1 (200/200), for id 2 it's $100 (1000/10), for id 3 it's $5 (5/1) and the query would return $1, because it is the minimum price/item.

So how can it be translated to SQL? I thought about:

SELECT MIN(price)/200 WHERE quantity=200

but it only works with a hard coded quantity and I must write the quantity for each id and would be impossible with 1000+ different prices and quantities. So I would need something flexible with variables or something, like:

SELECT MIN(price)/quantity

but that's not correct syntax. (or it just doesn't work for me)

What is the correct way to write it in MySQL?

Body:
select min(Price/Quantity) from tbl

tbl is the table where you have your Price and quantity Data. This will work


问:
Regex to split a String with 2 delimiters, 2 times
I'm trying to split a String that looks something like this -

"Tomorrow - Cloudy - -3/1 "

to

"Tomorrow", "Cloudy", "-3", "1"

I know how to do it in two takes, first string.split("-",3) then result[2].split("/") but is there a regex to do it in one line? I've tried"[-{3}/]" but it doesn't seem to work.

答:
You can add multiple delimiters by using the OR operator "|"

So in your case it would be:

```<code>    String s = "Tomorrow - Cloudy - -3/1 ";

    String[] splitResult = s.split(" - |/");

    for (String result : splitResult) {
        System.out.println(result.trim());
    }
</code>```

Results into:

Tomorrow

Cloudy

-3

1

Body:
You can add multiple delimiters by using the OR operator "|"

So in your case it would be:

    String s = "Tomorrow - Cloudy - -3/1 ";

    String[] splitResult = s.split(" - |/");

    for (String result : splitResult) {
        System.out.println(result.trim());
    }

Results into:

Tomorrow

Cloudy

-3

1


问:
PS-4 PHP package - Main folder classes are not able to access the sub folder classes - Namespace
I am learning to setup PHP package with PSR-4 autoload using composer. I have managed to set up the working package. But I can access the classes in the same directory but cannot access the sub folder classes from main folder class.

adding my src code link here https://github.com/nsatheesh87/PSR-4-PHP-Test

Kernel.php  from src directory trying to access the Http->Request.php class but only i can get Class cannot found error. Also I Checked the namespaces

答:
You miss parameter with create Kernel object
https://github.com/nsatheesh87/PSR-4-PHP-Test/blob/master/src/app.php#L14

This constructor require object of Request class
https://github.com/nsatheesh87/PSR-4-PHP-Test/blob/master/src/Kernel.php#L11


问:
C# String Comparison Ignore Case Sensitivity HTML Tags
I have to compare 2 strings that have HTML tags in them. I'd like to ignore the casing of the HTML tags themselves, but DO compare the casing of the other strings outside of HTML tags. Would like some help in coding this logic.
For example, I want to ignore the casing of the TD tags in the strings below.</p>

```<code>String1: "<td>this is case-sensitive</td>"

String2: "<TD>THIS is CASE-sensitive</TD>"
</code>```

答:
```<code> string str = "<td>This is case Sensitive</td>";
            str = Regex.Replace(str, "<.*?>", String.Empty);
            Console.Write(str);
</code>```

This Might Work for you

Body:
I have to compare 2 strings that have HTML tags in them. I'd like to ignore the casing of the HTML tags themselves, but DO compare the casing of the other strings outside of HTML tags. Would like some help in coding this logic.
For example, I want to ignore the casing of the TD tags in the strings below.

String1: "this is case-sensitive	"

String2: "THIS is CASE-sensitive	"

Body:
 string str = "<td>This is case Sensitive</td>";
            str = Regex.Replace(str, "<.*?>", String.Empty);
            Console.Write(str);

This Might Work for you


问:
mail-merge HTML from a database into MS Word
project: Using VB.NET to build a winforms database interface and work-automation app.

I am using this editor for the users to enter their text in the database interface environment that will both load/save/show them what they are working on in the form and also mail-merge into a Word document waiting for the content. I can do the first step and it works well, but how do I get MS Word to recognize HTML as formatting instead of just merging in tags and text all as text?

The tool has two relevant properties: one to get just the text (no markup, i.e. no HTML) and one to get the full markup with HTML. Both of these are in text format (which I use for easy storage in the Database).

ideas/directions I can think of:

1) use the clipboard. I can copy/paste the content straight from the editor window to Word and it works great! But loading from a database is significantly different, even when using the clipboard programatically. (maybe I don't understand how to use the clipboard tools)

2) maybe there is a library or class/function in Word that can understand the HTML as "mergable" content?

thanks!

:-Dan

答:
I ended up using the clipboard to set the text. Here is a code sample that I needed to answer this question.

```<code>Clipboard.SetText(Me._Object.Property, TextDataFormat.Rtf)
</code>```

I just didn't know how to tell the computer that the content was HTML or RTF etc. It turned out to be simple.

:-Dan

Body:
I ended up using the clipboard to set the text. Here is a code sample that I needed to answer this question.

Clipboard.SetText(Me._Object.Property, TextDataFormat.Rtf)

I just didn't know how to tell the computer that the content was HTML or RTF etc. It turned out to be simple.

:-Dan


问:
How to catch Subview events in the Controller?
BackboneJS app built with RequireJS modules.

A View has multiple instances of subView. Click events in a subView should run Controller methods.

Initialization order requires View module in Controller, so requiring Controller module in subView would create a circular dependency.

I would prefer to create Events to convey data to Controller. Considered two options:

View listens to subView events and fires own Events, listened by
Controller;

Have a third app-global object, subViews trigger
events on that object, Controller listenes on that object?

What is the best pattern here?

答:
Marionette has event bubbling in place. For example if a view triggers "some:event", you can listen it on collection view as "childview:some:event".

If you have really deep views structure, then "childview:...childview:some:event" starts to look really bad and then you might consider three options: manually bubble them, use global message bus like "backbone.radio" or passing down some entity to fire events on it.

I personally feel bad about global bus and prefer to have for each meaningful part of application something that would implement mediator/observer pattern. Basic implementation might be state model, created in controller (or router) and passed in all the views below - then any of them can change something in state or listen to changes.

Actually as Controllers were deprecated in Marionette 3, it might be a good idea to move all the controllers logic inside these state models. Unfortunately as Backbone community is on decline I can't find any good resources on the topic.


问:
Read content of a local file with chrome extension
I am developing an extension for the chrome browser.  I use the KangoExtensions framework. The extension is written in JavaScript. I want to read the content of a file, which is located on the local filesystem. What is the easiest way to implement this?</p>

答: If you already know the file's path in the filesystem you just need to add a permission to file://*in your manifest file and make a GET XMLHttpRequest to the url file://{filepath}.


问:
random() function same values in linux (while grof ing)
When I try to generate random values for various sorting algorithm to gprof them and compare the results, I noticed the random() function was creating same values within an instance and in same order. Is there a way to get rid of it?

Example I tried profiling bubble sort and so randomly created 10000 values and bubble sorted it, now again when I give 10000 values its generating same set of values as before and in the same order.

When I changed the value to 1000 the first 1000 values of previous test were exactly same as this case. I changed the range of values with different possibilities like only positive integers and both positive, negative integers. What is the reason random() function is generating same values? And is there a way to fix it?

答:
When you are using random you need to provide a seed otherwise you will always get the same result. A common seed to use is the current time.

As seen here: How to generate a random number in C?

```<code>#include <time.h>
#include <stdlib.h>

srand(time(NULL));   // should only be called once
int r = rand();      // returns a pseudo-random integer between 0 and RAND_MAX
</code>```

Body:
When you are using random you need to provide a seed otherwise you will always get the same result. A common seed to use is the current time.

As seen here: How to generate a random number in C?

#include <time.h>
#include <stdlib.h>

srand(time(NULL));   // should only be called once
int r = rand();      // returns a pseudo-random integer between 0 and RAND_MAX


问:
Getting list of network devices inside the Linux kernel
I've been looking through net/core/dev.c and other files to try to find out how to get the list of network devices that are currently configured and it's proving to be a little difficult to find.

The end goal is to be able to get network device statistics using dev_get_stats in dev.c, but I need to know the current interfaces so I can grab the net_device struct to pass in. I'm having to do this inside the kernel as I'm writing a module which adds in a new /proc/ entry which relates to some statistics from the current network devices so from what I can gather this must be done inside the kernel.

If someone could point me to how to get the interfaces it would be much appreciated.

答:
This ought to do the trick:</p>

```<code>#include <linux/netdevice.h>

struct net_device *dev;

read_lock(&dev_base_lock);

dev = first_net_device(&init_net);
while (dev) {
    printk(KERN_INFO "found [%s]\n", dev->name);
    dev = next_net_device(dev);
}

read_unlock(&dev_base_lock);
</code>```

Body:
This ought to do the trick:

#include <linux/netdevice.h>

struct net_device *dev;

read_lock(&dev_base_lock);

dev = first_net_device(&init_net);
while (dev) {
    printk(KERN_INFO "found [%s]\n", dev->name);
    dev = next_net_device(dev);
}

read_unlock(&dev_base_lock);


问:
Reset default styling of Select Dropdown
I'm creating a website and no matter what I do, I am unable to style select dropdown, when I'm looking at it on my mac. What can I do? Is there a script somewhere that reset the default styles?</p>

答:
This works for me:</p>

```<code>select {
    -webkit-appearance: none;
    -moz-appearance: none;
    appearance: none;
}

select::-ms-expand {
    display: none;
}
</code>```

Body:
This works for me:

select {
    -webkit-appearance: none;
    -moz-appearance: none;
    appearance: none;
}

select::-ms-expand {
    display: none;
}


问:
How to check a radio button based on some other value?
I have a bootstrap radio button which needs to get selected based on what value the user gives. Suppose the user enters 'male', male radio button should be selected. Consider the user enters the value in lower case.

    function check(){
    var val = document.getElementById("inp").value;
    if( val == "male"){
        //select male radio button
        }
    if(val == "female"){
         //select female radio button
        }
    }

    ```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>

    <div class="btn-group" data-toggle="buttons">
                  <p>Gender <span>*</span></p>
                  <label class="btn btn-default">
                    <input class="form-control input-sm" style="width: 0px;" value="M" type="radio" name="gender" />M</label>
                  <label class="btn btn-default">
                    <input class="form-control input-sm" style="width: 0px;" type="radio" value="F" name="gender" />F</label>

                </div><br><br>
    <input id="inp" type="text" onblur="check()"/>

    </code>```

答:
Try below snippets,

function check(){
    var val = document.getElementById("inp").value;

    var label_male_ = document.getElementById('male');
    var chk_male_ = document.getElementById('chk_male');

    var label_female_ = document.getElementById('female');
    var chk_female_ = document.getElementById('chk_female');
    // Set default.
    label_male_.className += 'btn btn-default';
    chk_male_.checked = false;
    // Set default.
    label_female_.className += 'btn btn-default';
    chk_female_.checked = false;
    if( val == "male"){
        //check male radio button
        label_male_.className += ' active';
        chk_male_.checked = true;
    }
    if(val == "female"){
        //check female radio button
        label_female_.className += ' active';
        chk_male_.checked = true;
    }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>

<div class="btn-group" data-toggle="buttons">
    <p>Gender <span>*</span></p>
    <label class="btn btn-default" id="male">
        <input class="form-control input-sm" style="width: 10px;" value="M" type="radio" name="gender" id="chk_male" />M
    </label>
    <label class="btn btn-default" id="female">
        <input class="form-control input-sm" type="radio" value="F" name="gender" id="chk_female" />F
    </label>
</div><br /><br />
<input id="inp" type="text" onblur="check()"/></code>```

Body:
I have a bootstrap radio button which needs to get selected based on what value the user gives. Suppose the user enters 'male', male radio button should be selected. Consider the user enters the value in lower case.

    function check(){
    var val = document.getElementById("inp").value;
    if( val == "male"){
        //select male radio button
        }
    if(val == "female"){
         //select female radio button
        }
    }

<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">

Gender *

                    <input class="form-control input-sm" style="width: 0px;" value="M" type="radio" name="gender" />M

                    <input class="form-control input-sm" style="width: 0px;" type="radio" value="F" name="gender" />F

    <input id="inp" type="text" onblur="check()"/>

Body:
Try below snippets,

function check(){
    var val = document.getElementById("inp").value;

    var label_male_ = document.getElementById('male');
    var chk_male_ = document.getElementById('chk_male');

    var label_female_ = document.getElementById('female');
    var chk_female_ = document.getElementById('chk_female');
    // Set default.
    label_male_.className += 'btn btn-default';
    chk_male_.checked = false;
    // Set default.
    label_female_.className += 'btn btn-default';
    chk_female_.checked = false;
    if( val == "male"){
        //check male radio button
        label_male_.className += ' active';
        chk_male_.checked = true;
    }
    if(val == "female"){
        //check female radio button
        label_female_.className += ' active';
        chk_male_.checked = true;
    }
}

<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>

<div class="btn-group" data-toggle="buttons">
    <p>Gender <span>*</span></p>
    <label class="btn btn-default" id="male">
        <input class="form-control input-sm" style="width: 10px;" value="M" type="radio" name="gender" id="chk_male" />M
    </label>
    <label class="btn btn-default" id="female">
        <input class="form-control input-sm" type="radio" value="F" name="gender" id="chk_female" />F
    </label>
</div><br /><br />
<input id="inp" type="text" onblur="check()"/>


问:
How to save multiple user details in user defaults?
I got a task to store multiple user details.

```<code>@IBOutlet weak var userName: UITextField!

@IBOutlet weak var email_id: UITextField!

@IBOutlet weak var password: UITextField!
</code>```

I know in user defaults we can store a value for a particular key and retrieve it but i would like to know how to save multiple values. like the key should be the email_id i have mentioned above and all the three fields should be its values, also i need to maintain all the details even if there is n number of users.

答:
1.You can store multiple values using tuples.

Rule:  A default object must be a property list—that is, an instance
  of (or for collections, a combination of instances of): NSData,
  NSString, NSNumber, NSDate, NSArray, or NSDictionary

If you want to store any other type of object, you should typically archive it to create an instance of NSData.

```<code>// you can create NSObject model to store into userdefaults
let users = [User(username: "user1", email: "user1@xxx.com", password: "******"), User(username: "user2", email: "user2@xxx.com", password: "******")]

var userDefaults = UserDefaults.standard
let encodedData: Data = NSKeyedArchiver.archivedData(withRootObject: teams)
userDefaults.set(encodedData, forKey: "users")
userDefaults.synchronize()
</code>```

Get data by unarchiving like below

```<code>let decodedUserDetail  = userDefaults.object(forKey: "users") as! Data
let decodedUsers= NSKeyedUnarchiver.unarchiveObject(with: decodedUserDetail) as! [Team]
print(decodedUsers)
</code>```

2.You can store multiple values using Array of objects.

```<code>let userDetails =
[
    "username" : "user1",
    "email": "user1@xxx.com",
    "password" : "******"
]
</code>```

before storing this get existing details

```<code>  let userDefault = NSUserDefaults.standardUserDefaults()

  var storedUserDetails = userDefault.objectForKey("userDetails") as?  [[String:AnyObject]]
  storedUserDetails.append(userDetails )

  userDefault.setObject(storedCredentials, forKey: "credentials")
  userDefault.synchronize()
</code>```

Body:
I got a task to store multiple user details.

@IBOutlet weak var userName: UITextField!

@IBOutlet weak var email_id: UITextField!

@IBOutlet weak var password: UITextField!

I know in user defaults we can store a value for a particular key and retrieve it but i would like to know how to save multiple values. like the key should be the email_id i have mentioned above and all the three fields should be its values, also i need to maintain all the details even if there is n number of users.

Body:
1.You can store multiple values using tuples.

Rule:  A default object must be a property list—that is, an instance
  of (or for collections, a combination of instances of): NSData,
  NSString, NSNumber, NSDate, NSArray, or NSDictionary

If you want to store any other type of object, you should typically archive it to create an instance of NSData.

// you can create NSObject model to store into userdefaults
let users = [User(username: "user1", email: "user1@xxx.com", password: "******"), User(username: "user2", email: "user2@xxx.com", password: "******")]

var userDefaults = UserDefaults.standard
let encodedData: Data = NSKeyedArchiver.archivedData(withRootObject: teams)
userDefaults.set(encodedData, forKey: "users")
userDefaults.synchronize()

Get data by unarchiving like below

let decodedUserDetail  = userDefaults.object(forKey: "users") as! Data
let decodedUsers= NSKeyedUnarchiver.unarchiveObject(with: decodedUserDetail) as! [Team]
print(decodedUsers)

2.You can store multiple values using Array of objects.

let userDetails =
[
    "username" : "user1",
    "email": "user1@xxx.com",
    "password" : "******"
]

before storing this get existing details

  let userDefault = NSUserDefaults.standardUserDefaults()

  var storedUserDetails = userDefault.objectForKey("userDetails") as?  [[String:AnyObject]]
  storedUserDetails.append(userDetails )

  userDefault.setObject(storedCredentials, forKey: "credentials")
  userDefault.synchronize()


问:
how can i write as one query to get count in mysql

I want to get the today count of users and yesterday's users count for that i want to write only one query how can i do that..?

these are my queries I want only one query:

```<code>SELECT COUNT(*) FROM visitors group by visited_date ORDER by visited_date DESC limit 1,1 as todayCount

SELECT COUNT(*) FROM visitors group by visited_date ORDER by visited_date DESC limit 1,0 as yesterdayCount
</code>```

My expected results or only 2 columns

```<code>todayCount yesterdayCount
     2          4
</code>```

答:
Try this:
$sqlToday = "Select COUNT(*) FROM menjava WHERE DATE(date_submitted)=CURRENT_DATE()";

$sqlYesterday = "Select COUNT(*) FROM menjava WHERE DATE(dc_created) = CURDATE() - INTERVAL 1 DAY";

Body:
I want to get the today count of users and yesterday's users count for that i want to write only one query how can i do that..?

these are my queries I want only one query:

SELECT COUNT(*) FROM visitors group by visited_date ORDER by visited_date DESC limit 1,1 as todayCount

SELECT COUNT(*) FROM visitors group by visited_date ORDER by visited_date DESC limit 1,0 as yesterdayCount

My expected results or only 2 columns

todayCount yesterdayCount
     2          4


问:
How do I push a new branch without pulling
So I've worked on new features and I realized that it would be too complicated to commit locally to master branch. Thus, I created a new branch as follows:

```<code>$ git stash branch project_0.2 stash@{0}
</code>```

The problem of course is that when I try to push the new branch to the server I get:

```<code>$ git push origin master
To https://svn.tudelft.nl/git/project.git
 ! [rejected]        master -> master (non-fast-forward)
error: failed to push some refs to 'https://svn.tudelft.nl/git/project.git'
hint: Updates were rejected because a pushed branch tip is behind its remote
hint: counterpart. Check out this branch and integrate the remote changes
hint: (e.g. 'git pull ...') before pushing again.
hint: See the 'Note about fast-forwards' in 'git push --help' for details.
</code>```

I've been looking on the internet and everywhere I see that I should git pull and merge the changes. I tried this (before I made a backup), and I get:

```<code>$ git pull
remote: Counting objects: 1105, done.
remote: Compressing objects: 100% (304/304), done.
remote: Total 725 (delta 501), reused 552 (delta 382)
Receiving objects: 100% (725/725), 5.29 MiB | 0 bytes/s, done.
Resolving deltas: 100% (501/501), completed with 165 local objects.
From https://svn.3me.tudelft.nl/git/project
   5d6516c..fd424b5  master     -> origin/master
There is no tracking information for the current branch.
Please specify which branch you want to merge with.
See git-pull(1) for details.

    git pull <remote> <branch>

If you wish to set tracking information for this branch you can do so with:

    git branch --set-upstream-to=origin/<branch> project_0.2
</code>```

I'm not sure what I should do here so I stopped. Also, the changes are so deep that it will take me forever to merge. I thought there may be a smarter way to just push the branch to the server. In this way, I can get help from the other members of my team in fixing the code. Is this possible?

答:
Create new branch first using

```<code>git checkout -b NewBranchName
</code>```

It will create a new branch on your local machine, now push this new branch.

```<code>git push origin NewBranchName
</code>```

Body:
So I've worked on new features and I realized that it would be too complicated to commit locally to master branch. Thus, I created a new branch as follows:

$ git stash branch project_0.2 stash@{0}

The problem of course is that when I try to push the new branch to the server I get:

$ git push origin master
To https://svn.tudelft.nl/git/project.git
 ! [rejected]        master -> master (non-fast-forward)
error: failed to push some refs to 'https://svn.tudelft.nl/git/project.git'
hint: Updates were rejected because a pushed branch tip is behind its remote
hint: counterpart. Check out this branch and integrate the remote changes
hint: (e.g. 'git pull ...') before pushing again.
hint: See the 'Note about fast-forwards' in 'git push --help' for details.

I've been looking on the internet and everywhere I see that I should git pull and merge the changes. I tried this (before I made a backup), and I get:

$ git pull
remote: Counting objects: 1105, done.
remote: Compressing objects: 100% (304/304), done.
remote: Total 725 (delta 501), reused 552 (delta 382)
Receiving objects: 100% (725/725), 5.29 MiB | 0 bytes/s, done.
Resolving deltas: 100% (501/501), completed with 165 local objects.
From https://svn.3me.tudelft.nl/git/project
   5d6516c..fd424b5  master     -> origin/master
There is no tracking information for the current branch.
Please specify which branch you want to merge with.
See git-pull(1) for details.

    git pull <remote> <branch>

If you wish to set tracking information for this branch you can do so with:

    git branch --set-upstream-to=origin/<branch> project_0.2

I'm not sure what I should do here so I stopped. Also, the changes are so deep that it will take me forever to merge. I thought there may be a smarter way to just push the branch to the server. In this way, I can get help from the other members of my team in fixing the code. Is this possible?

Body:
Create new branch first using

git checkout -b NewBranchName

It will create a new branch on your local machine, now push this new branch.

git push origin NewBranchName


问:
Overwriting Symfony 3.3 container services in controller tests
I have a series of tests for controllers that rely on 3rd-party APIs that need to be mocked out in the test environment. We override the functional test client crawler and mock out the dependencies we need to test with. The key here is that the mocks change on every test.

In Symfony 3.2 this worked fine but in Symfony 3.3 I have a number of deprecation warnings due to the way the services are now injected:

An example controller test case:

```<code>class MyControllerTest extends WebTestCase
{
    private static $kernelModifier = null;

    public function setKernelModifier(\Closure $kernelModifier)
    {
        self::$kernelModifier = $kernelModifier;
        $this->ensureKernelShutdown();
    }

    protected static function createClient(array $options = [], array $server = [])
    {
        static::bootKernel($options);

        if ($kernelModifier = self::$kernelModifier) {
            $kernelModifier->__invoke();
            self::$kernelModifier = null;
        };

        $client = static::$kernel->getContainer()->get('test.client');
        $client->setServerParameters($server);

        return $client;
    }

    protected function getPropertyClient()
    {
        $mockService = (new PropertyMock())->getPropertyMock();
        $this->setKernelModifier(function () use ($mockService) {
            static::$kernel->getContainer()->set('app.property_service', $mockService);
        });
        return static::createClient();
    }

    protected function getPropertyFailureClient()
    {
        $mockService = (new PropertyMock())->getPropertyFailureMock();
        $this->setKernelModifier(function () use ($mockService) {
            static::$kernel->getContainer()->set('app.property_service', $mockService);
        });
        return static::createClient();
    }
}
</code>```

The actual test:

```<code>public function testInvalidPropertyRequest()
{
    $client = $this->getPropertyClient();
    $client->request(
        'POST',
        '/webhook/property',
        [],
        [],
        [],
        ''
    );
    $this->assertEquals(400, $client->getResponse()->getStatusCode());
}
</code>```

The deprecation error:

Setting the "app.property_service" pre-defined service is
  deprecated since Symfony 3.3 and won't be supported anymore in Symfony
  4.0: 3x

I've been through the 3.3 release documentation, BC breaks and deprecations and can't figure out how I would go about replacing container services with mocks after they've been configured.

Any help is appreciated.

答:
I'm also facing this issue and there's no hint within the Container class on how to handle this deprecation.

// for all interested, there's a current issue open on github - but no real solution other than either have a lot more bootstrapping code for your unit tests or moving to test the controllers in isolation.
I'd recommend to have all controllers defined as services with fixed/defined dependiencies and no direct DIC usage.

Body:
I have a series of tests for controllers that rely on 3rd-party APIs that need to be mocked out in the test environment. We override the functional test client crawler and mock out the dependencies we need to test with. The key here is that the mocks change on every test.

In Symfony 3.2 this worked fine but in Symfony 3.3 I have a number of deprecation warnings due to the way the services are now injected:

An example controller test case:

class MyControllerTest extends WebTestCase
{
    private static $kernelModifier = null;

    public function setKernelModifier(\Closure $kernelModifier)
    {
        self::$kernelModifier = $kernelModifier;
        $this->ensureKernelShutdown();
    }

    protected static function createClient(array $options = [], array $server = [])
    {
        static::bootKernel($options);

        if ($kernelModifier = self::$kernelModifier) {
            $kernelModifier->__invoke();
            self::$kernelModifier = null;
        };

        $client = static::$kernel->getContainer()->get('test.client');
        $client->setServerParameters($server);

        return $client;
    }

    protected function getPropertyClient()
    {
        $mockService = (new PropertyMock())->getPropertyMock();
        $this->setKernelModifier(function () use ($mockService) {
            static::$kernel->getContainer()->set('app.property_service', $mockService);
        });
        return static::createClient();
    }

    protected function getPropertyFailureClient()
    {
        $mockService = (new PropertyMock())->getPropertyFailureMock();
        $this->setKernelModifier(function () use ($mockService) {
            static::$kernel->getContainer()->set('app.property_service', $mockService);
        });
        return static::createClient();
    }
}

The actual test:

public function testInvalidPropertyRequest()
{
    $client = $this->getPropertyClient();
    $client->request(
        'POST',
        '/webhook/property',
        [],
        [],
        [],
        ''
    );
    $this->assertEquals(400, $client->getResponse()->getStatusCode());
}

The deprecation error:

Setting the "app.property_service" pre-defined service is
  deprecated since Symfony 3.3 and won't be supported anymore in Symfony
  4.0: 3x

I've been through the 3.3 release documentation, BC breaks and deprecations and can't figure out how I would go about replacing container services with mocks after they've been configured.

Any help is appreciated.


问:
Docker: limit VPN to single container
My docker host has multiple network cards, though the same network

- Card1: 192.168.0.50

- Card2: 192.168.0.55

I am connecting to a VPN from container 1 but not from container 2.

Once VPN is connected on container 1 both containers have the new IP.

Is there a way to limit VPN to only single container and not affect the other ?

答: I was using --net host on the container which caused this issue, as the VPN was now active on host and all containers affected. OpenVPN just on a container without net host works perfectly fine.</p>

Title: Docker: limit VPN to single container


问:
Handle timeout with Alamofire
Is it possible to add timeout handler for Alamofire request?

In my project I use Alamofire this way:

```<code>init() {
    let configuration = NSURLSessionConfiguration.defaultSessionConfiguration()
    configuration.timeoutIntervalForRequest = 30

    self.alamofireManager = Alamofire.Manager(configuration: configuration)
}

func requestAuthorizationWithEmail(email:NSString, password:NSString, completion: (result: RequestResult) -> Void) {

    self.alamofireManager!.request(.POST, "myURL", parameters:["email": email, "password":password])
        .responseJSON { response in
            switch response.result {
            case .Success(let JSON):
                //do json stuff
            case .Failure(let error):
                print("\n\nAuth request failed with error:\n \(error)")
                completion(result: .ConnectionFailed)
            }
    }
}
</code>```

EDIT:

request fail message

Error Domain=NSURLErrorDomain Code=-1001 "The request timed out." UserInfo={NSUnderlyingError=0x7fc10b937320 {Error Domain=kCFErrorDomainCFNetwork Code=-1001 "(null)" UserInfo={_kCFStreamErrorCodeKey=-2102, _kCFStreamErrorDomainKey=4}}, NSErrorFailingURLStringKey=url, NSErrorFailingURLKey=url, _kCFStreamErrorDomainKey=4, _kCFStreamErrorCodeKey=-2102, NSLocalizedDescription=The request timed out.}

答:
Swift 3, Alamofire 4.5.0

I wanted to set the same timeout for every HTTP call in my project.

The key idea is to declare the Alamofire Session Manager as a global variable. Then to create a URLSessionConfiguration variable, set its timeout in seconds and assign it to the manager.

Every call in the project can use this configured session manager.

In my case the global Alamofire Session Manager variable was set in AppDelegate file (globally) and its configuration was managed in its didFinishLaunchingWithOptions method

AppDelegate.swift

```<code>import UIKit

var AFManager = SessionManager()

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

    var window: UIWindow?

    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {

        let configuration = URLSessionConfiguration.default
        configuration.timeoutIntervalForRequest = 4 // seconds
        configuration.timeoutIntervalForResource = 4 //seconds
        AFManager = Alamofire.SessionManager(configuration: configuration)

        return true
    }
    ...
}
</code>```

From now the Alamofire request function can be called from any part of the app using the afManager.

For example:

```<code>AFManager.request("yourURL", method: .post, parameters: parameters, encoding: JSONEncoding.default).validate().responseJSON { response in
    ...
}
</code>```

Title: Handle timeout with Alamofire

Body:
Is it possible to add timeout handler for Alamofire request?

In my project I use Alamofire this way:

init() {
    let configuration = NSURLSessionConfiguration.defaultSessionConfiguration()
    configuration.timeoutIntervalForRequest = 30

    self.alamofireManager = Alamofire.Manager(configuration: configuration)
}

func requestAuthorizationWithEmail(email:NSString, password:NSString, completion: (result: RequestResult) -> Void) {

    self.alamofireManager!.request(.POST, "myURL", parameters:["email": email, "password":password])
        .responseJSON { response in
            switch response.result {
            case .Success(let JSON):
                //do json stuff
            case .Failure(let error):
                print("\n\nAuth request failed with error:\n \(error)")
                completion(result: .ConnectionFailed)
            }
    }
}

EDIT:

request fail message

Error Domain=NSURLErrorDomain Code=-1001 "The request timed out." UserInfo={NSUnderlyingError=0x7fc10b937320 {Error Domain=kCFErrorDomainCFNetwork Code=-1001 "(null)" UserInfo={_kCFStreamErrorCodeKey=-2102, _kCFStreamErrorDomainKey=4}}, NSErrorFailingURLStringKey=url, NSErrorFailingURLKey=url, _kCFStreamErrorDomainKey=4, _kCFStreamErrorCodeKey=-2102, NSLocalizedDescription=The request timed out.}

Body:
Swift 3, Alamofire 4.5.0

I wanted to set the same timeout for every HTTP call in my project.

The key idea is to declare the Alamofire Session Manager as a global variable. Then to create a URLSessionConfiguration variable, set its timeout in seconds and assign it to the manager.

Every call in the project can use this configured session manager.

In my case the global Alamofire Session Manager variable was set in AppDelegate file (globally) and its configuration was managed in its didFinishLaunchingWithOptions method

AppDelegate.swift

import UIKit

var AFManager = SessionManager()

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

    var window: UIWindow?

    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {

        let configuration = URLSessionConfiguration.default
        configuration.timeoutIntervalForRequest = 4 // seconds
        configuration.timeoutIntervalForResource = 4 //seconds
        AFManager = Alamofire.SessionManager(configuration: configuration)

        return true
    }
    ...
}

From now the Alamofire request function can be called from any part of the app using the afManager.

For example:

AFManager.request("yourURL", method: .post, parameters: parameters, encoding: JSONEncoding.default).validate().responseJSON { response in
    ...
}


问:
jQuery AJAX or XHR request trigger fail callbacks from done callback
Is there a way in my done handler of a jQuery XHR (created from a $.get() call) to look for problems in the response and then trigger the registered subsequent handlers (lie fail & always) with a custom error message?

something like this:

```<code>$.get( URL )
.done(
    function (data, status, res) {
    if(/*some condition*/){
            this.Reject(res, status, "some reason");
            return
        }
    //Do stuff on success
    }
)

.fail(
//Common error handler here
)
.always(
    //common always handler here
);
</code>```

Kind of a secondary filter on done.  The reason is of course all the APIs that shove an error in a 200 response that jQuery could never know was an error.

答:
Thanks for this question, and Chris's answer.

I tried this and it worked, except it was triggering the fail function for an implicit unexpected exception (caused by a bug), not for my test AJAX exception. Which made me thought, it might work for an explicit exception without the hassle of creating a new promise object. So I though I would try an explicit throw - and it worked.

This explicit throwing works in jQuery 3. I'm not sure about earlier versions. I tried doing this in a done handler and it didn't work: throwing only seems to work in a then handler

```<code>$.get( URL )
.then(
    function (data, status, res) {
        if(/**some error check**/({
             throw "error message";
        }

        return data; //this is also important
    }
)
.done(
    function (data, status, res) {
        //Do stuff on success
    }
)

.fail(
//Common error handler here
)
.always(
    //common always handler here
);
</code>```

Body:
Is there a way in my done handler of a jQuery XHR (created from a $.get() call) to look for problems in the response and then trigger the registered subsequent handlers (lie fail & always) with a custom error message?

something like this:

$.get( URL )
.done(
    function (data, status, res) {
    if(/*some condition*/){
            this.Reject(res, status, "some reason");
            return
        }
    //Do stuff on success
    }
)

.fail(
//Common error handler here
)
.always(
    //common always handler here
);

Kind of a secondary filter on done.  The reason is of course all the APIs that shove an error in a 200 response that jQuery could never know was an error.

Body:
Thanks for this question, and Chris's answer.

I tried this and it worked, except it was triggering the fail function for an implicit unexpected exception (caused by a bug), not for my test AJAX exception. Which made me thought, it might work for an explicit exception without the hassle of creating a new promise object. So I though I would try an explicit throw - and it worked.

This explicit throwing works in jQuery 3. I'm not sure about earlier versions. I tried doing this in a done handler and it didn't work: throwing only seems to work in a then handler

$.get( URL )
.then(
    function (data, status, res) {
        if(/**some error check**/({
             throw "error message";
        }

        return data; //this is also important
    }
)
.done(
    function (data, status, res) {
        //Do stuff on success
    }
)

.fail(
//Common error handler here
)
.always(
    //common always handler here
);


问:
How to limit the textview text height with 10 lines and then remaining text to scroll in Swift3
Here I have designed textview which will move up with keyboard and adjust its height depend on the text, in the textview there is no scrolling for textview, now I need textview  should limit with 10 lines then want scrolling.

Below is my code:

```<code>import UIKit

class ViewController: UIViewController, UITextFieldDelegate, UITextViewDelegate{

    @IBOutlet weak var msgTextViewheightConstraint: NSLayoutConstraint!
    @IBOutlet weak var msgTextView: UITextView!
    @IBOutlet weak var textViewBottomLayoutContraint: NSLayoutConstraint!

    var activeTextView: UITextView?

    override func viewDidLoad() {
        super.viewDidLoad()

        msgTextView.layer.cornerRadius = 5
        msgTextView.layer.borderColor = UIColor.gray.withAlphaComponent(0.5).cgColor
        msgTextView.layer.borderWidth = 0.5
        msgTextView.clipsToBounds = true
        self.setupTextView()
        self.registerForKeyboardNotifications()
    }

    func registerForKeyboardNotifications(){
        //Adding notifies on keyboard appearing
        NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShow(notification:)), name: NSNotification.Name.UIKeyboardWillShow, object: nil)
        NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillHide(notification:)), name: NSNotification.Name.UIKeyboardWillHide, object: nil)
    }
    func deregisterFromKeyboardNotifications(){
        //Removing notifies on keyboard appearing
        NotificationCenter.default.removeObserver(self, name: NSNotification.Name.UIKeyboardWillShow, object: nil)
        NotificationCenter.default.removeObserver(self, name: NSNotification.Name.UIKeyboardWillHide, object: nil)
    }

    func keyboardWillShow(notification: NSNotification) {
        if let keyboardSize = (notification.userInfo?[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue {
            self.textViewBottomLayoutContraint.constant = keyboardSize.size.height + 10

        }
    }

    func keyboardWillHide(notification: NSNotification) {
        if let keyboardSize = (notification.userInfo?[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue {
            self.textViewBottomLayoutContraint.constant = 10

        }
    }

    func textViewDidBeginEditing(_ textView: UITextView) {

        activeTextView = textView

    }
    func textViewDidEndEditing(_ textView: UITextView) {
        activeTextView = nil

    }
    private func textViewShouldReturn(_ textView: UITextView) -> Bool {
        textView.resignFirstResponder()
        return true
    }

    func setupTextView() {
        if let txtView = msgTextView {

            txtView.scrollsToTop = true
            txtView.isScrollEnabled = true

            txtView.addObserver(self, forKeyPath: "contentSize", options:[ NSKeyValueObservingOptions.old , NSKeyValueObservingOptions.new], context: nil)
        }
    }

    override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {

        if let changeDict = change, let constraint = msgTextViewheightConstraint, let view = self.msgTextView {
            if object as? NSObject == self.msgTextView && keyPath == "contentSize" {
                if let oldContentSize = (changeDict[NSKeyValueChangeKey.oldKey] as AnyObject).cgSizeValue,
                    let newContentSize = (changeDict[NSKeyValueChangeKey.newKey] as AnyObject).cgSizeValue {

                    let dy = newContentSize.height - oldContentSize.height
                    constraint.constant = constraint.constant + dy;
                    self.view.layoutIfNeeded()
                    let contentOffsetToShowLastLine = CGPoint(x: 0.0, y: view.contentSize.height - view.bounds.height)
                    view.contentOffset = contentOffsetToShowLastLine
                }
            }
        }
    }

    func textView(textView: UITextView, shouldChangeTextInRange range: NSRange, replacementText text: String) -> Bool {
        return true
    }

}
</code>```

Please help me in this concept.

答:
You can get the number of lines of text by dividing the hight of the textView's content by the textView's font's line hight:

```<code>let numberOfLines = textView.contentSize.height/(textView.font?.lineHeight)!
</code>```

You can then get the size of each line by dividing the textView.contentSize by the number of lines it contains:

```<code>let lineHeight = textView.contentSize.height / numberOfLines
</code>```

Then, in your viewDidAppear method, you can set the height constraint for the textView to the lineHeight times 10:

```<code>NSLayoutConstraint.activate([
    textView.heightAnchor.constraint(lessThanOrEqualToConstant: lineHeight * 10)
])
</code>```

Make sure that you are not setting a height constraint in your storyboard  if you do this.

Body:
Here I have designed textview which will move up with keyboard and adjust its height depend on the text, in the textview there is no scrolling for textview, now I need textview  should limit with 10 lines then want scrolling.

Below is my code:

import UIKit

class ViewController: UIViewController, UITextFieldDelegate, UITextViewDelegate{

    @IBOutlet weak var msgTextViewheightConstraint: NSLayoutConstraint!
    @IBOutlet weak var msgTextView: UITextView!
    @IBOutlet weak var textViewBottomLayoutContraint: NSLayoutConstraint!

    var activeTextView: UITextView?

    override func viewDidLoad() {
        super.viewDidLoad()

        msgTextView.layer.cornerRadius = 5
        msgTextView.layer.borderColor = UIColor.gray.withAlphaComponent(0.5).cgColor
        msgTextView.layer.borderWidth = 0.5
        msgTextView.clipsToBounds = true
        self.setupTextView()
        self.registerForKeyboardNotifications()
    }

    func registerForKeyboardNotifications(){
        //Adding notifies on keyboard appearing
        NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShow(notification:)), name: NSNotification.Name.UIKeyboardWillShow, object: nil)
        NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillHide(notification:)), name: NSNotification.Name.UIKeyboardWillHide, object: nil)
    }
    func deregisterFromKeyboardNotifications(){
        //Removing notifies on keyboard appearing
        NotificationCenter.default.removeObserver(self, name: NSNotification.Name.UIKeyboardWillShow, object: nil)
        NotificationCenter.default.removeObserver(self, name: NSNotification.Name.UIKeyboardWillHide, object: nil)
    }

    func keyboardWillShow(notification: NSNotification) {
        if let keyboardSize = (notification.userInfo?[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue {
            self.textViewBottomLayoutContraint.constant = keyboardSize.size.height + 10

        }
    }

    func keyboardWillHide(notification: NSNotification) {
        if let keyboardSize = (notification.userInfo?[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue {
            self.textViewBottomLayoutContraint.constant = 10

        }
    }

    func textViewDidBeginEditing(_ textView: UITextView) {

        activeTextView = textView

    }
    func textViewDidEndEditing(_ textView: UITextView) {
        activeTextView = nil

    }
    private func textViewShouldReturn(_ textView: UITextView) -> Bool {
        textView.resignFirstResponder()
        return true
    }

    func setupTextView() {
        if let txtView = msgTextView {

            txtView.scrollsToTop = true
            txtView.isScrollEnabled = true

            txtView.addObserver(self, forKeyPath: "contentSize", options:[ NSKeyValueObservingOptions.old , NSKeyValueObservingOptions.new], context: nil)
        }
    }

    override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {

        if let changeDict = change, let constraint = msgTextViewheightConstraint, let view = self.msgTextView {
            if object as? NSObject == self.msgTextView && keyPath == "contentSize" {
                if let oldContentSize = (changeDict[NSKeyValueChangeKey.oldKey] as AnyObject).cgSizeValue,
                    let newContentSize = (changeDict[NSKeyValueChangeKey.newKey] as AnyObject).cgSizeValue {

                    let dy = newContentSize.height - oldContentSize.height
                    constraint.constant = constraint.constant + dy;
                    self.view.layoutIfNeeded()
                    let contentOffsetToShowLastLine = CGPoint(x: 0.0, y: view.contentSize.height - view.bounds.height)
                    view.contentOffset = contentOffsetToShowLastLine
                }
            }
        }
    }

    func textView(textView: UITextView, shouldChangeTextInRange range: NSRange, replacementText text: String) -> Bool {
        return true
    }

}

Please help me in this concept.

Body:
You can get the number of lines of text by dividing the hight of the textView's content by the textView's font's line hight:

let numberOfLines = textView.contentSize.height/(textView.font?.lineHeight)!

You can then get the size of each line by dividing the textView.contentSize by the number of lines it contains:

let lineHeight = textView.contentSize.height / numberOfLines

Then, in your viewDidAppear method, you can set the height constraint for the textView to the lineHeight times 10:

NSLayoutConstraint.activate([
    textView.heightAnchor.constraint(lessThanOrEqualToConstant: lineHeight * 10)
])

Make sure that you are not setting a height constraint in your storyboard  if you do this.


问:
jQuery alert when row with specific attribute is clicked
I have html table like below:

```<code><table id='messagelist'>

  <tr id="rcmrowMTM" class="message selected" aria-selected="true">
    <td class="threads"><span class="threads"></span></td>
    <td class="subject" tabindex="0"><span class="fromto skip-on-drag"><span class="adr"><span title="test@example.com" class="rcmContactAddress">test@example.com</span></span>
      </span><span class="date skip-on-drag">Today 08:27</span><span class="subject"><span id="msgicnrcmrowMTM" class="msgicon status" title=""></span><a href="./?_task=mail&_mbox=INBOX&_uid=13&_action=show" onclick="return rcube_event.keyboard_only(event)"
      onmouseover="rcube_webmail.long_subject_title(this,1)" tabindex="-1"><span>test</span></a></span>
    </td>
    <td class="flags"><span class="flag"><span id="flagicnrcmrowMTM" class="unflagged" title="Not Flagged"></span></span><span class="attachment"><span class="attachment" title="With attachment"></span></span>
    </td>
  </tr>

  <tr id="rcmrowNw" class="message">
    <td class="threads"><span class="threads"></span></td>
    <td class="subject"><span class="fromto skip-on-drag"><span class="adr"><span title="test@example.com" class="rcmContactAddress">test@example.com</span></span>
      </span><span class="date skip-on-drag">Sun 12:22</span><span class="subject"><span id="msgicnrcmrowNw" class="msgicon status" title=""></span><a href="./?_task=mail&_mbox=INBOX&_uid=7&_action=show" onclick="return rcube_event.keyboard_only(event)"
      onmouseover="rcube_webmail.long_subject_title(this,1)" tabindex="-1"><span>test</span></a></span>
    </td>
    <td class="flags"><span class="flag"><span id="flagicnrcmrowNw" class="unflagged" title="Not Flagged"></span></span><span class="attachment"> </span></td>
  </tr>

</table>
</code>```

Every time user click a row new class "selected" is added in tr.

What I want is to show alert if user click on a row and row has title="With attachment" like in last td of first row

Here is my code that I tried but it's not working.

```<code>$('#messagelist tr.selected').on('click', function() {
  if ($(this).find("span[title|='With attachment']")) {
    alert('with attachment');
  }
});
</code>```

any help is appreciated. Thanks in advance.

JSFiddle

答:
Here you made mistake in your code

Your Code

```<code>$('#messagelist tr.selected').on('click', function() {
  if ($(this).find("span[title|='With attachment']")) {
    alert('with attachment');
  }
});
</code>```

Updated Code

```<code>$('.messagelist tr.selected').on('click', function() {
  if ($(this).find("span[title|='With attachment']")) {
    alert('with attachment');
  }
});
</code>```

messagelist is a class it's not a id So you should use .messagelist instead of #messagelist.

Hope this will helps you. :)

Body:
I have html table like below:

    test@example.com
      Today 08:27test

    test@example.com
      Sun 12:22test

Every time user click a row new class "selected" is added in tr.

What I want is to show alert if user click on a row and row has title="With attachment" like in last td of first row

Here is my code that I tried but it's not working.

$('#messagelist tr.selected').on('click', function() {
  if ($(this).find("span[title|='With attachment']")) {
    alert('with attachment');
  }
});

any help is appreciated. Thanks in advance.

JSFiddle

Body:
Here you made mistake in your code

Your Code

$('#messagelist tr.selected').on('click', function() {
  if ($(this).find("span[title|='With attachment']")) {
    alert('with attachment');
  }
});

Updated Code

$('.messagelist tr.selected').on('click', function() {
  if ($(this).find("span[title|='With attachment']")) {
    alert('with attachment');
  }
});

messagelist is a class it's not a id So you should use .messagelist instead of #messagelist.

Hope this will helps you. :)


问:
variable button vb.net
i declared a global variable button:

Dim button1 As New Button()

Now, i dont know how to add a click event in this button since it is a variable. Do you have any idea how do i do it?

答:
AddHandler button1.click, AddressOf MyClickEventHandler (MSDN Documentation)

You have to make sure MyClickEventHandler is defined with the same signature as any other Click event handler (i.e. Sub MyClickEventHandler(ByVal sender as Object, ByVal e as EventArgs))

OwnerDisplayName: sef

LastEditorDisplayName: lc

Title: variable button vb.net

OwnerDisplayName: lc


问:
In Django, is there a built in filter which can mark these as safe?
```<code>> <strong>
</code>```

HTML tags, and much more (these 3 are just examples)

Is there a filter that I actually render these in Django template, but keep tags escaped.

答: No, there isn't - if you mark something as safe, nothing will be escaped. If it's unsafe, everything will be. There isn't really way to say this content is varying degrees of safe - so if you want this, you'll have to write it yourself.

Body:
>

HTML tags, and much more (these 3 are just examples)

Is there a filter that I actually render these in Django template, but keep tags escaped.


问:
Custom landing page for SaaS application
I am building a SaaS based web application, to which users can connect using their own domain and apply their company branding to it.

How can I customize the landing page of my application based on domain from which it is being accessed. There is no login information to identify the customer.

Thanks.

答:
On your landing page, you can fetch request url and then customize the response accordingly.

You didn't mention the programming language, however in Java we can use ((HttpServletRequest)request).getRequestURL().toString() to get it.

Recently for one of my projects I used a third party service -  www.grooveui.com, it does something similar but without you having to write server side code.