问:
Why does module parse failed: /xxx/MyFont.ttf Unexpected character ''
I encountered this error

ERROR in ./src/style/MyFont.ttf Module parse failed: /xxx/MyFont.ttf
  Unexpected character '' (1:0) You may need an appropriate loader to
  handle this file type. (Source code omitted for this binary file)`
  when I import my custom font in my less file like this:

```<code>@font-face {
    font-family: "MyFont";
    src: url("./MyFont.ttf") format("truetype");
}
</code>```

my webpack config is as follow:

```<code>rules: [
  {
    test: /\.jsx?$/,
    exclude: /node_modules/,
    loader: 'babel-loader',
    query: babelQuery
  },{
    test: /\.css$/,
    use: [
      'style-loader',
      'css-loader'
    ]
  },
  {
    test: /\.less$/i,
    use: ExtractTextPlugin.extract([ 'css-loader', 'less-loader' ])
  },
  { test: /\.ttf(\?v=\d+\.\d+\.\d+)?$/, loader: "url?limit=10000&mimetype=application/octet-stream" },
]
</code>```

Anyone knows how to solve it?

答:
Add this to your rules array.

```<code>{
  test: /\.(png|jpe?g|gif|svg|woff|woff2|ttf|eot|ico)$/,
  loader: 'file-loader?name=assets/[name].[hash].[ext]'
}
</code>```

and you should install the file-loader using npm install.
Hope this will help you.

Body:
I encountered this error

ERROR in ./src/style/MyFont.ttf Module parse failed: /xxx/MyFont.ttf
  Unexpected character '' (1:0) You may need an appropriate loader to
  handle this file type. (Source code omitted for this binary file)`
  when I import my custom font in my less file like this:

@font-face {
    font-family: "MyFont";
    src: url("./MyFont.ttf") format("truetype");
}

my webpack config is as follow:

rules: [
  {
    test: /\.jsx?$/,
    exclude: /node_modules/,
    loader: 'babel-loader',
    query: babelQuery
  },{
    test: /\.css$/,
    use: [
      'style-loader',
      'css-loader'
    ]
  },
  {
    test: /\.less$/i,
    use: ExtractTextPlugin.extract([ 'css-loader', 'less-loader' ])
  },
  { test: /\.ttf(\?v=\d+\.\d+\.\d+)?$/, loader: "url?limit=10000&mimetype=application/octet-stream" },
]

Anyone knows how to solve it?

Body:
Add this to your rules array.

{
  test: /\.(png|jpe?g|gif|svg|woff|woff2|ttf|eot|ico)$/,
  loader: 'file-loader?name=assets/[name].[hash].[ext]'
}

and you should install the file-loader using npm install.
Hope this will help you.


来源: stackexchange

问:
Aspose.word :Add pdf attachment to word file
I am new to aspose.word  in .Net.

I have a template document where I need to replace text fields from a word document by the attachment.I have excel and pdf documents as attachments.

Can someday help me to add attachment to the word document?

Thanks,
Joy

答:
you can use InsertOleObject

try this :

```<code> doc = new Document();
    DocumentBuilder builder = new DocumentBuilder(doc);
    Stream memStream = File.OpenRead("addreess+file.xls");
    Shape oleObject = builder.InsertOleObject(memStream, "AcroExch.Document.7"", false, null);
</code>```

ContentLicense: CC BY-SA 3.0

Body:
you can use InsertOleObject

try this :

 doc = new Document();
    DocumentBuilder builder = new DocumentBuilder(doc);
    Stream memStream = File.OpenRead("addreess+file.xls");
    Shape oleObject = builder.InsertOleObject(memStream, "AcroExch.Document.7"", false, null);


问:
Python Pandas Error tokenizing data
I'm trying to use pandas to manipulate a .csv file but I get this error:

pandas.parser.CParserError: Error tokenizing data. C error: Expected 2 fields in line 3,  saw 12

I have tried to read the pandas docs, but found nothing.

My code is simple:

```<code>path = 'GOOG Key Ratios.csv'
#print(open(path).read())
data = pd.read_csv(path)
</code>```

How can I resolve this? Should I use the csv module or another language ?

File is from Morningstar

答:
Sometimes the problem is not how to use python, but with the raw data.

I got this error message

```<code>Error tokenizing data. C error: Expected 18 fields in line 72, saw 19.
</code>```

It turned out that in the column description there were sometimes commas.  This means that the CSV file needs to be cleaned up or another separator used.

Title: Python Pandas Error tokenizing data

Body:
I'm trying to use pandas to manipulate a .csv file but I get this error:

pandas.parser.CParserError: Error tokenizing data. C error: Expected 2 fields in line 3,  saw 12

I have tried to read the pandas docs, but found nothing.

My code is simple:

path = 'GOOG Key Ratios.csv'
#print(open(path).read())
data = pd.read_csv(path)

How can I resolve this? Should I use the csv module or another language ?

File is from Morningstar

Body:
Sometimes the problem is not how to use python, but with the raw data.

I got this error message

Error tokenizing data. C error: Expected 18 fields in line 72, saw 19.

It turned out that in the column description there were sometimes commas.  This means that the CSV file needs to be cleaned up or another separator used.


问:
how to set Linear layout child's height as tallest child height
I have four textviews in my Linear Layout and they have equal
width as follows,

```<code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="match_parent">
    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/textView86" />
    <LinearLayout
        android:orientation="horizontal"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">
        <TextView
            android:layout_width="0dp"
            android:layout_weight="0.25"
            android:layout_height="wrap_content" />
        <TextView
            android:layout_width="0dp"
            android:layout_weight="0.25"
            android:layout_height="wrap_content" />
        <TextView
            android:layout_width="0dp"
            android:layout_weight="0.25"
            android:layout_height="wrap_content" />
        <TextView
            android:layout_width="0dp"
            android:layout_weight="0.25"
            android:layout_height="wrap_content" />
    </LinearLayout>
</LinearLayout>
</code>```

My problem is, The textviews should be displayed with the same height.The content(text) for that textview will be set programmatically. I tried with Relative layout but the width of textview couldn't be same. I need both height and width should be same as tallest child.

Guide me please. Thanks!

答:
Use below layout :</p>

```<code><LinearLayout
    android:weightSum="1"
    android:background="@color/colorPrimaryDark"
    android:orientation="horizontal"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">
    <TextView
        android:background="@color/black_30"
        android:layout_width="0dp"
        android:layout_weight="0.25"
        android:layout_height="match_parent"
        />
    <TextView
        android:background="@color/com_facebook_blue"
        android:layout_width="0dp"
        android:layout_weight="0.25"
        android:layout_height="match_parent"
        />
    <TextView
        android:background="@color/tw__composer_red"
        android:layout_width="0dp"
        android:layout_weight="0.25"
        android:layout_height="match_parent"
        />
    <TextView
        android:background="@color/colorAccent"
        android:layout_width="0dp"
        android:layout_weight="0.25"
        android:layout_height="match_parent"
        />
</LinearLayout>
</code>```

Body:
I have four textviews in my Linear Layout and they have equal
width as follows,

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="match_parent">
    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/textView86" />
    <LinearLayout
        android:orientation="horizontal"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">
        <TextView
            android:layout_width="0dp"
            android:layout_weight="0.25"
            android:layout_height="wrap_content" />
        <TextView
            android:layout_width="0dp"
            android:layout_weight="0.25"
            android:layout_height="wrap_content" />
        <TextView
            android:layout_width="0dp"
            android:layout_weight="0.25"
            android:layout_height="wrap_content" />
        <TextView
            android:layout_width="0dp"
            android:layout_weight="0.25"
            android:layout_height="wrap_content" />
    </LinearLayout>
</LinearLayout>

My problem is, The textviews should be displayed with the same height.The content(text) for that textview will be set programmatically. I tried with Relative layout but the width of textview couldn't be same. I need both height and width should be same as tallest child.

Guide me please. Thanks!

Body:
Use below layout :

<LinearLayout
    android:weightSum="1"
    android:background="@color/colorPrimaryDark"
    android:orientation="horizontal"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">
    <TextView
        android:background="@color/black_30"
        android:layout_width="0dp"
        android:layout_weight="0.25"
        android:layout_height="match_parent"
        />
    <TextView
        android:background="@color/com_facebook_blue"
        android:layout_width="0dp"
        android:layout_weight="0.25"
        android:layout_height="match_parent"
        />
    <TextView
        android:background="@color/tw__composer_red"
        android:layout_width="0dp"
        android:layout_weight="0.25"
        android:layout_height="match_parent"
        />
    <TextView
        android:background="@color/colorAccent"
        android:layout_width="0dp"
        android:layout_weight="0.25"
        android:layout_height="match_parent"
        />
</LinearLayout>


问:
CSS position type change (absolute to relative) on child div causes odd effect on parent div. Why is that?
I'm trying to understand CSS positioning and I'm having trouble figuring out why a simple change that apparently should have no effect on the layout is causing a very disruptive change. I'm obviously missing something.

The initial objective was to place an inner div
 vertically and horizontally within another div. That was fairly simple:

```<code>html, body {
 margin:0;
 padding:0;
 height:100%;
}

div#container {
 position:relative;
 background:#4444ff;
 margin: 0 auto; /* center, not in IE5 */

 height:80%;
 min-height:80%;
}

div#childDiv {
 position:absolute;
 background:#ff5555;

 /* next we center it vertically and horizontally */
 width:900px;
 height:600px;
 top:50%;
 margin-top:-300px;
 left:50%;
 margin-left:-450px;
}
</code>```

...and in the HTML page I used:

```<code><body>
<div id=container>
 <div id=childDiv>
  test
    </div>
</div>

</body>
</code>```

which worked fine.

The curious part is what happens when I change the position attribute of the #childDiv div from absolute to relative.

My understanding is that first is should not affect the #container div at all since I'm changing only the position of the child element, and second that it should not change the layout since it is the only child element, its parent uses relative position and third I have not specified any offsets (tp, left, etc).

Instead, when I make this change, the parent #container is messed up (shows only up to the half of the viewport instead of 80% height as previously), and the position of #childDiv changes accordingly (also upwards, half outside the viewport).

My questions is: why does that happen? What concepts I'm not taking into account and why was the parent div affected by a change in the children's position setting?

If I remove #childDiv from within #container and place it inside body, then #container is no longer affected by that change so it seems something is propagating up in the DOM, which is odd to me. I've seen the same in firefox, opera, IE and chrome.

I have read W3C's spec on this topic but I haven't been able to figure this one out so far...

UPDATE: I created examples in JS fiddle to show the problem. You can see the original is here: jsfiddle.net/7Pr9y/1 and the affected one is here: jsfiddle.net/7Pr9y/3

Thank you!
Eduardo

答:
It looks like your CSS got complex quickly because as soon as you positioned the child div absolutely, your container div would have disappeared, and putting percentage-based widths and heights on it wouldn't work.

The reason for this is that once you position something absolutely, it's taken out of the document flow, so your container div is now acting as if it contains nothing.  If it contains nothing, unless you give it absolute dimensions (say, in pixels), you're saying "size yourself to a certain percentage of your container", which in this case, is the body element, which also acts as if it contains nothing.

When you start tossing heights and widths and min-heights on every element to compensate, especially when they are relative values, the results can become unpredictable very quickly.  My advice would be to check out this reference on the box model by Chris Coyier: http://css-tricks.com/the-css-box-model/

It's super straightforward and uses some great diagrams to help visualize the different aspects of CSS positioning.

ContentLicense: CC BY-SA 2.5

Body:
I'm trying to understand CSS positioning and I'm having trouble figuring out why a simple change that apparently should have no effect on the layout is causing a very disruptive change. I'm obviously missing something.

The initial objective was to place an inner div
 vertically and horizontally within another div. That was fairly simple:

html, body {
 margin:0;
 padding:0;
 height:100%;
}

div#container {
 position:relative;
 background:#4444ff;
 margin: 0 auto; /* center, not in IE5 */

 height:80%;
 min-height:80%;
}

div#childDiv {
 position:absolute;
 background:#ff5555;

 /* next we center it vertically and horizontally */
 width:900px;
 height:600px;
 top:50%;
 margin-top:-300px;
 left:50%;
 margin-left:-450px;
}

...and in the HTML page I used:

  test

which worked fine.

The curious part is what happens when I change the position attribute of the #childDiv div from absolute to relative.

My understanding is that first is should not affect the #container div at all since I'm changing only the position of the child element, and second that it should not change the layout since it is the only child element, its parent uses relative position and third I have not specified any offsets (tp, left, etc).

Instead, when I make this change, the parent #container is messed up (shows only up to the half of the viewport instead of 80% height as previously), and the position of #childDiv changes accordingly (also upwards, half outside the viewport).

My questions is: why does that happen? What concepts I'm not taking into account and why was the parent div affected by a change in the children's position setting?

If I remove #childDiv from within #container and place it inside body, then #container is no longer affected by that change so it seems something is propagating up in the DOM, which is odd to me. I've seen the same in firefox, opera, IE and chrome.

I have read W3C's spec on this topic but I haven't been able to figure this one out so far...

UPDATE: I created examples in JS fiddle to show the problem. You can see the original is here: jsfiddle.net/7Pr9y/1 and the affected one is here: jsfiddle.net/7Pr9y/3

Thank you!
Eduardo


问:
Odoo 10.0 - Don't round quantity
I'm using Odoo 10.0 Community Edition and I can't find where to configure to specify Odoo to do not round the quantity ordered.

For example, if the unit of an article is days, I would like to be able to set 1.5 days. But every time I try, Odoo automatically round the value to 2 (or to 1 if I put 1.4 days). I've tried on different products with different unit (days, hours, unit, etc.) but same result.

Could you please tell me where to configure this ?

Thanks

Arnaud

答:
That was simple but not obvious change the decimal accuracy for the Product Unit of Measure (dev mode needs to be activate) :
Settings > Technical > Database Structure > Decimal Accuracy >  Product Unit of Measure > decimal precision > Set the number you want (for example 1 if you want 1 decimal)</p>

Title: Odoo 10.0 - Don't round quantity


问:
Excel VBA ADO recordset issue with Null values
I'm pretty new at VBA and having an issue with ADO.

Currently the code im using returns fields (Name, Suburb, State) from a SQL database into a ListBox.
The code works fine as long as there are there all fields have a value, if there is a Null value it returns the error

Could not set the List property. Type mismatch

I need to find a way so if the Suburb and/or State fields return a Null value that it still populates the Listbox.

Any info would be greatly appreciated, thanks in advance!

Database entries

Screenshot of error

```<code>Dim cnn As ADODB.Connection
Dim rs As New ADODB.Recordset
Dim SQLquery As String
Dim cnnstr As String
Dim SQLName As String
Dim i As Integer

SQLName = "Salon"
SQLquery = "SELECT [Name], [Suburb], [State] FROM Salon WHERE Name like '" & SQLName & "%'"

Set cnn = New Connection
cnnstr = "Provider=SQLOLEDB; " & _
                "Data Source=localhost; " & _
                "Initial Catalog=MyDatabase;" & _
                "User ID=sa;" & _
                "Password=Password;" & _
                "Trusted_Connection=Yes;"

cnn.Open cnnstr
cnn.Execute SQLquery
rs.Open SQLquery, cnn, adOpenStatic

    rs.MoveFirst
    i = 0
    With Me.lb_search
        .Clear
        Do
            .AddItem
            .List(i, 0) = rs!Name
            .List(i, 1) = rs!Suburb
            .List(i, 2) = rs!State
            i = i + 1
            rs.MoveNext
        Loop Until rs.EOF
    End With

btn_search_test_Exit:
On Error Resume Next
rs.Close
cnn.Close
Set rs = Nothing
Set cnn = Nothing
</code>```

答:
nz is annoyingly not-available in Excel
Oh yes it is :-)

```<code>Public Function NZ(v As Variant, Optional valueifnull As Variant = 0) As Variant
If IsNull(v) Then
      NZ = valueifnull
Else
    NZ = v
End If
End Function
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I'm pretty new at VBA and having an issue with ADO.

Currently the code im using returns fields (Name, Suburb, State) from a SQL database into a ListBox.
The code works fine as long as there are there all fields have a value, if there is a Null value it returns the error

Could not set the List property. Type mismatch

I need to find a way so if the Suburb and/or State fields return a Null value that it still populates the Listbox.

Any info would be greatly appreciated, thanks in advance!

Database entries

Screenshot of error

Dim cnn As ADODB.Connection
Dim rs As New ADODB.Recordset
Dim SQLquery As String
Dim cnnstr As String
Dim SQLName As String
Dim i As Integer

SQLName = "Salon"
SQLquery = "SELECT [Name], [Suburb], [State] FROM Salon WHERE Name like '" & SQLName & "%'"

Set cnn = New Connection
cnnstr = "Provider=SQLOLEDB; " & _
                "Data Source=localhost; " & _
                "Initial Catalog=MyDatabase;" & _
                "User ID=sa;" & _
                "Password=Password;" & _
                "Trusted_Connection=Yes;"

cnn.Open cnnstr
cnn.Execute SQLquery
rs.Open SQLquery, cnn, adOpenStatic

    rs.MoveFirst
    i = 0
    With Me.lb_search
        .Clear
        Do
            .AddItem
            .List(i, 0) = rs!Name
            .List(i, 1) = rs!Suburb
            .List(i, 2) = rs!State
            i = i + 1
            rs.MoveNext
        Loop Until rs.EOF
    End With

btn_search_test_Exit:
On Error Resume Next
rs.Close
cnn.Close
Set rs = Nothing
Set cnn = Nothing

Body:
nz is annoyingly not-available in Excel
Oh yes it is :-)

Public Function NZ(v As Variant, Optional valueifnull As Variant = 0) As Variant
If IsNull(v) Then
      NZ = valueifnull
Else
    NZ = v
End If
End Function


问:
Help sending email usings the linux mail command in a perl CGI script
How can I send an html email using the linux command line inside of a perl CGI script.
I tried:</p>

```<code>system(echo $message | mail -s $subject $email);
</code>```

答:
Take a look at Net::SMTP.

From the documentation:

This module implements a client interface to the SMTP and ESMTP protocol, enabling a perl5 application to talk to SMTP servers.

...

This example sends a small message to the postmaster at the SMTP server known as mailhost:

```<code>#!/usr/local/bin/perl -w

use Net::SMTP;

$smtp = Net::SMTP->new('mailhost');

$smtp->mail($ENV{USER});
$smtp->to('postmaster');

$smtp->data();
$smtp->datasend("To: postmaster\n");
$smtp->datasend("\n");
$smtp->datasend("A simple test message\n");
$smtp->dataend();

$smtp->quit;
</code>```

Body:
How can I send an html email using the linux command line inside of a perl CGI script.
I tried:

system(echo $message | mail -s $subject $email);

Body:
Take a look at Net::SMTP.

From the documentation:

This module implements a client interface to the SMTP and ESMTP protocol, enabling a perl5 application to talk to SMTP servers.

...

This example sends a small message to the postmaster at the SMTP server known as mailhost:

#!/usr/local/bin/perl -w

use Net::SMTP;

$smtp = Net::SMTP->new('mailhost');

$smtp->mail($ENV{USER});
$smtp->to('postmaster');

$smtp->data();
$smtp->datasend("To: postmaster\n");
$smtp->datasend("\n");
$smtp->datasend("A simple test message\n");
$smtp->dataend();

$smtp->quit;


问:
JPA LocalDateTime comparison SQL
I have a Java project which contains an entity with a LocalDateTime. I want to extract records via SQL where the LocalDateTime falls in between 2 other LocalDateTime's.

ENTITY

```<code>@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(nullable = false)
private long id;

@Basic(optional = false)
@Column(nullable = false)
private long assignmentId;

@Basic(optional = false)
@Column(nullable = false)
private LocalDateTime startDateTime;

@Basic(optional = false)
@Column(nullable = false)
private LocalDateTime endDateTime;
</code>```

JAVA

```<code>//Sub assignments
public List<Subassignment> findAllSubassignmentsForAssignmentBetweenDates(long id, LocalDateTime startDateTime, LocalDateTime endDateTime) {
    return getEntityManager().createNamedQuery("ResourceVO.findByAssignmentIdAndDates", Subassignment.class)
            .setParameter("id", id)
            .setParameter("sdt", startDateTime)
            .setParameter("edt", endDateTime)
            .getResultList();
}
</code>```

QUERY

```<code><named-query name='ResourceVO.findByAssignmentIdAndDates'>
    <query>
        SELECT c FROM Subassignment AS c
        WHERE (c.assignmentId IN (SELECT b.id FROM Assignment b WHERE b.resource.id = :id))
        AND (c.startDateTime BETWEEN :sdt AND :edt)

    </query>
</named-query>
</code>```

I'm always getting an 'Internal Server Error'. Any tips or suggestions?

P.S. The query works fine without the LocalDateTime parameters.

Thanks

Matthijs

答: I changed LocalDateTime to long</p>

Title: JPA LocalDateTime comparison SQL

Body:
I have a Java project which contains an entity with a LocalDateTime. I want to extract records via SQL where the LocalDateTime falls in between 2 other LocalDateTime's.

ENTITY

@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(nullable = false)
private long id;

@Basic(optional = false)
@Column(nullable = false)
private long assignmentId;

@Basic(optional = false)
@Column(nullable = false)
private LocalDateTime startDateTime;

@Basic(optional = false)
@Column(nullable = false)
private LocalDateTime endDateTime;

JAVA

//Sub assignments
public List<Subassignment> findAllSubassignmentsForAssignmentBetweenDates(long id, LocalDateTime startDateTime, LocalDateTime endDateTime) {
    return getEntityManager().createNamedQuery("ResourceVO.findByAssignmentIdAndDates", Subassignment.class)
            .setParameter("id", id)
            .setParameter("sdt", startDateTime)
            .setParameter("edt", endDateTime)
            .getResultList();
}

QUERY

<named-query name='ResourceVO.findByAssignmentIdAndDates'>
    <query>
        SELECT c FROM Subassignment AS c
        WHERE (c.assignmentId IN (SELECT b.id FROM Assignment b WHERE b.resource.id = :id))
        AND (c.startDateTime BETWEEN :sdt AND :edt)

    </query>
</named-query>

I'm always getting an 'Internal Server Error'. Any tips or suggestions?

P.S. The query works fine without the LocalDateTime parameters.

Thanks

Matthijs

Body: I changed LocalDateTime to long


问:
How to specify Image type in Google Custom Search
I am using Google Custom Search to get images with some criteria.

I am initiating HTTP Get requests from java application to call the Google Custom Search API
 (Please note I am NOT using javascript or css and I am NOT developing web site).

I am able to get the images, and the program is working. the application brings  images which has Jpg extension.

I want to :

bring ONLY the images which has png extension AND has transparent background.

I tried to specify the filetype in the query string of the request URL like this

```<code>https://www.googleapis.com/customsearch/v1?q=cars&filetype=png&cx=[myinformatino]&searchType=image&rights=cc_publicdomain&num=10&key=[myKey]
</code>```

but the result is really still in jpg and the Google Custom search brings only one or two result.

Notes

I configured the Google Custom Search (from its Control panel) to search all the web, I am not restricting it to search some sites.

I configured the Google Custom Search to enable the Image Searching (also from Control panel) like this

I also configured the search result to the ImageResult (from the Search Features -> Advanced page) as the following picture

I also founded this code examples from google documentation which restrict the type of the Image but they seems to be in javascripts (NOT in java) which not suitable for me at all.

UPDATE
I found a solution for searching for png files, the solution was by providing the filetype:png in the query itself instead of specify this value as query string to the Google Custom Search. and The result is reasonable and acceptable.

UPDATE
I also tried the tbs query string parameter which is used in the Google Image search which worked as the following if we want to get the transparent images

```<code>?tbs=ic:trans&
</code>```

this works only for Google Image Search, But it did not work in the Google Custom Search. Even when I used the hq parameter for the Google Custom Search which just add the parameter as it is to the url to add the tbs parameter.

BUT I Still can not fore the Google Custom Search to bring the Images which has the transparent background only.

UPDATE

if there is a way to achieve the same goal (bringing the images with transparent background) using Bing Search API, I will also accept the answer.
I tried also the Bing Search API, It worked also, but the same problem appeared, there is no way to specify that I need a images with transparent background.

UPDATE
according to this discussion
there is undocumented parameter in the Google deprecated search api which do bring the transparent images, which as the following

```<code>imgc=trans
</code>```

this is working for the old deprecated google search api, but it does not work for the new API and it does not worked also for the BING api.

UPDATE
For Bing Search API I tried to add this query parameter which speicyf the transparent background in the BING image search (in the website not in the API) to the URL

```<code>qft=+filterui:photo-transparent
</code>```

although this is working for the Normal BING search, it did not work for the BING Search API.

答:
How about putting "transparent" at the end of query string? It worked for me: &q="<brand>+logo+transparent"
and for filetype &filetype=png

Body:
I am using Google Custom Search to get images with some criteria.

I am initiating HTTP Get requests from java application to call the Google Custom Search API
 (Please note I am NOT using javascript or css and I am NOT developing web site).

I am able to get the images, and the program is working. the application brings  images which has Jpg extension.

I want to :

bring ONLY the images which has png extension AND has transparent background.

I tried to specify the filetype in the query string of the request URL like this

https://www.googleapis.com/customsearch/v1?q=cars&filetype=png&cx=[myinformatino]&searchType=image&rights=cc_publicdomain&num=10&key=[myKey]

but the result is really still in jpg and the Google Custom search brings only one or two result.

Notes

I configured the Google Custom Search (from its Control panel) to search all the web, I am not restricting it to search some sites.

I configured the Google Custom Search to enable the Image Searching (also from Control panel) like this

I also configured the search result to the ImageResult (from the Search Features -> Advanced page) as the following picture

I also founded this code examples from google documentation which restrict the type of the Image but they seems to be in javascripts (NOT in java) which not suitable for me at all.

UPDATE
I found a solution for searching for png files, the solution was by providing the filetype:png in the query itself instead of specify this value as query string to the Google Custom Search. and The result is reasonable and acceptable.

UPDATE
I also tried the tbs query string parameter which is used in the Google Image search which worked as the following if we want to get the transparent images

?tbs=ic:trans&

this works only for Google Image Search, But it did not work in the Google Custom Search. Even when I used the hq parameter for the Google Custom Search which just add the parameter as it is to the url to add the tbs parameter.

BUT I Still can not fore the Google Custom Search to bring the Images which has the transparent background only.

UPDATE

if there is a way to achieve the same goal (bringing the images with transparent background) using Bing Search API, I will also accept the answer.
I tried also the Bing Search API, It worked also, but the same problem appeared, there is no way to specify that I need a images with transparent background.

UPDATE
according to this discussion
there is undocumented parameter in the Google deprecated search api which do bring the transparent images, which as the following

imgc=trans

this is working for the old deprecated google search api, but it does not work for the new API and it does not worked also for the BING api.

UPDATE
For Bing Search API I tried to add this query parameter which speicyf the transparent background in the BING image search (in the website not in the API) to the URL

qft=+filterui:photo-transparent

although this is working for the Normal BING search, it did not work for the BING Search API.


问:
Verilog error: not a valid l-value
I'm trying to test if a wire(s) is on or not to signify if there is an error/overflow in my alu code. Given  this code:

```<code>output reg[3:0]x;                       // line 149
output wire error;
output wire overflow;

always @* begin
    if(error || overflow) begin
        assign x = 4'b1111;             // line 155
        assign error = ~error;
        assign overflow = ~overflow;
    end else begin
        assign x = opcode;
    end
end
</code>```

I get following error messages:

uut is my instantiation unit in my testbench called main

答:
The code in the example has several issues.

1) you tried to use 'procedural assignments' which is an advanced verilog topic. In other words assign statement inside of an always block. This is not synthesizable, can only be used on reg types, and is there in verilog for very special cases. Do not use it.

You error messages coming from the fact that error and overflow are declared as wire.

2) you are trying to assign inverted version of a value to itself in a non-clocked logic. It will not behave the way you expect. Depending on usage it can either not toggle or will cause an infinite zero-delay loop, or in your case it could just generate a glitch.

So, potentially, your code should look something like the following:

```<code>input wire clk; // << you need clock
output reg[3:0]x;                       // line 149
output wire error;
output wire overflow;

reg error_reg, overflow_reg;

 always @(posedge clk) begin
    if(error || overflow) begin
        x <= 4'b1111;             // line 155
        error_reg <= ~error;
        overflow_reg <= ~overflow;
    end else begin
        x <= opcode;
    end
 assign error = error_reg;
 assign overflow = overflow_reg;
end
</code>```

Title: Verilog error: not a valid l-value

Body:
I'm trying to test if a wire(s) is on or not to signify if there is an error/overflow in my alu code. Given  this code:

output reg[3:0]x;                       // line 149
output wire error;
output wire overflow;

always @* begin
    if(error || overflow) begin
        assign x = 4'b1111;             // line 155
        assign error = ~error;
        assign overflow = ~overflow;
    end else begin
        assign x = opcode;
    end
end

I get following error messages:

uut is my instantiation unit in my testbench called main

Body:
The code in the example has several issues.

1) you tried to use 'procedural assignments' which is an advanced verilog topic. In other words assign statement inside of an always block. This is not synthesizable, can only be used on reg types, and is there in verilog for very special cases. Do not use it.

You error messages coming from the fact that error and overflow are declared as wire.

2) you are trying to assign inverted version of a value to itself in a non-clocked logic. It will not behave the way you expect. Depending on usage it can either not toggle or will cause an infinite zero-delay loop, or in your case it could just generate a glitch.

So, potentially, your code should look something like the following:

input wire clk; // << you need clock
output reg[3:0]x;                       // line 149
output wire error;
output wire overflow;

reg error_reg, overflow_reg;

 always @(posedge clk) begin
    if(error || overflow) begin
        x <= 4'b1111;             // line 155
        error_reg <= ~error;
        overflow_reg <= ~overflow;
    end else begin
        x <= opcode;
    end
 assign error = error_reg;
 assign overflow = overflow_reg;
end


问:
Send image in email through web service
I am a email web services which allows html content and one method that allows

```<code>byte[][] lstAttachment, string attachmentName, string[] contentType
</code>```

I want to send email with inline image.
I know I can send using system.net.mail by using AlternateView and LinkedResources but I can't use them because I have custom web service to send email.

I tried putting absolute address like :

body = "<htm>  ";

but it didn't work either.

So how can I embed image in email without using AlternateView or without using system.net for sending email

Update :

I tried converting image to base64 but didn't work that.. here is my html with base64

```<code><htm><body>  <img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADwAAAAZCAYAAABtnU33AAAACXBIWXMAAAsTAAALEwEAmpwYAAAAIGNIUk0AAHolAACAgwAA+f8AAIDpAAB1MAAA6mAAADqYAAAXb5JfxUYAAAHCSURBVHja5NgvbBNRGADwH0clAoJDkZBDgEBhEFzQhIBEEhwWMUGKGblkwayG1ZHKVrGF1JFAKk6sglZsYmEJqcCRTmAmliH2ujRho39WWHv3JU9c8/W7/vou7973Lrz6slPGG8WI1xG2FSe2I3TRLwC2j26EXWQFAGdpEu9G4aJVAHALBuDP2Msxdi8Yj8FtNHMMbqZJ3B4Gw8ccg49tw+B1bOQQuxFsf4D3UcdBjrAHqKdJvH8SWADXcgSupUlcH/4gOiHpPbZygN0KFqPAGao5AFfTJM7GAcMaKguMrQSDccGHWEVjAbENrKZJfDgJGHpYWbANSRMraRL3TkuIRhToYHlB0E0sp0nc+VtSNEahTZTn/PFuoJwm8eaoxGjMgh0szelCVsHSqJkdRGmCwj28xDe8wO05eM9WsXbaAnVW8GD1foeveI5nuHgO28Va2FRkaRJP9OXSlDfNwviEp3j8HxuBehhTRemMP6COD3iCR3iIy/+geW+GFm89NDnOCzzoshph3MUD3Mc9XJmyZj88Qa1wUtGe1b9XmvFstMN4ixu4g1u4ieu4hqu4FPJ/4Sd+4Dt2HB0bdx0dLs48fg8Ax9hvy8gn+qUAAAAASUVORK5CYII=" /></body></html>
</code>```

答:
Convert the image to Base64 string, set it as image source as followed.

```<code>    <div>
       <p>Taken from wikpedia</p>
       <img src="data:image/png;base64, iVBORw0KGgoAAAANSUhEUgAAAAUA
         AAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO
         9TXL0Y4OHwAAAABJRU5ErkJggg==" alt="Red dot" />
    </div>
</code>```

Code example coming from:

How to display Base64 images in HTML?

Title: Send image in email through web service

Body:
I am a email web services which allows html content and one method that allows

byte[][] lstAttachment, string attachmentName, string[] contentType

I want to send email with inline image.
I know I can send using system.net.mail by using AlternateView and LinkedResources but I can't use them because I have custom web service to send email.

I tried putting absolute address like :

body = "<htm>  ";

but it didn't work either.

So how can I embed image in email without using AlternateView or without using system.net for sending email

Update :

I tried converting image to base64 but didn't work that.. here is my html with base64

<htm>  <img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADwAAAAZCAYAAABtnU33AAAACXBIWXMAAAsTAAALEwEAmpwYAAAAIGNIUk0AAHolAACAgwAA+f8AAIDpAAB1MAAA6mAAADqYAAAXb5JfxUYAAAHCSURBVHja5NgvbBNRGADwH0clAoJDkZBDgEBhEFzQhIBEEhwWMUGKGblkwayG1ZHKVrGF1JFAKk6sglZsYmEJqcCRTmAmliH2ujRho39WWHv3JU9c8/W7/vou7973Lrz6slPGG8WI1xG2FSe2I3TRLwC2j26EXWQFAGdpEu9G4aJVAHALBuDP2Msxdi8Yj8FtNHMMbqZJ3B4Gw8ccg49tw+B1bOQQuxFsf4D3UcdBjrAHqKdJvH8SWADXcgSupUlcH/4gOiHpPbZygN0KFqPAGao5AFfTJM7GAcMaKguMrQSDccGHWEVjAbENrKZJfDgJGHpYWbANSRMraRL3TkuIRhToYHlB0E0sp0nc+VtSNEahTZTn/PFuoJwm8eaoxGjMgh0szelCVsHSqJkdRGmCwj28xDe8wO05eM9WsXbaAnVW8GD1foeveI5nuHgO28Va2FRkaRJP9OXSlDfNwviEp3j8HxuBehhTRemMP6COD3iCR3iIy/+geW+GFm89NDnOCzzoshph3MUD3Mc9XJmyZj88Qa1wUtGe1b9XmvFstMN4ixu4g1u4ieu4hqu4FPJ/4Sd+4Dt2HB0bdx0dLs48fg8Ax9hvy8gn+qUAAAAASUVORK5CYII=" />

Body:
Convert the image to Base64 string, set it as image source as followed.

    <div>
       <p>Taken from wikpedia</p>
       <img src="data:image/png;base64, iVBORw0KGgoAAAANSUhEUgAAAAUA
         AAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO
         9TXL0Y4OHwAAAABJRU5ErkJggg==" alt="Red dot" />
    </div>

Code example coming from:

How to display Base64 images in HTML?


问:
Strings in android/java, replace() does nothing
In android/java, I'm trying to replace the space in some strings with a <code>+</code>, but it doesn't seem to work. Am I doing it wrong?    </p>

```<code>String string="Hello world";
string.replace(" ", "+");
</code>```

答:
String objects are immutable, so the replace method doesn't change the string but creates a new one that you have to re-save:

```<code>String string="Hello world";
string = string.replace(" ", "+");
</code>```

Body:
In android/java, I'm trying to replace the space in some strings with a +, but it doesn't seem to work. Am I doing it wrong?

String string="Hello world";
string.replace(" ", "+");

Body:
String objects are immutable, so the replace method doesn't change the string but creates a new one that you have to re-save:

String string="Hello world";
string = string.replace(" ", "+");


问:
How do I check if a cookie exists?
What's a good way to check if a cookie exist?

Conditions:

Cookie exists if

```<code>cookie1=;cookie1=345534;
//or
cookie1=345534;cookie1=;
//or
cookie1=345534;
</code>```

Cookie doesn't exist if

```<code>cookie=;
//or
<blank>
</code>```

答:
ATTENTION!
the chosen answer contains a bug (Jac's answer).

if you have more than one cookie (very likely..) and the cookie you are retrieving is the first on the list, it doesn't set the variable "end" and therefore it will return the entire string of characters following the "cookieName=" within the document.cookie string!

here is a revised version of that function:

```<code>function getCookie( name ) {
    var dc,
        prefix,
        begin,
        end;

    dc = document.cookie;
    prefix = name + "=";
    begin = dc.indexOf("; " + prefix);
    end = dc.length; // default to end of the string

    // found, and not in first position
    if (begin !== -1) {
        // exclude the "; "
        begin += 2;
    } else {
        //see if cookie is in first position
        begin = dc.indexOf(prefix);
        // not found at all or found as a portion of another cookie name
        if (begin === -1 || begin !== 0 ) return null;
    }

    // if we find a ";" somewhere after the prefix position then "end" is that position,
    // otherwise it defaults to the end of the string
    if (dc.indexOf(";", begin) !== -1) {
        end = dc.indexOf(";", begin);
    }

    return decodeURI(dc.substring(begin + prefix.length, end) ).replace(/\"/g, '');
}
</code>```

Title: How do I check if a cookie exists?

Body:
What's a good way to check if a cookie exist?

Conditions:

Cookie exists if

cookie1=;cookie1=345534;
//or
cookie1=345534;cookie1=;
//or
cookie1=345534;

Cookie doesn't exist if

cookie=;
//or
<blank>

Body:
ATTENTION!
the chosen answer contains a bug (Jac's answer).

if you have more than one cookie (very likely..) and the cookie you are retrieving is the first on the list, it doesn't set the variable "end" and therefore it will return the entire string of characters following the "cookieName=" within the document.cookie string!

here is a revised version of that function:

function getCookie( name ) {
    var dc,
        prefix,
        begin,
        end;

    dc = document.cookie;
    prefix = name + "=";
    begin = dc.indexOf("; " + prefix);
    end = dc.length; // default to end of the string

    // found, and not in first position
    if (begin !== -1) {
        // exclude the "; "
        begin += 2;
    } else {
        //see if cookie is in first position
        begin = dc.indexOf(prefix);
        // not found at all or found as a portion of another cookie name
        if (begin === -1 || begin !== 0 ) return null;
    }

    // if we find a ";" somewhere after the prefix position then "end" is that position,
    // otherwise it defaults to the end of the string
    if (dc.indexOf(";", begin) !== -1) {
        end = dc.indexOf(";", begin);
    }

    return decodeURI(dc.substring(begin + prefix.length, end) ).replace(/\"/g, '');
}


问:
spring-boot spring security angularjs
I'm a newbie to the spring world. I need to create a spring boot - angularjs application with some CRUD operations.

The clients need LDAP and local JDBC authentication mechanisms.

They need an authorization mechanism which is common for both sets of users.

The users should be restricted from some pages based on their roles. And separate permissions(Create, Update, Delete) sets needed to be applied to each user

And the roles should be created by the Admin user.

so how can I implement the page-wise authorization which would be decided by the admin that who (which role) can access which page?

```<code>@Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests().antMatchers("/", "/home").permitAll().antMatchers("/admin").hasRole("ADMIN")
                .anyRequest().authenticated().and().formLogin().loginPage("/login").permitAll().and().logout()
                .permitAll();
        http.exceptionHandling().accessDeniedPage("/403");
    }
</code>```

should I specify each role-page combination in the config?
Is there any way to dynamically change pages and roles, as the roles may get added later.

答:
You can use spring mvc and Secured annotation

```<code>@Controller
public class MainController extends BaseController  {

    @Secured("ROLE_ADMIN")
    @RequestMapping("/")
    String home(Model model) {
        return "home";
    }
</code>```

}

home page will be   /resources/templates/home.ftl or jsp as you preferred. If User is not admin then it will redirect to error page.

If you want you can check permissions manually and send redirect to another page.

P.S : You need to add
@EnableGlobalMethodSecurity(securedEnabled = true)
to Spring boot Configuration class in order to Secured annotation work.

```<code>@EnableAutoConfiguration
@ComponentScan
@Configuration
@EnableGlobalMethodSecurity(securedEnabled = true)
public class Application {

   public static void main(String[] args) throws Exception {
       SpringApplication.run(Application.class, args);
   }
</code>```

}

Title: spring-boot spring security angularjs

Body:
I'm a newbie to the spring world. I need to create a spring boot - angularjs application with some CRUD operations.

The clients need LDAP and local JDBC authentication mechanisms.

They need an authorization mechanism which is common for both sets of users.

The users should be restricted from some pages based on their roles. And separate permissions(Create, Update, Delete) sets needed to be applied to each user

And the roles should be created by the Admin user.

so how can I implement the page-wise authorization which would be decided by the admin that who (which role) can access which page?

@Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests().antMatchers("/", "/home").permitAll().antMatchers("/admin").hasRole("ADMIN")
                .anyRequest().authenticated().and().formLogin().loginPage("/login").permitAll().and().logout()
                .permitAll();
        http.exceptionHandling().accessDeniedPage("/403");
    }

should I specify each role-page combination in the config?
Is there any way to dynamically change pages and roles, as the roles may get added later.

Body:
You can use spring mvc and Secured annotation

@Controller
public class MainController extends BaseController  {

    @Secured("ROLE_ADMIN")
    @RequestMapping("/")
    String home(Model model) {
        return "home";
    }

}

home page will be   /resources/templates/home.ftl or jsp as you preferred. If User is not admin then it will redirect to error page.

If you want you can check permissions manually and send redirect to another page.

P.S : You need to add
@EnableGlobalMethodSecurity(securedEnabled = true)
to Spring boot Configuration class in order to Secured annotation work.

@EnableAutoConfiguration
@ComponentScan
@Configuration
@EnableGlobalMethodSecurity(securedEnabled = true)
public class Application {

   public static void main(String[] args) throws Exception {
       SpringApplication.run(Application.class, args);
   }

}


问:
JavaFX TreeTableView and ContextMenu
In my project I have a TreeTableView with 5 columns.
I need a different context Menu for every columns.
I have created a ContextMenu in Source Builder for every columns (in the example you see only one for "value" column), but the menù appears only with right click on column header, but I need the menù appears only on right click on cell value

```<code>      <TreeTableView fx:id="valueTable" prefHeight="200.0" prefWidth="200.0" BorderPane.alignment="CENTER">
    <columns>
      <TreeTableColumn fx:id="context" prefWidth="483.20001524686813" sortable="false" text="Context" />
      <TreeTableColumn fx:id="tag" minWidth="50.0" prefWidth="90.0" sortable="false" text="Tag" />
      <TreeTableColumn fx:id="offset" minWidth="50.0" prefWidth="90.0" sortable="false" text="OffSet" />
      <TreeTableColumn fx:id="lenght" minWidth="50.0" prefWidth="90.0" sortable="false" text="Lenght" />
      <TreeTableColumn fx:id="value" prefWidth="367.99993896484375" sortable="false" text="Value">
           <contextMenu>
              <ContextMenu fx:id="contextMenuValue" >
                <items>
                  <MenuItem mnemonicParsing="false" text="Action 1" />
                  <MenuItem mnemonicParsing="false" text="Action 2" />
                  <MenuItem mnemonicParsing="false" text="Action 3" />
                  <MenuItem mnemonicParsing="false" text="Action 4" />
                </items>
              </ContextMenu>
           </contextMenu>
      </TreeTableColumn>
    </columns>
  </TreeTableView>
</code>```

I try to add this code for check the MouseClick event, but event is intercepted only on TreeTableView "valueTable" and not on TreeTableColumn "value".

```<code>        value.addEventHandler(MouseEvent.MOUSE_CLICKED, (MouseEvent e) -> {
                System.out.println("Work Cell");
        });
        valueTable.addEventHandler(MouseEvent.MOUSE_CLICKED, (MouseEvent e) -> {
            System.out.println("Work Table");
        });
</code>```

Can you help me?
Regard.

答:
I have resolved with</p>

```<code>            value.setCellFactory(tc -> {
            TreeTableCell<MyModel, String> cell = new TreeTableCell<MyModel, String>() {
                @Override
                protected void updateItem(String item, boolean empty) {
                    super.updateItem(item, empty) ;
                    setText(empty ? null : item);
                }
            };
            cell.setOnMouseClicked(e -> {
                if (! cell.isEmpty()) {
                    String userId = cell.getItem();
                    System.out.println("Work!");
                }
            });
            return cell ;
        });
</code>```

Title: JavaFX TreeTableView and ContextMenu

Body:
In my project I have a TreeTableView with 5 columns.
I need a different context Menu for every columns.
I have created a ContextMenu in Source Builder for every columns (in the example you see only one for "value" column), but the menù appears only with right click on column header, but I need the menù appears only on right click on cell value

      <TreeTableView fx:id="valueTable" prefHeight="200.0" prefWidth="200.0" BorderPane.alignment="CENTER">
    <columns>
      <TreeTableColumn fx:id="context" prefWidth="483.20001524686813" sortable="false" text="Context" />
      <TreeTableColumn fx:id="tag" minWidth="50.0" prefWidth="90.0" sortable="false" text="Tag" />
      <TreeTableColumn fx:id="offset" minWidth="50.0" prefWidth="90.0" sortable="false" text="OffSet" />
      <TreeTableColumn fx:id="lenght" minWidth="50.0" prefWidth="90.0" sortable="false" text="Lenght" />
      <TreeTableColumn fx:id="value" prefWidth="367.99993896484375" sortable="false" text="Value">
           <contextMenu>
              <ContextMenu fx:id="contextMenuValue" >
                <items>
                  <MenuItem mnemonicParsing="false" text="Action 1" />
                  <MenuItem mnemonicParsing="false" text="Action 2" />
                  <MenuItem mnemonicParsing="false" text="Action 3" />
                  <MenuItem mnemonicParsing="false" text="Action 4" />
                </items>
              </ContextMenu>
           </contextMenu>
      </TreeTableColumn>
    </columns>
  </TreeTableView>

I try to add this code for check the MouseClick event, but event is intercepted only on TreeTableView "valueTable" and not on TreeTableColumn "value".

        value.addEventHandler(MouseEvent.MOUSE_CLICKED, (MouseEvent e) -> {
                System.out.println("Work Cell");
        });
        valueTable.addEventHandler(MouseEvent.MOUSE_CLICKED, (MouseEvent e) -> {
            System.out.println("Work Table");
        });

Can you help me?
Regard.

Body:
I have resolved with

            value.setCellFactory(tc -> {
            TreeTableCell<MyModel, String> cell = new TreeTableCell<MyModel, String>() {
                @Override
                protected void updateItem(String item, boolean empty) {
                    super.updateItem(item, empty) ;
                    setText(empty ? null : item);
                }
            };
            cell.setOnMouseClicked(e -> {
                if (! cell.isEmpty()) {
                    String userId = cell.getItem();
                    System.out.println("Work!");
                }
            });
            return cell ;
        });


问:
VBA to maintain format during copy paste
I have a Macros enabled workbook(protected sheets).
Users are allowed to provide the inputs to the cells that are unlocked.

The problem here is when users copy paste the data from other applications, it will overwrite the format used on an existing sheet, which is creating a hassle.

Is it possible to keep the format even when users copy/paste?

答:
1) Create custom styles for various formatting used on your sheet and (if possible) name ranges which are "styled"

```<code>Private Sub Worksheet_Change(ByVal Target As Range)

If Intersect(Target, Range("STYLE")).Count = Target.Count Then
    Target.Style = "STYLE"
End If

End Sub
</code>```

This code will check, if changed cells are "inside" of styled range. If all changed cells are inside the styled range - apply the style. If you keep the range naming consistent with style naming you can use a loop to go through.

Body:
1) Create custom styles for various formatting used on your sheet and (if possible) name ranges which are "styled"

Private Sub Worksheet_Change(ByVal Target As Range)

If Intersect(Target, Range("STYLE")).Count = Target.Count Then
    Target.Style = "STYLE"
End If

End Sub

This code will check, if changed cells are "inside" of styled range. If all changed cells are inside the styled range - apply the style. If you keep the range naming consistent with style naming you can use a loop to go through.


问:
Debug JS Verticle vertx
Is there a way to debug a javascript verticle in intellij(or any other app/tool) like you can debug it on any browser dev tool? I have tried adding debugger to the code but doesn't work and I could literally find nothing online on this.

答:
You can debug from IntelliJ IDEA. I'm currently on version (2017.2.4) and this is how it works. Assuming you have a minimal js project (for reference I've used this generator: http://vertx-starter.jetdrone.xyz/)

I've added 2 breakpoints to the generated main_verticle.js file:

Now you need to configure your runner, for this you need to create a run configuration of type Application with the following config:

Main Class: always io.vertx.core.Launcher

Program Arguments: run your_js_file.js

You can test the configuration by running it and see that the server starts.
Now to debug just press the debug icon and you should get:

Title: Debug JS Verticle vertx


问:
Mysql query join table and let fill with empty if value same
I Have problem with joining 2 table
this is mysql query

select *
  from tbl_perspective a
  inner join tbl_objective b on b.idperspective=a.idperspective

The result is:
Query Result

I Want to display first row of perspectivename and blank or null

Final Result:
enter image description here

答:
Hi Anwr Rawk simply you can use LEFT JOIN</p>

```<code> select * from tbl_perspective as a
     left join
 tbl_objective as b
 on b.idperspective=a.idperspective
</code>```

Body:
Hi Anwr Rawk simply you can use LEFT JOIN

 select * from tbl_perspective as a
     left join
 tbl_objective as b
 on b.idperspective=a.idperspective


问:
Inserting running total
Problem to insert running total in MySQL transactional database. need your help for solutions and opinion. Table structure of my table is,

```<code>create table `wtacct` (
  `ID` int(11) NOT NULL AUTO_INCREMENT,
  `ACCOUNT_NO` varchar(16),
  `AMOUNT` float(16,2),
  `BALANCE` float(16,2)
);
</code>```

[Please note other fields have been removed to make it simple example]

I am doing Transaction as,

Dr 10 USD from account 1001 and

Cr 10 USD to   account 2002

Insert query

```<code>INSERT INTO wtacct (ID, ACCOUNT_NO, AMOUNT, BALANCE)
VALUES ('', 1001, -10, 100), ('', 2002, 10, 5000);
</code>```

I want the Balance as,

BALANCE of Account no 1001 = Last transaction Balance of account 1001 - 10.

My solutions and limitations

Solution 1

In insert statement put sub query in balance field:

```<code>select balance from wtacct where account_no=1001 and id in(select max(id) from wtacct where account_no=1001)
</code>```

Limitation: Mysql does not support same table select query (wtacct) where inserting the data (wtacct).

Solution 2

Using insert into select statement

```<code>insert into wtacct select '' ID, 1001 ACCOUNT_NO, -10 AMOUNT, (BALANCE-10) BALANCE where account_no=1001 and id in(select max(id) from wtacct where account_no=1001)
</code>```

Limitation: For first transaction there is no record in wtacct for the account 1001 so select query will not return any record for first transaction.

Solution 3

Taking balance in variable and use it in insert statement.

```<code>select @balance1001 :=balance from wtacct
  where account_no=1001 and id in(select max(id) from wtacct where account_no=1001)

select @balance2002 :=balance from wtacct
  where account_no=2002 and id in(select max(id) from wtacct where account_no=2002)

INSERT INTO wtacct (ID, ACCOUNT_NO, AMOUNT, BALANCE)
VALUES ('', 1001, -10, @balance1001-10), ('', 2002, 10, @balance2002+10);
</code>```

Limitation: there is a chance to be change the balance in time between select and insert query execution. also its costly, 3 query execution required.

Solution 4

Insert and then update Balance

```<code>INSERT INTO wtacct (ID, ACCOUNT_NO, AMOUNT, BALANCE)
VALUES ('', 1001, -10, 0);

UPDATE wtacct set balance = (ifnull(Select balance from wtacct where account_no=1001 and id in(select max(id) from wtacct where id <last_insert_id() and account_no=1001),0) -10)
  where id =last_insert_id() and account_no=1001

........
</code>```

Limitation: query is costly. its required 4 (two insert and 2 update) query execution. note last_insert_id() is php function

Solution 5

Using a trigger on insert statement. In the trigger, the balance will be updated calculating last transaction value and insert amount.

Limitation: Trigger not support transaction behavior and may fail.

Please give your solution and opinion on the above solutions. Please note in the above example their may be some syntax error/error. Please ignore them.

答:
I have done it using Store Procedure for MySql

```<code>CREATE DEFINER=`root`@`%` PROCEDURE `example_add`(IN dr Int, IN cr Int)
BEGIN

DECLARE LID int;
Declare Balance decimal(16,2);

INSERT INTO example (Debit,Credit)
VALUES (dr, cr);

SET LID = LAST_INSERT_ID();

SET Balance = (select SUM(Debit) - SUM(Credit) as Balance from example);

UPDATE Example SET  Balance = Balance WHERE ID = LID;

END
</code>```

Use it example_add(10,0) or example_add(0,15) then select and see the result.

Title: Inserting running total

Body:
Problem to insert running total in MySQL transactional database. need your help for solutions and opinion. Table structure of my table is,

create table `wtacct` (
  `ID` int(11) NOT NULL AUTO_INCREMENT,
  `ACCOUNT_NO` varchar(16),
  `AMOUNT` float(16,2),
  `BALANCE` float(16,2)
);

[Please note other fields have been removed to make it simple example]

I am doing Transaction as,

Dr 10 USD from account 1001 and

Cr 10 USD to   account 2002

Insert query

INSERT INTO wtacct (ID, ACCOUNT_NO, AMOUNT, BALANCE)
VALUES ('', 1001, -10, 100), ('', 2002, 10, 5000);

I want the Balance as,

BALANCE of Account no 1001 = Last transaction Balance of account 1001 - 10.

My solutions and limitations

Solution 1

In insert statement put sub query in balance field:

select balance from wtacct where account_no=1001 and id in(select max(id) from wtacct where account_no=1001)

Limitation: Mysql does not support same table select query (wtacct) where inserting the data (wtacct).

Solution 2

Using insert into select statement

insert into wtacct select '' ID, 1001 ACCOUNT_NO, -10 AMOUNT, (BALANCE-10) BALANCE where account_no=1001 and id in(select max(id) from wtacct where account_no=1001)

Limitation: For first transaction there is no record in wtacct for the account 1001 so select query will not return any record for first transaction.

Solution 3

Taking balance in variable and use it in insert statement.

select @balance1001 :=balance from wtacct
  where account_no=1001 and id in(select max(id) from wtacct where account_no=1001)

select @balance2002 :=balance from wtacct
  where account_no=2002 and id in(select max(id) from wtacct where account_no=2002)

INSERT INTO wtacct (ID, ACCOUNT_NO, AMOUNT, BALANCE)
VALUES ('', 1001, -10, @balance1001-10), ('', 2002, 10, @balance2002+10);

Limitation: there is a chance to be change the balance in time between select and insert query execution. also its costly, 3 query execution required.

Solution 4

Insert and then update Balance

INSERT INTO wtacct (ID, ACCOUNT_NO, AMOUNT, BALANCE)
VALUES ('', 1001, -10, 0);

UPDATE wtacct set balance = (ifnull(Select balance from wtacct where account_no=1001 and id in(select max(id) from wtacct where id <last_insert_id() and account_no=1001),0) -10)
  where id =last_insert_id() and account_no=1001

........

Limitation: query is costly. its required 4 (two insert and 2 update) query execution. note last_insert_id() is php function

Solution 5

Using a trigger on insert statement. In the trigger, the balance will be updated calculating last transaction value and insert amount.

Limitation: Trigger not support transaction behavior and may fail.

Please give your solution and opinion on the above solutions. Please note in the above example their may be some syntax error/error. Please ignore them.

Body:
I have done it using Store Procedure for MySql

CREATE DEFINER=`root`@`%` PROCEDURE `example_add`(IN dr Int, IN cr Int)
BEGIN

DECLARE LID int;
Declare Balance decimal(16,2);

INSERT INTO example (Debit,Credit)
VALUES (dr, cr);

SET LID = LAST_INSERT_ID();

SET Balance = (select SUM(Debit) - SUM(Credit) as Balance from example);

UPDATE Example SET  Balance = Balance WHERE ID = LID;

END

Use it example_add(10,0) or example_add(0,15) then select and see the result.


问:
Context menu for windows bash admin
I would like to be able to open the windows bash terminal from windows explorer with a context menu. Much like you can do in Ubuntu. I have created a subkey in the HKEY_CLASSES_ROOT/Directory/Background/shell with the command:

```<code>powershell -c start -verb runas cmd '/c start /D "%V" bash.exe'
</code>```

This works well for opening the bash as admin in most directories, but it crashes if the directory has a space in it. It seems to be that bash only takes part of the string, and then can't find the directory to navigate to. I've tried escape quotes around the %V, e.g """%V""" but that didn't help. Any ideas?

答: Here's an alternate approach that avoids PowerShell. Create a key named "HKLM\Software\Classes\Directory\background\shell\runas" and give it a default value like "Open in bash as administrator". Create a subkey named "command" and give it a default value of "C:\Windows\System32\cmd.exe" /c start /B /D "%V" bash.exe. Change the path to cmd.exe if you have a different system directory. It has to be the fully-qualified path to cmd.exe.  – eryksun</p>

Title: Context menu for windows bash admin

Body:
I would like to be able to open the windows bash terminal from windows explorer with a context menu. Much like you can do in Ubuntu. I have created a subkey in the HKEY_CLASSES_ROOT/Directory/Background/shell with the command:

powershell -c start -verb runas cmd '/c start /D "%V" bash.exe'

This works well for opening the bash as admin in most directories, but it crashes if the directory has a space in it. It seems to be that bash only takes part of the string, and then can't find the directory to navigate to. I've tried escape quotes around the %V, e.g """%V""" but that didn't help. Any ideas?


问:
Dask - Reading partitions in order using itertuples
I'm using Dask to read in a table with around 14 million rows using read_sql_table. When I read the dataframe using itertuples the index (which is ordered in the table) is not read out sequentially for one or two partitions. How is it possible to enforce this? The row_id is generated by row_number (on the view) and is used as the index when generating the dataframe. I know Pandas has a sorted=True arg, anything similar?

This is what happens at the moment, while reading the data in (number of rows read should match the current index):

 INFO - Read 11870000 Rows (index: 11870000)
 INFO - Read 11880000 Rows (index: 11880000)
 INFO - Read 11890000 Rows (index: 11890000)
 INFO - Read 11900000 Rows (index: 11900000)
 --INFO - Read 11910000 Rows (index: 12159912)--
 INFO - Read 11920000 Rows (index: 12169912)
 INFO - Read 11930000 Rows (index: 12179912)
 INFO - Read 11940000 Rows (index: 12189912)

All is good until the 11,900,000th row, and at that point it switches in the wrong partition.

答:
This might be an answer to the issue (which is perhaps rare), but the software that reads the stream requires a monotonically increasing index. I can only assume that it's the multiple calls to the DB which are being resolved at different speeds, so possibly another option would be to use the single-threaded scheduler on the compute call to read_sql_table.

First of all, I get the first index in each partition;

```<code>def _order_partitions(self, ddf):
    ordering = {}
    for partition in range(ddf.npartitions):
        ordering.update({partition: int(df.get_partition(partition).head(1).index[0])})

    return sorted(ordering, key=ordering.get)
</code>```

Storing the result in self._ordered_partitions, and then I recreate the itertuples function call in Dask (which is quite simple);

```<code>def _generator(self):
    for i in range(self._ddf.npartitions):
        ordered_partition = self._ordered_partitions[i]
        df = self._ddf.get_partition(ordered_partition).compute()
        for row in df.itertuples():
            yield row
</code>```

The only change being the addition of the ordered_partition. I've not fully tested it yet, so will mark as an answer once I'm happy with it.

Body:
This might be an answer to the issue (which is perhaps rare), but the software that reads the stream requires a monotonically increasing index. I can only assume that it's the multiple calls to the DB which are being resolved at different speeds, so possibly another option would be to use the single-threaded scheduler on the compute call to read_sql_table.

First of all, I get the first index in each partition;

def _order_partitions(self, ddf):
    ordering = {}
    for partition in range(ddf.npartitions):
        ordering.update({partition: int(df.get_partition(partition).head(1).index[0])})

    return sorted(ordering, key=ordering.get)

Storing the result in self._ordered_partitions, and then I recreate the itertuples function call in Dask (which is quite simple);

def _generator(self):
    for i in range(self._ddf.npartitions):
        ordered_partition = self._ordered_partitions[i]
        df = self._ddf.get_partition(ordered_partition).compute()
        for row in df.itertuples():
            yield row

The only change being the addition of the ordered_partition. I've not fully tested it yet, so will mark as an answer once I'm happy with it.


问:
Binary data with pyserial(python serial port)
serial.write() method in pyserial seems to only send string data. I have arrays like [0xc0,0x04,0x00] and want to be able to send/receive them via the serial port? Are there any separate methods for raw I/O?

I think I might need to change the arrays to ['\xc0','\x04','\x00'], still, null character might pose a problem.

答:
You need to convert your data to a string

```<code>"\xc0\x04\x00"
</code>```

Null characters are not a problem in Python -- strings are not null-terminated the zero byte behaves just like another byte "\x00".

One way to do this:

```<code>>>> import array
>>> array.array('B', [0xc0, 0x04, 0x00]).tostring()
'\xc0\x04\x00'
</code>```

OwnerDisplayName: Atilla Filiz

Body:
You need to convert your data to a string

"\xc0\x04\x00"

Null characters are not a problem in Python -- strings are not null-terminated the zero byte behaves just like another byte "\x00".

One way to do this:

>>> import array
>>> array.array('B', [0xc0, 0x04, 0x00]).tostring()
'\xc0\x04\x00'

OwnerDisplayName: dF


问:
Firebase Realtime Database read rule for specific user
How can I add new rule to Firebase Realtime Database so that users can read data where recid equal to user ID?

I have a massage table with this structure:

```<code>"messages" : {
    "-KyyjeMOtc7fWAsOiuiP" : {
      "recid" : "FL5hyQJrsHWRQsRtiLe1PxkyRnk1",
      "senderid" : "6K6pQHaCishDlCb0Y9AaN3zI22n1",
      "text" : "hi"
    },
    "-KyykczCNpsSL6a1t8vt" : {
      "recid" : "FL5hyQJrsHWRQsRtiLe1PxkyRnk1",
      "senderid" : "6K6pQHaCishDlCb0Y9AaN3zI22n1",
      "text" : "test"
    },
  }
</code>```

I want a rule that when data is added to the database, only the user whose uid is equal to recid can see the data.

答:
To achieve this, you can create user-based security rules for your database, something similar to:

```<code>{
  "rules": {
    "messages": {
      "$messageId": {
        ".read": "auth.uid == data.child('recid').val()",
        ".write": "auth !== null"
      }
    }
  }
}
</code>```

In this example, $messageId uses a $location variable that will match any key under your messages list. Then, we grant read access only if the current user's auth.uid matches the recid child value.

Body:
How can I add new rule to Firebase Realtime Database so that users can read data where recid equal to user ID?

I have a massage table with this structure:

"messages" : {
    "-KyyjeMOtc7fWAsOiuiP" : {
      "recid" : "FL5hyQJrsHWRQsRtiLe1PxkyRnk1",
      "senderid" : "6K6pQHaCishDlCb0Y9AaN3zI22n1",
      "text" : "hi"
    },
    "-KyykczCNpsSL6a1t8vt" : {
      "recid" : "FL5hyQJrsHWRQsRtiLe1PxkyRnk1",
      "senderid" : "6K6pQHaCishDlCb0Y9AaN3zI22n1",
      "text" : "test"
    },
  }

I want a rule that when data is added to the database, only the user whose uid is equal to recid can see the data.

Body:
To achieve this, you can create user-based security rules for your database, something similar to:

{
  "rules": {
    "messages": {
      "$messageId": {
        ".read": "auth.uid == data.child('recid').val()",
        ".write": "auth !== null"
      }
    }
  }
}

In this example, $messageId uses a $location variable that will match any key under your messages list. Then, we grant read access only if the current user's auth.uid matches the recid child value.


问:
kali linux pip install paramiko get ValueError
when I install paramiko with pip get error

ValueError: Unable to determine SOCKS version from socks://127.0.0.1:1080/

This is the detailed error code I get:

```<code>root@kali-linux:~# pip install paramiko
Collecting paramiko
Exception:
Traceback (most recent call last):
  File "/usr/local/lib/python2.7/dist-packages/pip-9.0.1-py2.7.egg/pip/basecommand.py", line 215, in main
    status = self.run(options, args)
  File "/usr/local/lib/python2.7/dist-packages/pip-9.0.1-py2.7.egg/pip/commands/install.py", line 335, in run
    wb.build(autobuilding=True)
  File "/usr/local/lib/python2.7/dist-packages/pip-9.0.1-py2.7.egg/pip/wheel.py", line 749, in build
    self.requirement_set.prepare_files(self.finder)
  File "/usr/local/lib/python2.7/dist-packages/pip-9.0.1-py2.7.egg/pip/req/req_set.py", line 380, in prepare_files
    ignore_dependencies=self.ignore_dependencies))
  File "/usr/local/lib/python2.7/dist-packages/pip-9.0.1-py2.7.egg/pip/req/req_set.py", line 554, in _prepare_file
    require_hashes
  File "/usr/local/lib/python2.7/dist-packages/pip-9.0.1-py2.7.egg/pip/req/req_install.py", line 278, in populate_link
    self.link = finder.find_requirement(self, upgrade)
  File "/usr/local/lib/python2.7/dist-packages/pip-9.0.1-py2.7.egg/pip/index.py", line 465, in find_requirement
    all_candidates = self.find_all_candidates(req.name)
  File "/usr/local/lib/python2.7/dist-packages/pip-9.0.1-py2.7.egg/pip/index.py", line 423, in find_all_candidates
    for page in self._get_pages(url_locations, project_name):
  File "/usr/local/lib/python2.7/dist-packages/pip-9.0.1-py2.7.egg/pip/index.py", line 568, in _get_pages
    page = self._get_page(location)
  File "/usr/local/lib/python2.7/dist-packages/pip-9.0.1-py2.7.egg/pip/index.py", line 683, in _get_page
    return HTMLPage.get_page(link, session=self.session)
  File "/usr/local/lib/python2.7/dist-packages/pip-9.0.1-py2.7.egg/pip/index.py", line 792, in get_page
    "Cache-Control": "max-age=600",
  File "/usr/local/lib/python2.7/dist-packages/pip-9.0.1-py2.7.egg/pip/_vendor/requests/sessions.py", line 488, in get
    return self.request('GET', url, **kwargs)
  File "/usr/local/lib/python2.7/dist-packages/pip-9.0.1-py2.7.egg/pip/download.py", line 386, in request
    return super(PipSession, self).request(method, url, *args, **kwargs)
  File "/usr/local/lib/python2.7/dist-packages/pip-9.0.1-py2.7.egg/pip/_vendor/requests/sessions.py", line 475, in request
    resp = self.send(prep, **send_kwargs)
  File "/usr/local/lib/python2.7/dist-packages/pip-9.0.1-py2.7.egg/pip/_vendor/requests/sessions.py", line 596, in send
   r = adapter.send(request, **kwargs)
  File "/usr/local/lib/python2.7/dist-packages/pip-9.0.1-py2.7.egg/pip/_vendor/cachecontrol/adapter.py", line 47, in send
    resp = super(CacheControlAdapter, self).send(request, **kw)
  File "/usr/local/lib/python2.7/dist-packages/pip-9.0.1-py2.7.egg/pip/_vendor/requests/adapters.py", line 390, in send
    conn = self.get_connection(request.url, proxies)
  File "/usr/local/lib/python2.7/dist-packages/pip-9.0.1-py2.7.egg/pip/_vendor/requests/adapters.py", line 290, in get_connection
    proxy_manager = self.proxy_manager_for(proxy)
  File "/usr/local/lib/python2.7/dist-packages/pip-9.0.1-py2.7.egg/pip/_vendor/requests/adapters.py", line 184, in proxy_manager_for
    **proxy_kwargs
  File "/usr/local/lib/python2.7/dist-packages/pip-9.0.1-py2.7.egg/pip/_vendor/requests/packages/urllib3/contrib/socks.py", line 154, in __init__
    "Unable to determine SOCKS version from %s" % proxy_url
ValueError: Unable to determine SOCKS version from socks://127.0.0.1:1080/
</code>```

And I don't what to do then I try to upgrade pip

```<code>pip install --upgrade pip
</code>```

get error prompt code

```<code>root@kali-linux:~# pip install --upgrade pip
Exception:
Traceback (most recent call last):
  File "/usr/local/lib/python2.7/dist-packages/pip-9.0.1-py2.7.egg/pip/basecommand.py", line 215, in main
    status = self.run(options, args)
  File "/usr/local/lib/python2.7/dist-packages/pip-9.0.1-py2.7.egg/pip/commands/install.py", line 335, in run
    wb.build(autobuilding=True)
  File "/usr/local/lib/python2.7/dist-packages/pip-9.0.1-py2.7.egg/pip/wheel.py", line 749, in build
    self.requirement_set.prepare_files(self.finder)
  File "/usr/local/lib/python2.7/dist-packages/pip-9.0.1-py2.7.egg/pip/req/req_set.py", line 380, in prepare_files
    ignore_dependencies=self.ignore_dependencies))
  File "/usr/local/lib/python2.7/dist-packages/pip-9.0.1-py2.7.egg/pip/req/req_set.py", line 487, in _prepare_file
    req_to_install, finder)
  File "/usr/local/lib/python2.7/dist-packages/pip-9.0.1-py2.7.egg/pip/req/req_set.py", line 428, in _check_skip_installed
    req_to_install, upgrade_allowed)
  File "/usr/local/lib/python2.7/dist-packages/pip-9.0.1-py2.7.egg/pip/index.py", line 465, in find_requirement
    all_candidates = self.find_all_candidates(req.name)
  File "/usr/local/lib/python2.7/dist-packages/pip-9.0.1-py2.7.egg/pip/index.py", line 423, in find_all_candidates
    for page in self._get_pages(url_locations, project_name):
  File "/usr/local/lib/python2.7/dist-packages/pip-9.0.1-py2.7.egg/pip/index.py", line 568, in _get_pages
    page = self._get_page(location)
  File "/usr/local/lib/python2.7/dist-packages/pip-9.0.1-py2.7.egg/pip/index.py", line 683, in _get_page
    return HTMLPage.get_page(link, session=self.session)
  File "/usr/local/lib/python2.7/dist-packages/pip-9.0.1-py2.7.egg/pip/index.py", line 792, in get_page
    "Cache-Control": "max-age=600",
  File "/usr/local/lib/python2.7/dist-packages/pip-9.0.1-py2.7.egg/pip/_vendor/requests/sessions.py", line 488, in get
    return self.request('GET', url, **kwargs)
  File "/usr/local/lib/python2.7/dist-packages/pip-9.0.1-py2.7.egg/pip/download.py", line 386, in request
    return super(PipSession, self).request(method, url, *args, **kwargs)
  File "/usr/local/lib/python2.7/dist-packages/pip-9.0.1-py2.7.egg/pip/_vendor/requests/sessions.py", line 475, in request
    resp = self.send(prep, **send_kwargs)
  File "/usr/local/lib/python2.7/dist-packages/pip-9.0.1-py2.7.egg/pip/_vendor/requests/sessions.py", line 596, in send
    r = adapter.send(request, **kwargs)
  File "/usr/local/lib/python2.7/dist-packages/pip-9.0.1-py2.7.egg/pip/_vendor/cachecontrol/adapter.py", line 47, in send
    resp = super(CacheControlAdapter, self).send(request, **kw)
  File "/usr/local/lib/python2.7/dist-packages/pip-9.0.1-py2.7.egg/pip/_vendor/requests/adapters.py", line 390, in send
    conn = self.get_connection(request.url, proxies)
  File "/usr/local/lib/python2.7/dist-packages/pip-9.0.1-py2.7.egg/pip/_vendor/requests/adapters.py", line 290, in get_connection
    proxy_manager = self.proxy_manager_for(proxy)
  File "/usr/local/lib/python2.7/dist-packages/pip-9.0.1-py2.7.egg/pip/_vendor/requests/adapters.py", line 184, in proxy_manager_for
    **proxy_kwargs
  File "/usr/local/lib/python2.7/dist-packages/pip-9.0.1-py2.7.egg/pip/_vendor/requests/packages/urllib3/contrib/socks.py", line 154, in __init__
    "Unable to determine SOCKS version from %s" % proxy_url
ValueError: Unable to determine SOCKS version from socks://127.0.0.1:1080/
</code>```

I use the command

```<code>set | grep -i all_proxy
</code>```

get the prompt code

```<code>ALL_PROXY=socks://127.0.0.1:1080/
all_proxy=socks://127.0.0.1:1080/
</code>```

what should I do?

答:
```<code>export all_proxy="socks5://127.0.0.1:1080"
export ALL_PROXY="socks5://127.0.0.1:1080"
</code>```

if you don't want a proxy:

```<code>export all_proxy=""
export ALL_PROXY=""
</code>```

Body:
when I install paramiko with pip get error

ValueError: Unable to determine SOCKS version from socks://127.0.0.1:1080/

This is the detailed error code I get:

root@kali-linux:~# pip install paramiko
Collecting paramiko
Exception:
Traceback (most recent call last):
  File "/usr/local/lib/python2.7/dist-packages/pip-9.0.1-py2.7.egg/pip/basecommand.py", line 215, in main
    status = self.run(options, args)
  File "/usr/local/lib/python2.7/dist-packages/pip-9.0.1-py2.7.egg/pip/commands/install.py", line 335, in run
    wb.build(autobuilding=True)
  File "/usr/local/lib/python2.7/dist-packages/pip-9.0.1-py2.7.egg/pip/wheel.py", line 749, in build
    self.requirement_set.prepare_files(self.finder)
  File "/usr/local/lib/python2.7/dist-packages/pip-9.0.1-py2.7.egg/pip/req/req_set.py", line 380, in prepare_files
    ignore_dependencies=self.ignore_dependencies))
  File "/usr/local/lib/python2.7/dist-packages/pip-9.0.1-py2.7.egg/pip/req/req_set.py", line 554, in _prepare_file
    require_hashes
  File "/usr/local/lib/python2.7/dist-packages/pip-9.0.1-py2.7.egg/pip/req/req_install.py", line 278, in populate_link
    self.link = finder.find_requirement(self, upgrade)
  File "/usr/local/lib/python2.7/dist-packages/pip-9.0.1-py2.7.egg/pip/index.py", line 465, in find_requirement
    all_candidates = self.find_all_candidates(req.name)
  File "/usr/local/lib/python2.7/dist-packages/pip-9.0.1-py2.7.egg/pip/index.py", line 423, in find_all_candidates
    for page in self._get_pages(url_locations, project_name):
  File "/usr/local/lib/python2.7/dist-packages/pip-9.0.1-py2.7.egg/pip/index.py", line 568, in _get_pages
    page = self._get_page(location)
  File "/usr/local/lib/python2.7/dist-packages/pip-9.0.1-py2.7.egg/pip/index.py", line 683, in _get_page
    return HTMLPage.get_page(link, session=self.session)
  File "/usr/local/lib/python2.7/dist-packages/pip-9.0.1-py2.7.egg/pip/index.py", line 792, in get_page
    "Cache-Control": "max-age=600",
  File "/usr/local/lib/python2.7/dist-packages/pip-9.0.1-py2.7.egg/pip/_vendor/requests/sessions.py", line 488, in get
    return self.request('GET', url, **kwargs)
  File "/usr/local/lib/python2.7/dist-packages/pip-9.0.1-py2.7.egg/pip/download.py", line 386, in request
    return super(PipSession, self).request(method, url, *args, **kwargs)
  File "/usr/local/lib/python2.7/dist-packages/pip-9.0.1-py2.7.egg/pip/_vendor/requests/sessions.py", line 475, in request
    resp = self.send(prep, **send_kwargs)
  File "/usr/local/lib/python2.7/dist-packages/pip-9.0.1-py2.7.egg/pip/_vendor/requests/sessions.py", line 596, in send
   r = adapter.send(request, **kwargs)
  File "/usr/local/lib/python2.7/dist-packages/pip-9.0.1-py2.7.egg/pip/_vendor/cachecontrol/adapter.py", line 47, in send
    resp = super(CacheControlAdapter, self).send(request, **kw)
  File "/usr/local/lib/python2.7/dist-packages/pip-9.0.1-py2.7.egg/pip/_vendor/requests/adapters.py", line 390, in send
    conn = self.get_connection(request.url, proxies)
  File "/usr/local/lib/python2.7/dist-packages/pip-9.0.1-py2.7.egg/pip/_vendor/requests/adapters.py", line 290, in get_connection
    proxy_manager = self.proxy_manager_for(proxy)
  File "/usr/local/lib/python2.7/dist-packages/pip-9.0.1-py2.7.egg/pip/_vendor/requests/adapters.py", line 184, in proxy_manager_for
    **proxy_kwargs
  File "/usr/local/lib/python2.7/dist-packages/pip-9.0.1-py2.7.egg/pip/_vendor/requests/packages/urllib3/contrib/socks.py", line 154, in __init__
    "Unable to determine SOCKS version from %s" % proxy_url
ValueError: Unable to determine SOCKS version from socks://127.0.0.1:1080/

And I don't what to do then I try to upgrade pip

pip install --upgrade pip

get error prompt code

root@kali-linux:~# pip install --upgrade pip
Exception:
Traceback (most recent call last):
  File "/usr/local/lib/python2.7/dist-packages/pip-9.0.1-py2.7.egg/pip/basecommand.py", line 215, in main
    status = self.run(options, args)
  File "/usr/local/lib/python2.7/dist-packages/pip-9.0.1-py2.7.egg/pip/commands/install.py", line 335, in run
    wb.build(autobuilding=True)
  File "/usr/local/lib/python2.7/dist-packages/pip-9.0.1-py2.7.egg/pip/wheel.py", line 749, in build
    self.requirement_set.prepare_files(self.finder)
  File "/usr/local/lib/python2.7/dist-packages/pip-9.0.1-py2.7.egg/pip/req/req_set.py", line 380, in prepare_files
    ignore_dependencies=self.ignore_dependencies))
  File "/usr/local/lib/python2.7/dist-packages/pip-9.0.1-py2.7.egg/pip/req/req_set.py", line 487, in _prepare_file
    req_to_install, finder)
  File "/usr/local/lib/python2.7/dist-packages/pip-9.0.1-py2.7.egg/pip/req/req_set.py", line 428, in _check_skip_installed
    req_to_install, upgrade_allowed)
  File "/usr/local/lib/python2.7/dist-packages/pip-9.0.1-py2.7.egg/pip/index.py", line 465, in find_requirement
    all_candidates = self.find_all_candidates(req.name)
  File "/usr/local/lib/python2.7/dist-packages/pip-9.0.1-py2.7.egg/pip/index.py", line 423, in find_all_candidates
    for page in self._get_pages(url_locations, project_name):
  File "/usr/local/lib/python2.7/dist-packages/pip-9.0.1-py2.7.egg/pip/index.py", line 568, in _get_pages
    page = self._get_page(location)
  File "/usr/local/lib/python2.7/dist-packages/pip-9.0.1-py2.7.egg/pip/index.py", line 683, in _get_page
    return HTMLPage.get_page(link, session=self.session)
  File "/usr/local/lib/python2.7/dist-packages/pip-9.0.1-py2.7.egg/pip/index.py", line 792, in get_page
    "Cache-Control": "max-age=600",
  File "/usr/local/lib/python2.7/dist-packages/pip-9.0.1-py2.7.egg/pip/_vendor/requests/sessions.py", line 488, in get
    return self.request('GET', url, **kwargs)
  File "/usr/local/lib/python2.7/dist-packages/pip-9.0.1-py2.7.egg/pip/download.py", line 386, in request
    return super(PipSession, self).request(method, url, *args, **kwargs)
  File "/usr/local/lib/python2.7/dist-packages/pip-9.0.1-py2.7.egg/pip/_vendor/requests/sessions.py", line 475, in request
    resp = self.send(prep, **send_kwargs)
  File "/usr/local/lib/python2.7/dist-packages/pip-9.0.1-py2.7.egg/pip/_vendor/requests/sessions.py", line 596, in send
    r = adapter.send(request, **kwargs)
  File "/usr/local/lib/python2.7/dist-packages/pip-9.0.1-py2.7.egg/pip/_vendor/cachecontrol/adapter.py", line 47, in send
    resp = super(CacheControlAdapter, self).send(request, **kw)
  File "/usr/local/lib/python2.7/dist-packages/pip-9.0.1-py2.7.egg/pip/_vendor/requests/adapters.py", line 390, in send
    conn = self.get_connection(request.url, proxies)
  File "/usr/local/lib/python2.7/dist-packages/pip-9.0.1-py2.7.egg/pip/_vendor/requests/adapters.py", line 290, in get_connection
    proxy_manager = self.proxy_manager_for(proxy)
  File "/usr/local/lib/python2.7/dist-packages/pip-9.0.1-py2.7.egg/pip/_vendor/requests/adapters.py", line 184, in proxy_manager_for
    **proxy_kwargs
  File "/usr/local/lib/python2.7/dist-packages/pip-9.0.1-py2.7.egg/pip/_vendor/requests/packages/urllib3/contrib/socks.py", line 154, in __init__
    "Unable to determine SOCKS version from %s" % proxy_url
ValueError: Unable to determine SOCKS version from socks://127.0.0.1:1080/

I use the command

set | grep -i all_proxy

get the prompt code

ALL_PROXY=socks://127.0.0.1:1080/
all_proxy=socks://127.0.0.1:1080/

what should I do?

Body:
export all_proxy="socks5://127.0.0.1:1080"
export ALL_PROXY="socks5://127.0.0.1:1080"

if you don't want a proxy:

export all_proxy=""
export ALL_PROXY=""


问:
Webservice Security and Windows Certificates
I want to sign webservice requests using Apache CXF and WSS4J. As far as I know, I would need a JKS store containing the certificate I want to use for signing.
There's the requirement to be able to use a X.509 certificate from the Windows certificate store. The certificate shall be read from the store at the time of signing the webservice request.
I know how to access the store and get the certificate. But how can I use it for signing instead of the certificate from my own JKS store?</p>

答: The KeyStore need not be a JKS one. You might write your own JCA Provider and implement KeyStoreSpi, and have it access the Windows certificate store.</p>


问:
Handling certificate errors in Android Webview and clearing the certificate peferences
I am trying to find a proper way to handle SSL certificate errors in the Android Webview.
My goal is to provide a way to load pages with SSL certificate errors, but let the user choose to load the page after warning him about security any time he tries to load a URL with certificate errors.

The closest solutions I found in threads suggest overriding the WebViewClient as following:

```<code>webView.setWebViewClient(new WebViewClient() {
    @Override
    public void onReceivedSslError(final WebView view, final SslErrorHandler handler, final SslError error) {
        handler.proceed();
    }
});
</code>```

However this basically disables SSL in the WebView without the user consent.

For reference here are the threads where I found that solution:

Android WebView SSL 'Security Warning'

Does the Web View on Android support SSL?

Android WebView not loading an HTTPS URL

android webview with client certificate

Web view shows blank/white page after loading URL when using WIFI in Android

Unable to load a specific webpage on Android webview

WebView displays a blank view for certain links

Android WebView blocks redirect from https to http

Ignore ssl certificate requests in webview

I went ahead and implemented a slightly different version which prompts the user:

```<code>webView.setWebViewClient(new WebViewClient() {
    @Override
    public void onReceivedSslError(final WebView view, final SslErrorHandler handler, final SslError error) {
        //Showing a first confirmation dialog
        AndroidUtils.showYesNoDialog(
            //First confirmation message
            "WARNING - THIS PAGE IS NOT SECURE! Are you sure you want to continue loading it?",
            //First confirmation "YES" option runnable
            new Runnable() {
                @Override
                public void run() {
                    //Showing a second confirmation dialog
                    AndroidUtils.showYesNoDialogWithResId(
                        //Second confirmation message
                        "You chose to load an unsecure page, are you sure you want to do that?",
                        //Second confirmation "YES" option runnable
                        new Runnable() {
                            @Override
                            public void run() {
                                //Disregard the error and proceed with the bad certificate anyways
                                handler.proceed();
                            }
                        },
                        //Second confirmation "NO" option runnable
                        new Runnable() {
                            @Override
                            public void run() {
                                //Cancel loading the page with that certificate error
                                handler.cancel();
                            }
                        }
                    );
                }
            },
            //First confirmation "NO" option runnable
            new Runnable() {
                @Override
                public void run() {
                    //Cancel loading the page with that certificate error
                    handler.cancel();
                }
            });
    }
});
</code>```

This implementation asks the user twice if he wants to load the page, if he says yes twice, then the error is disregarded and the page loads, otherwise the page loading is canceled.

The first time a URL with certificate error loads, WebViewClient.onReceivedSslError is called, however if the user proceeds with the certificate error and SslErrorHandler.proceed() is called, the following times the same URL loads, WebViewClient.onReceivedSslError is never called again: only killing the app resets this behavior.

I would want WebViewClient.onReceivedSslError to be called systematically when a URL with a certificate error loads, not just the first time. I tried calling those methods without success:

```<code>/** JAVADOC QUOTE: Clears the SSL preferences table stored in response to proceeding with SSL certificate errors.*/
webView.clearSslPreferences();
//Those other methods I tried out of despair just in case
webView.clearFormData();
webView.clearCache(true);
webView.clearHistory();
webView.clearMatches();
</code>```

Does anybody know how to make the WebView call WebViewClient.onReceivedSslError more than once for the same URL, after SslErrorHandler.proceed() has been called?

答: Do not ever override onReceivedSslError method. Goole play will reject your upload. The smartest way is to handle SSL error, use webSettings.setDomStorageEnabled(true).

Body:
I am trying to find a proper way to handle SSL certificate errors in the Android Webview.
My goal is to provide a way to load pages with SSL certificate errors, but let the user choose to load the page after warning him about security any time he tries to load a URL with certificate errors.

The closest solutions I found in threads suggest overriding the WebViewClient as following:

webView.setWebViewClient(new WebViewClient() {
    @Override
    public void onReceivedSslError(final WebView view, final SslErrorHandler handler, final SslError error) {
        handler.proceed();
    }
});

However this basically disables SSL in the WebView without the user consent.

For reference here are the threads where I found that solution:

Android WebView SSL 'Security Warning'

Does the Web View on Android support SSL?

Android WebView not loading an HTTPS URL

android webview with client certificate

Web view shows blank/white page after loading URL when using WIFI in Android

Unable to load a specific webpage on Android webview

WebView displays a blank view for certain links

Android WebView blocks redirect from https to http

Ignore ssl certificate requests in webview

I went ahead and implemented a slightly different version which prompts the user:

webView.setWebViewClient(new WebViewClient() {
    @Override
    public void onReceivedSslError(final WebView view, final SslErrorHandler handler, final SslError error) {
        //Showing a first confirmation dialog
        AndroidUtils.showYesNoDialog(
            //First confirmation message
            "WARNING - THIS PAGE IS NOT SECURE! Are you sure you want to continue loading it?",
            //First confirmation "YES" option runnable
            new Runnable() {
                @Override
                public void run() {
                    //Showing a second confirmation dialog
                    AndroidUtils.showYesNoDialogWithResId(
                        //Second confirmation message
                        "You chose to load an unsecure page, are you sure you want to do that?",
                        //Second confirmation "YES" option runnable
                        new Runnable() {
                            @Override
                            public void run() {
                                //Disregard the error and proceed with the bad certificate anyways
                                handler.proceed();
                            }
                        },
                        //Second confirmation "NO" option runnable
                        new Runnable() {
                            @Override
                            public void run() {
                                //Cancel loading the page with that certificate error
                                handler.cancel();
                            }
                        }
                    );
                }
            },
            //First confirmation "NO" option runnable
            new Runnable() {
                @Override
                public void run() {
                    //Cancel loading the page with that certificate error
                    handler.cancel();
                }
            });
    }
});

This implementation asks the user twice if he wants to load the page, if he says yes twice, then the error is disregarded and the page loads, otherwise the page loading is canceled.

The first time a URL with certificate error loads, WebViewClient.onReceivedSslError is called, however if the user proceeds with the certificate error and SslErrorHandler.proceed() is called, the following times the same URL loads, WebViewClient.onReceivedSslError is never called again: only killing the app resets this behavior.

I would want WebViewClient.onReceivedSslError to be called systematically when a URL with a certificate error loads, not just the first time. I tried calling those methods without success:

/** JAVADOC QUOTE: Clears the SSL preferences table stored in response to proceeding with SSL certificate errors.*/
webView.clearSslPreferences();
//Those other methods I tried out of despair just in case
webView.clearFormData();
webView.clearCache(true);
webView.clearHistory();
webView.clearMatches();

Does anybody know how to make the WebView call WebViewClient.onReceivedSslError more than once for the same URL, after SslErrorHandler.proceed() has been called?