问:
Sorting and comparing arrays in Go
I am a beginner Go student and I've been given the following assignment that needs to be built in Go:

-Read in a data file that contains all 83 counties of Michigan and the coordinates (in decimal) for each county seat.

-Set beginning coordinates to the college I attend.
-Prompt user for a direction (n,s,e,w) and the program then finds the closest county seat in that specified direction.  The found county seat then becomes the new starting point and the program starts over with the direction prompt.

-the program needs to show an error if the user hits water or is about to leave the state.

I am able to do most of this without issue, but here is where I'm hitting a brick wall:
My plan is to use two arrays; one for latitude and one for longitude.  I need to sort each array so that the numbers are in order from the eastern most county seat to the western most county seat (for latitude and the same for longtitude).  My thinking is that if the user enters that they want to go west, the program will take the latitude coordinate of the starting point, determine where in the array it is supposed to be positioned then the program selects the closest coordinate in the numbers to the right of starting coordinate.  The program should then take the determined coordinate and reference the main map of coordinates, find the matching complete set of coordinates then set the starting point to the new coordinates.  I'm using float64s for the coordinate data types.

So to break it down:  the data file reads in the coordinates of {1, 1.2} {2,1.3} {3, 2.4} {4, 5.4} {5, 6.6};  the starting point is (1,2) and the user wants to go west.  So the latitude array holds {1.2, 1.3, 2.4, 5.4, 6.6} and the program needs to take the 2 from the starting, determine that it belongs between the 1.3 and 2.4, the determine that the 2.4 is the closest coordinate to the starting point.  Then it takes the 2.4 and compares it to the data file coordinates to match the {3, 2.4}.  The starting point is now {3, 2.4}.  Then the program starts over from the user choosing a direction.

I apologize for the novel but I wanted to make sure I was as clear (as mud, I know LOL) as possible.  How do I code the sort and comparisons?  If there is an easier way to complete this assignment, I would be incredibly grateful for any help.  Please keep in mind, I've only been working with Go for about a month and a half.  Please be gentle with complicated code.  LOL  Thank you!

答:
From a design perspective, consider creating a type that encapsulates the information about each county seat (e.g. a struct with the city/town name, latitude, and longitude) since they are logically related.

The code example below shows how you could sort these objects by latitude or longitude using sort.Slice(...), making it easier to find which one is closest in the specified direction.

Hope it helps!

```<code>package main

import "sort"

type CountySeat struct {
  Name     string
  Lat, Lng float64
}

func main() {
  // Pretend we've read these from the data file.
  countySeats := []CountySeat{
    CountySeat{"Alpha", 3.0, 1.0},
    CountySeat{"Bravo", 2.0, 2.0},
    CountySeat{"Charlie", 1.0, 3.0},
  }

  // Sorting by latitude makes it easy to find N/S proximity.
  sort.Slice(countySeats, func(i, j int) bool {
    return countySeats[i].Lat < countySeats[j].Lat;
  })
  // Now countySeats are ordered by increasing latitude...

  // Sorting by longitude makes it easy to find E/W proximity.
  sort.Slice(countySeats, func(i, j int) bool {
    return countySeats[i].Lng < countySeats[j].Lng;
  })
  // Now countySeats are ordered by increasing longitude...

}
</code>```

Title: Sorting and comparing arrays in Go

Body:
From a design perspective, consider creating a type that encapsulates the information about each county seat (e.g. a struct with the city/town name, latitude, and longitude) since they are logically related.

The code example below shows how you could sort these objects by latitude or longitude using sort.Slice(...), making it easier to find which one is closest in the specified direction.

Hope it helps!

package main

import "sort"

type CountySeat struct {
  Name     string
  Lat, Lng float64
}

func main() {
  // Pretend we've read these from the data file.
  countySeats := []CountySeat{
    CountySeat{"Alpha", 3.0, 1.0},
    CountySeat{"Bravo", 2.0, 2.0},
    CountySeat{"Charlie", 1.0, 3.0},
  }

  // Sorting by latitude makes it easy to find N/S proximity.
  sort.Slice(countySeats, func(i, j int) bool {
    return countySeats[i].Lat < countySeats[j].Lat;
  })
  // Now countySeats are ordered by increasing latitude...

  // Sorting by longitude makes it easy to find E/W proximity.
  sort.Slice(countySeats, func(i, j int) bool {
    return countySeats[i].Lng < countySeats[j].Lng;
  })
  // Now countySeats are ordered by increasing longitude...

}


来源: stackexchange

问:
SPWeb.Groups vs SPWeb.AssociatedGroups
I've seen three types of group properties for an SPWeb object - Groups, SiteGroups, AssociatedGroups.

I understand that SiteGroups will fetch all the groups in the current site collection. But what is the difference between Groups and AssociatedGroups. MSDN definition says that Groups will get all the 'cross-site'(!) groups for that web site. AssociatedGroups are fairly easily to understand just from the very name.

So what does Groups return? Can somebody explain me with an example?

答:
Groups return all groups which have security roles assigned to the current site.

AssociatedGroups return all groups visible in the left menu of the People and Group page. Those groups may not have access to the current site (if the security settings do not inherit from parent site). In this case, some of them will not be listed in the Groups property.

To view the difference, in a subsite, create a new group without giving any permission. The group will be visible in the AssociatedGroups and Left menu, but will not be listed in Groups or Site Permissions page.

ContentLicense: CC BY-SA 2.5

Title: SPWeb.Groups vs SPWeb.AssociatedGroups


问:
Intellisense not working in VS Code on Ubuntu
I am running VS Code version 1.17.2 on Ubuntu 16.0.4 on a VMware Player VM in Windows 10. I installed the C++ extension for VS Code. When installing the extension there was a message to say that the extension installed OK but afterwards there was a lot of repeated messages saying something like "failed to update database".

When I type something which is invalid syntax there is no red squiggle and if I press Ctl-Space it just shows "Loading..." but nothing comes. The red flame icon on the status bar shows and I see "Updating Intellisense..." when I hover the mouse over but the icon doesn't ever seem to go away.

If I #include a non existent header, there is no green squiggle but if I save the file, exit VS Code and reopen, them the green squiggle shows on the header but there is no light bulb showing in the left margin.

答:
I had exactly the same problem, running ElementaryOS on VirtualBox. As per this comment (https://github.com/Microsoft/vscode-cpptools/issues/756#issuecomment-303513360) I changed my settings to

```<code>"C_Cpp.intelliSenseEngine": "Tag Parser"
</code>```

And things seems to be working again.

ContentLicense: CC BY-SA 3.0

Body:
I had exactly the same problem, running ElementaryOS on VirtualBox. As per this comment (https://github.com/Microsoft/vscode-cpptools/issues/756#issuecomment-303513360) I changed my settings to

"C_Cpp.intelliSenseEngine": "Tag Parser"

And things seems to be working again.


问:
Colour scale based on how far value is from other cell value
I have a column of targets (C2:C30) and a column of projections (D2:D30).

I've been able to conditionally format the projections to highlight values either above or below target, but I want to expand this into a colour scale to be able to identify more quickly how far from the target my projection is.

For example, if D:D is above 90% of C:C, a green colouring would suffice. 80-90% would be amber, below 80% would be red. In an ideal world, a fully fledged colour scale would be great but at this moment in time I'll be happy with anything more sophisticated than my current above/below setup.

I believe I could use a series of stacked conditional formats but thought there might be a more efficient way of doing this?

答:
You can create your own scale,

Create first rule using something like:

```<code>=C2*1.9<D2
</code>```

Apply this in Cell D2, then apply to D2:D30,

Then create second rule:

```<code>=C2*1.8<D2
</code>```

And so on..

Body:
You can create your own scale,

Create first rule using something like:

=C2*1.9<D2

Apply this in Cell D2, then apply to D2:D30,

Then create second rule:

=C2*1.8<D2

And so on..


问:
How would I get updated position after passing object through event?
I'm working on putting together a point and click game and I need to get the updated position of a moving gameobject in a scene. I'm currently passing the object that is selected with the mouse through an event to another script after the object is clicked on. The object's position is stored from when the object is clicked on, not it's current location, I would like to pass this into the update loop somehow to get an updated position.

I've looked at using member variables to get updates from the update function, but that just seems messy.
Is there a better solution for this or should I just use member variables?

Thanks!

here is the code I'm concerned with

```<code>    void Start()
    {
        RegisterForMouseEvents();
    }

    private void RegisterForMouseEvents()
    {
        var cameraRaycaster = FindObjectOfType<CameraRaycaster>();
        cameraRaycaster.onMouseOverEnemy += OnMouseOverEnemy;
    }

    void OnMouseOverEnemy(EnemyAI enemy)
    {
     // enemy is object passed from delegate
     // that has the EnemyAI script attached.
     // how do I pass enemy into Update() then either
     // back into this method or another method?
    }
</code>```

答:
Use a local variable.</p>

```<code>private EnemyAI myEnemy;

void Start()
{
    RegisterForMouseEvents();
}

private void RegisterForMouseEvents()
{
    var cameraRaycaster = FindObjectOfType<CameraRaycaster>();
    cameraRaycaster.onMouseOverEnemy += OnMouseOverEnemy;
}

void OnMouseOverEnemy(EnemyAI enemy)
{
    myEnemy = enemy;
}

void Update(){
    //log position
    print(myEnemy.transform.position);
}
</code>```

Body:
I'm working on putting together a point and click game and I need to get the updated position of a moving gameobject in a scene. I'm currently passing the object that is selected with the mouse through an event to another script after the object is clicked on. The object's position is stored from when the object is clicked on, not it's current location, I would like to pass this into the update loop somehow to get an updated position.

I've looked at using member variables to get updates from the update function, but that just seems messy.
Is there a better solution for this or should I just use member variables?

Thanks!

here is the code I'm concerned with

    void Start()
    {
        RegisterForMouseEvents();
    }

    private void RegisterForMouseEvents()
    {
        var cameraRaycaster = FindObjectOfType<CameraRaycaster>();
        cameraRaycaster.onMouseOverEnemy += OnMouseOverEnemy;
    }

    void OnMouseOverEnemy(EnemyAI enemy)
    {
     // enemy is object passed from delegate
     // that has the EnemyAI script attached.
     // how do I pass enemy into Update() then either
     // back into this method or another method?
    }

Body:
Use a local variable.

private EnemyAI myEnemy;

void Start()
{
    RegisterForMouseEvents();
}

private void RegisterForMouseEvents()
{
    var cameraRaycaster = FindObjectOfType<CameraRaycaster>();
    cameraRaycaster.onMouseOverEnemy += OnMouseOverEnemy;
}

void OnMouseOverEnemy(EnemyAI enemy)
{
    myEnemy = enemy;
}

void Update(){
    //log position
    print(myEnemy.transform.position);
}


问:
XPath / XQuery: find text in a node, but ignoring content of specific descendant elements
I am trying to find a way to search for a string within nodes, but excluding ythe content of some subelements of those nodes. Plain and simple, I want to search for a string in paragraphs of a text, excluding the footnotes which are children elements of the paragraphs.

For example,

My document being:

```<code><document>
   <p n="1">My text starts here/</p>
   <p n="2">Then it goes on there<footnote>It's not a very long text!</footnote></p>
</document>
</code>```

When I'm searching for "text", I would like the Xpath / XQuery to retrieve the first p element, but not the second one (where "text" is contained only in the footnote subelement).

I have tried the contains() function, but it retrieves both p elements.

Any help would be much appreciated :)

答: /document/p[text()[contains(., 'text')]] should do.

Body:
I am trying to find a way to search for a string within nodes, but excluding ythe content of some subelements of those nodes. Plain and simple, I want to search for a string in paragraphs of a text, excluding the footnotes which are children elements of the paragraphs.

For example,

My document being:

<document>

My text starts here/

Then it goes on there<footnote>It's not a very long text!</footnote>

</document>

When I'm searching for "text", I would like the Xpath / XQuery to retrieve the first p element, but not the second one (where "text" is contained only in the footnote subelement).

I have tried the contains() function, but it retrieves both p elements.

Any help would be much appreciated :)


问:
primary key column needs to be Auto incremented in postgresql
I have created a below table in postgresql:

```<code>create table retail_fact( id serial not null, name text);
</code>```

I have customer table in hive and MySQL and I want to load the data from them to PostgreSQL retail_fact table using Pentaho pdi (connecting through presto).

Also, O want the id to auto-increment in Postgres while I load the table with data from Hive and MySQL (in easier terms. i need an sql query to do the same).

The query is something like below:

```<code>insert into postgresql.rpt.order_fact(

select name from hive.retail.customer_hive
UNION
select name from mysql.retail.customer_mysql

);
</code>```

while i insert the above data for name column into order_fact in postgres, how do i make the id column auto increment?

答:
Your table construct doesn't look much like PostgreSQL...  maybe MS SQL Server or Sybase, but that aside.  If you are using PostgreSQL and are on version 9.x, then a serial implements a sequence/default value behind the scenes.  I think on 10.x it's different, but on 9.x, you could simply hijack the sequence on your insert:

```<code>insert into postgresql.rpt.order_fact
with results as (
  select name from hive.retail.customer_hive
  UNION
  select name from mysql.retail.customer_mysql
)
select
  nextval('retail_fact_id_seq'), name
from results;
</code>```

I'm assuming the CTE is necessary, otherwise the unique sequence values would turn your union into a union all.

Or, better yet (and more portable), specify the field(s) explicitly in your insert:

```<code>insert into postgresql.rpt.order_fact (name)
select name from hive.retail.customer_hive
UNION
select name from mysql.retail.customer_mysql
</code>```

Body:
I have created a below table in postgresql:

create table retail_fact( id serial not null, name text);

I have customer table in hive and MySQL and I want to load the data from them to PostgreSQL retail_fact table using Pentaho pdi (connecting through presto).

Also, O want the id to auto-increment in Postgres while I load the table with data from Hive and MySQL (in easier terms. i need an sql query to do the same).

The query is something like below:

insert into postgresql.rpt.order_fact(

select name from hive.retail.customer_hive
UNION
select name from mysql.retail.customer_mysql

);

while i insert the above data for name column into order_fact in postgres, how do i make the id column auto increment?

Body:
Your table construct doesn't look much like PostgreSQL...  maybe MS SQL Server or Sybase, but that aside.  If you are using PostgreSQL and are on version 9.x, then a serial implements a sequence/default value behind the scenes.  I think on 10.x it's different, but on 9.x, you could simply hijack the sequence on your insert:

insert into postgresql.rpt.order_fact
with results as (
  select name from hive.retail.customer_hive
  UNION
  select name from mysql.retail.customer_mysql
)
select
  nextval('retail_fact_id_seq'), name
from results;

I'm assuming the CTE is necessary, otherwise the unique sequence values would turn your union into a union all.

Or, better yet (and more portable), specify the field(s) explicitly in your insert:

insert into postgresql.rpt.order_fact (name)
select name from hive.retail.customer_hive
UNION
select name from mysql.retail.customer_mysql


问:
How can I use my own data set in sklearn - Python3
I'm new in machine learning and sklearn.
So, I have the following question:

I'm trying to do a linear regression, but I want to use my own data from some .txt file.
I have some data with a table with 3 columns.

Then, I would like to know how can I change this following code, that is an example from http://scikit-learn.org/stable/auto_examples/linear_model/plot_ols.html

Then I changed a bit the code in the example before and I invented some data, is that a correct way to do it? Like use some X and Y like this way. And then I would also to know how in the equation: x_train = x [:2], the [:2] has some influence on my procedure. I didn't really get this part.

```<code>from sklearn import linear_model
import matplotlib.pyplot as plt
from sklearn.metrics import mean_squared_error, r2_score

#X has to be numpy array not list.

x=([0],[1],[2],[3],[4],[5],[6],[7],[8],[9],[10])
y=[5,3,8,3,4,5,5,7,8,9,10]

x_train = x [:2]
x_test = x [2:]

y_train = y[:2]
y_test = y[2:]

regr = linear_model.LinearRegression()
regr.fit (x_train,y_train)

y_pred = regr.predict(x_test)

#coefficient
print('Coefficients: \n', regr.coef_)

#the mean square error
print("Mean squared error: %.2f" % mean_squared_error(y_test, y_pred))
print('Variance score: %.2f' % r2_score(y_test, y_pred))

plt.scatter(x_test, y_test,  color='black')
plt.plot(x_test, y_pred, color='blue', linewidth=3)
plt.axis([0, 20, 0, 20])
plt.show()
</code>```

Thanks a lot!

EDIT 1

With the help I received in this webpage, I tried to make some code, to produce a fit of my own data, but I'm not able to get the correct fit, so if someone has time to help me a bit more or tell me if I'm doing something wrong.

The code I'm using with the pics I'm getting

```<code>import pandas as pd
import numpy as np
from sklearn.model_selection import KFold
from sklearn.model_selection import cross_val_score
from sklearn import linear_model
from sklearn.metrics import mean_squared_error, r2_score
import matplotlib.pyplot as plt

data = pd.read_csv('data.txt')
#x = data[['col1','col2']]
x = data[['col1']]
y = data['col3']

#convert to array to fit the model
x=np.asarray(x)
y=np.asarray(y)

# define the KFolds
kf = KFold(n_splits=2)

#define the model
regr = linear_model.LinearRegression()

# use cross validation and return the r2 score for each Fold
#if you want to return other scores than r2, just change the scoring in cross_val_score
scores = cross_val_score(regr, x, y, cv= kf, scoring= 'r2')

print(scores)

for train_index, test_index in kf.split(x):
  print("TRAIN:", train_index, "TEST:", test_index)
  X_train, X_test = x[train_index], x[test_index]
  y_train, y_test = y[train_index], y[test_index]

plt.scatter (X_test, y_test)
plt.show()
</code>```

I'm here putting a picture of what looks like my data and what I get from TRAIN AND TEST

Then I did some fit procedure, but I'm not sure if it's correct:

```<code>regr.fit (X_train, y_train)
y_pred = regr.predict(X_test)
print(y_pred)
plt.scatter(X_test, y_test,  color='black')
plt.plot(X_test, y_pred, color='blue', linewidth=3)
plt.show()
</code>```

And I get a completely strange fit.

I don't understand why I get it, if when i did this using MINUIT, my fit worked. So, if someone has some hints to help me.

Why apparently the program is not using my data from "y" to do TRAIN or TEST samples?

My data can be taked here: https://www.dropbox.com/sh/nbbsc0fqznkwxvt/AAD-u6lM4orJOGrgIyz0o8B9a?dl=0

For me the only important is col1 and col3, the col2 should be ignored. Then I want make a fit in this data and extract the value of my fit. I know it's a line that fits this data.

Thank you!

答:
First of all, the main reason that you want to split the data and use a part of the data to train the model and another part to evaluate it, is to avoid overfitting. Usually, we use KFolds or LOO(leave one out) to perform cross validation.

Here is an example using 30 samples, 3 variables and cross validation with KFolds.

```<code>import numpy as np
from sklearn.model_selection import KFold
from sklearn.model_selection import cross_val_score
from sklearn import linear_model

#create artificial data with 30 lines (samples) and 3 columns (variables)
x = np.random.rand(30,3)

#create the target variable y
y = range(30)

# convert the list to numpy array (this is needed for fit method of sklearn)
y = np.asarray(y)

# define the KFolds (3 folds in this example)
kf = KFold(n_splits=3)

#define the model
regr = linear_model.LinearRegression()

# use cross validation and return the r2 score for each Fold (here we have 3).
#if you want to return other scores than r2, just change the scoring in cross_val_score.
scores = cross_val_score(regr, x, y, cv= kf, scoring= 'r2')

print(scores)
</code>```

Results:

Here you can see the r2 score of the model for each fold. So we splitted the data 3 times and we used 3 different training data to get these values. This is done automatically by sklearn inside cross_val_score method.

```<code> array([-30.36184326,  -0.4149778 , -28.89110233])
</code>```

To understand what KFold does you can print the training and testing indices using:

```<code>for train_index, test_index in kf.split(x):
   print("TRAIN:", train_index, "TEST:", test_index)
   X_train, X_test = x[train_index], x[test_index]
   y_train, y_test = y[train_index], y[test_index]
</code>```

Results:

```<code>('TRAIN:', array([10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26,
   27, 28, 29]), 'TEST:', array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]))
('TRAIN:', array([ 0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 20, 21, 22, 23, 24, 25, 26,
   27, 28, 29]), 'TEST:', array([10, 11, 12, 13, 14, 15, 16, 17, 18, 19]))
('TRAIN:', array([ 0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12, 13, 14, 15, 16,
   17, 18, 19]), 'TEST:', array([20, 21, 22, 23, 24, 25, 26, 27, 28, 29]))
</code>```

Now, you can see that for the 1st Fold we used the samples: 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29.

Next, for the second fold we used the samples: 0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29.

Note: these numbers are the indices of the x data. E.g. 2 means the 3rd sample(line). In python we count from 0.
As you can see, we do not use the exact same data (samples) in each Fold.

Hope this helps.

EDIT 1

To answer your question about loading the txt data. Let's suppose that you have a txt file with 3 columns. The first 2 columns are the features and the last column is the y (target).

In this case, you can do the following using pandas:

```<code>import pandas as pd
import numpy as np

data = pd.read_csv('data.txt')
x = data[['col1','col2']]
y = data['col3']

#convert to array to fit the model
x=np.asarray(x)
y=np.asarray(y)
</code>```

The txt is here: https://ufile.io/eb5xl (choose slow download).

EDIT 2

This is only for visualization purposes. I do not split the data. I use all the data to fit the model and then I predict on the same data. Then I plot the predicted values.

```<code>import pandas as pd
import numpy as np
from sklearn.model_selection import KFold
from sklearn.model_selection import cross_val_predict
from sklearn import linear_model
import matplotlib.pyplot as plt

data = pd.read_csv('data.txt')

x = data[['col1']]
y = data['col3']

#convert to array to fit the model
x=np.asarray(x)
y=np.asarray(y)

regr = linear_model.LinearRegression()
regr.fit(x, y)

y_predicted = regr.predict(x)

plt.scatter(x, y,  color='black')
plt.plot(x, y_predicted, color='blue', linewidth=3)

plt.xticks(())
plt.yticks(())

plt.show()
</code>```

Results:

It seems that the data dont follow a linear pattern. Other models should be used (e.g. exponential fitting)

Body:
I'm new in machine learning and sklearn.
So, I have the following question:

I'm trying to do a linear regression, but I want to use my own data from some .txt file.
I have some data with a table with 3 columns.

Then, I would like to know how can I change this following code, that is an example from http://scikit-learn.org/stable/auto_examples/linear_model/plot_ols.html

Then I changed a bit the code in the example before and I invented some data, is that a correct way to do it? Like use some X and Y like this way. And then I would also to know how in the equation: x_train = x [:2], the [:2] has some influence on my procedure. I didn't really get this part.

from sklearn import linear_model
import matplotlib.pyplot as plt
from sklearn.metrics import mean_squared_error, r2_score

#X has to be numpy array not list.

x=([0],[1],[2],[3],[4],[5],[6],[7],[8],[9],[10])
y=[5,3,8,3,4,5,5,7,8,9,10]

x_train = x [:2]
x_test = x [2:]

y_train = y[:2]
y_test = y[2:]

regr = linear_model.LinearRegression()
regr.fit (x_train,y_train)

y_pred = regr.predict(x_test)

#coefficient
print('Coefficients: \n', regr.coef_)

#the mean square error
print("Mean squared error: %.2f" % mean_squared_error(y_test, y_pred))
print('Variance score: %.2f' % r2_score(y_test, y_pred))

plt.scatter(x_test, y_test,  color='black')
plt.plot(x_test, y_pred, color='blue', linewidth=3)
plt.axis([0, 20, 0, 20])
plt.show()

Thanks a lot!

EDIT 1

With the help I received in this webpage, I tried to make some code, to produce a fit of my own data, but I'm not able to get the correct fit, so if someone has time to help me a bit more or tell me if I'm doing something wrong.

The code I'm using with the pics I'm getting

import pandas as pd
import numpy as np
from sklearn.model_selection import KFold
from sklearn.model_selection import cross_val_score
from sklearn import linear_model
from sklearn.metrics import mean_squared_error, r2_score
import matplotlib.pyplot as plt

data = pd.read_csv('data.txt')
#x = data[['col1','col2']]
x = data[['col1']]
y = data['col3']

#convert to array to fit the model
x=np.asarray(x)
y=np.asarray(y)

# define the KFolds
kf = KFold(n_splits=2)

#define the model
regr = linear_model.LinearRegression()

# use cross validation and return the r2 score for each Fold
#if you want to return other scores than r2, just change the scoring in cross_val_score
scores = cross_val_score(regr, x, y, cv= kf, scoring= 'r2')

print(scores)

for train_index, test_index in kf.split(x):
  print("TRAIN:", train_index, "TEST:", test_index)
  X_train, X_test = x[train_index], x[test_index]
  y_train, y_test = y[train_index], y[test_index]

plt.scatter (X_test, y_test)
plt.show()

I'm here putting a picture of what looks like my data and what I get from TRAIN AND TEST

Then I did some fit procedure, but I'm not sure if it's correct:

regr.fit (X_train, y_train)
y_pred = regr.predict(X_test)
print(y_pred)
plt.scatter(X_test, y_test,  color='black')
plt.plot(X_test, y_pred, color='blue', linewidth=3)
plt.show()

And I get a completely strange fit.

I don't understand why I get it, if when i did this using MINUIT, my fit worked. So, if someone has some hints to help me.

Why apparently the program is not using my data from "y" to do TRAIN or TEST samples?

My data can be taked here: https://www.dropbox.com/sh/nbbsc0fqznkwxvt/AAD-u6lM4orJOGrgIyz0o8B9a?dl=0

For me the only important is col1 and col3, the col2 should be ignored. Then I want make a fit in this data and extract the value of my fit. I know it's a line that fits this data.

Thank you!

Body:
First of all, the main reason that you want to split the data and use a part of the data to train the model and another part to evaluate it, is to avoid overfitting. Usually, we use KFolds or LOO(leave one out) to perform cross validation.

Here is an example using 30 samples, 3 variables and cross validation with KFolds.

import numpy as np
from sklearn.model_selection import KFold
from sklearn.model_selection import cross_val_score
from sklearn import linear_model

#create artificial data with 30 lines (samples) and 3 columns (variables)
x = np.random.rand(30,3)

#create the target variable y
y = range(30)

# convert the list to numpy array (this is needed for fit method of sklearn)
y = np.asarray(y)

# define the KFolds (3 folds in this example)
kf = KFold(n_splits=3)

#define the model
regr = linear_model.LinearRegression()

# use cross validation and return the r2 score for each Fold (here we have 3).
#if you want to return other scores than r2, just change the scoring in cross_val_score.
scores = cross_val_score(regr, x, y, cv= kf, scoring= 'r2')

print(scores)

Results:

Here you can see the r2 score of the model for each fold. So we splitted the data 3 times and we used 3 different training data to get these values. This is done automatically by sklearn inside cross_val_score method.

 array([-30.36184326,  -0.4149778 , -28.89110233])

To understand what KFold does you can print the training and testing indices using:

for train_index, test_index in kf.split(x):
   print("TRAIN:", train_index, "TEST:", test_index)
   X_train, X_test = x[train_index], x[test_index]
   y_train, y_test = y[train_index], y[test_index]

Results:

('TRAIN:', array([10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26,
   27, 28, 29]), 'TEST:', array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]))
('TRAIN:', array([ 0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 20, 21, 22, 23, 24, 25, 26,
   27, 28, 29]), 'TEST:', array([10, 11, 12, 13, 14, 15, 16, 17, 18, 19]))
('TRAIN:', array([ 0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12, 13, 14, 15, 16,
   17, 18, 19]), 'TEST:', array([20, 21, 22, 23, 24, 25, 26, 27, 28, 29]))

Now, you can see that for the 1st Fold we used the samples: 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29.

Next, for the second fold we used the samples: 0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29.

Note: these numbers are the indices of the x data. E.g. 2 means the 3rd sample(line). In python we count from 0.
As you can see, we do not use the exact same data (samples) in each Fold.

Hope this helps.

EDIT 1

To answer your question about loading the txt data. Let's suppose that you have a txt file with 3 columns. The first 2 columns are the features and the last column is the y (target).

In this case, you can do the following using pandas:

import pandas as pd
import numpy as np

data = pd.read_csv('data.txt')
x = data[['col1','col2']]
y = data['col3']

#convert to array to fit the model
x=np.asarray(x)
y=np.asarray(y)

The txt is here: https://ufile.io/eb5xl (choose slow download).

EDIT 2

This is only for visualization purposes. I do not split the data. I use all the data to fit the model and then I predict on the same data. Then I plot the predicted values.

import pandas as pd
import numpy as np
from sklearn.model_selection import KFold
from sklearn.model_selection import cross_val_predict
from sklearn import linear_model
import matplotlib.pyplot as plt

data = pd.read_csv('data.txt')

x = data[['col1']]
y = data['col3']

#convert to array to fit the model
x=np.asarray(x)
y=np.asarray(y)

regr = linear_model.LinearRegression()
regr.fit(x, y)

y_predicted = regr.predict(x)

plt.scatter(x, y,  color='black')
plt.plot(x, y_predicted, color='blue', linewidth=3)

plt.xticks(())
plt.yticks(())

plt.show()

Results:

It seems that the data dont follow a linear pattern. Other models should be used (e.g. exponential fitting)


问:
Need proc variable to be written to my talb
I have a table I have created to insert the results of my proc and it is running great.  I would like to add a column to my table called objectnamee and have it insert the objectname I used to run the proc.

```<code>create table DatasetMapping
(
Name nvarchar(257),
Type nvarchar(16),
updated nvarchar(7),
Selected nvarchar(8),
Column sysname,
OjectName nvarchar(257)---need to add to table

);

EXEC [dbo].[Repotingdatasets] @object ='dbo.PositionReport_Quote_V3_2016';
</code>```

I would like to have 'dbo.PositionReport_Quote_V3_2016' insert into my table as objectname.  Below is the proc I am using.

```<code>SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[Repotingdatasets]
AS
DECLARE @object NVARCHAR(257)

 INSERT INTO DatasetMapping
  EXEC sp_epends  @objname = @object
</code>```

答:
Alter the table

```<code>alter table DatasetMapping
add OjectName nvarchar(257) null
go
</code>```

Then insert your data however you want. Though, i find your current method odd

ContentLicense: CC BY-SA 4.0

Body:
I have a table I have created to insert the results of my proc and it is running great.  I would like to add a column to my table called objectnamee and have it insert the objectname I used to run the proc.

create table DatasetMapping
(
Name nvarchar(257),
Type nvarchar(16),
updated nvarchar(7),
Selected nvarchar(8),
Column sysname,
OjectName nvarchar(257)---need to add to table

);

EXEC [dbo].[Repotingdatasets] @object ='dbo.PositionReport_Quote_V3_2016';

I would like to have 'dbo.PositionReport_Quote_V3_2016' insert into my table as objectname.  Below is the proc I am using.

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[Repotingdatasets]
AS
DECLARE @object NVARCHAR(257)

 INSERT INTO DatasetMapping
  EXEC sp_epends  @objname = @object

Body:
Alter the table

alter table DatasetMapping
add OjectName nvarchar(257) null
go

Then insert your data however you want. Though, i find your current method odd


问:
Excluding lines conditional upon multiple fields with awk
I have a pretty simple awk question:

I have the following file test1.txt

```<code>ids op  count
id1 op1 1
id7 op1 2
id13    op1 3
id4 op1 4
id10    op1 5
id11    op2 1
id2 op2 2
id8 op2 3
id14    op2 4
id5 op2 5
</code>```

I would like to exclude certain rows based on the op and count columns. For example exclude anything in op2 that has a count from 2 to 5, finally giving me the following test2.txt:

```<code>ids op  count
id1 op1 1
id7 op1 2
id13    op1 3
id4 op1 4
id10    op1 5
id11    op2 1
id5 op2 5
</code>```

I'm looking for an awk code that would do something like:

```<code>awk '{
    if($2 ~ /op2/ && $3>1 && $3<5)
    skip
    else
    print $0
    }' test1.txt > test2.txt
</code>```

This code actually works. But I appreciate any suggestions for 1 liners.

Many thanks!

答:
It's as simple as this:

```<code>awk 'NR==1 || !($2=="op2" && $3<5 && $3>1)' test.file
</code>```

Note that an awk program basically has the following form:

```<code>CONDITION { ACTIONS }
</code>```

where the default action is print. That means if condition expands to true and you specify no action, awk will print the input line.

The logic means:

print all lines which don't match both of the following conditions:

op==op2

2 < count >= 5

Body:
I have a pretty simple awk question:

I have the following file test1.txt

ids op  count
id1 op1 1
id7 op1 2
id13    op1 3
id4 op1 4
id10    op1 5
id11    op2 1
id2 op2 2
id8 op2 3
id14    op2 4
id5 op2 5

I would like to exclude certain rows based on the op and count columns. For example exclude anything in op2 that has a count from 2 to 5, finally giving me the following test2.txt:

ids op  count
id1 op1 1
id7 op1 2
id13    op1 3
id4 op1 4
id10    op1 5
id11    op2 1
id5 op2 5

I'm looking for an awk code that would do something like:

awk '{
    if($2 ~ /op2/ && $3>1 && $3<5)
    skip
    else
    print $0
    }' test1.txt > test2.txt

This code actually works. But I appreciate any suggestions for 1 liners.

Many thanks!

Body:
It's as simple as this:

awk 'NR==1 || !($2=="op2" && $3<5 && $3>1)' test.file

Note that an awk program basically has the following form:

CONDITION { ACTIONS }

where the default action is print. That means if condition expands to true and you specify no action, awk will print the input line.

The logic means:

print all lines which don't match both of the following conditions:

op==op2

2 < count >= 5


问:
AdMob Rewarded Video ERROR_CODE_NO_FILL for test ad
My rewarded video was working 2 weeks ago. I have changed nothing, my code is the same. Right now, when I try to load rewarded video ad, it gives me ERROR_CODE_NO_FILL. I know that it means there is no available ad for my app. But I am on the test device, I simply need a test ad. I created a new rewarded video ad then tried to see a test ad with its ID but the result is the same; no test ad. This system was working for almost 3 months... I was going to publish my app but now I have this problem. Any ideas how I can solve this problem ?

in OnCreate method:

```<code>MobileAds.initialize(this, "my app id");
RVA = MobileAds.getRewardedVideoAdInstance(this);
RVA.setRewardedVideoAdListener(this);
loadRewardedAd();
</code>```

in loadRewardedAd method:

```<code>RVA.loadAd("my ad id",
            new AdRequest.Builder().addTestDevice("myphoneid")
                    .build());
</code>```

I show rewarded ad as:

```<code>if (RVA.isLoaded()) {
        RVA.show();
}
</code>```

Problem is solved by AdMob team. Everything is normal right now. There was a problem with AdMob system.

答:
I have this also, and the support acknowledge that they have issues serving interstitial and banner ads

https://groups.google.com/forum/#!msg/google-admob-ads-sdk/-jOxbj7AZ_c/A79JBFPiCQAJ

so it looks like its happening at there end

Body:
My rewarded video was working 2 weeks ago. I have changed nothing, my code is the same. Right now, when I try to load rewarded video ad, it gives me ERROR_CODE_NO_FILL. I know that it means there is no available ad for my app. But I am on the test device, I simply need a test ad. I created a new rewarded video ad then tried to see a test ad with its ID but the result is the same; no test ad. This system was working for almost 3 months... I was going to publish my app but now I have this problem. Any ideas how I can solve this problem ?

in OnCreate method:

MobileAds.initialize(this, "my app id");
RVA = MobileAds.getRewardedVideoAdInstance(this);
RVA.setRewardedVideoAdListener(this);
loadRewardedAd();

in loadRewardedAd method:

RVA.loadAd("my ad id",
            new AdRequest.Builder().addTestDevice("myphoneid")
                    .build());

I show rewarded ad as:

if (RVA.isLoaded()) {
        RVA.show();
}

Problem is solved by AdMob team. Everything is normal right now. There was a problem with AdMob system.


问:
phpMailer plesk centos multiple IP setup
I have a Plesk centos 6 cloud server that runs two domains on two different IPs. One of the domains has subdomains which send emails out via phpMailer, through a designated smtp server, in the case at hand, gmail.

Although I don't believe the problem lies or can be mitigated at the level of executing phpMailer, here is an example of that to demonstrate:

```<code>$mail = new PHPMailer;
$mail->SMTPDebug = false;
$mail->isSMTP();
$mail->Host = "smtp.gmail.com";
$mail->SMTPAuth = true;
$mail->CharSet = 'UTF-8';
$mail->Username = $GLOBALS['gmail'];
$mail->Password = $GLOBALS['email_password'];
$mail->SMTPSecure = "tls";
$mail->Port = 587;
$mail->From = $GLOBALS['gmail'];
$mail->FromName = $GLOBALS['sender'];
$mail->addReplyTo($GLOBALS['gmail'], "Reply");
$mail->isHTML(true);
$mail->addAddress($this->data['Email']);
$mail->Subject = "...";
$mail->Body = "...";
$mail->Send();
</code>```

Now I see within the Smart Network Data Service at postmaster.live.com that both IPs have been blocked due to evidence of spamming.

Investigating I found what I suspect is the problem - that in the Received part of the email header, the sending subdomain is identified correctly by name, but the sending IP address is that of the other domain. Like this:

Received: from correct subdomain.domain.com (incorrect reverseDNS domain [incorrect IP])  by smtp.gmail.com ...

It appears that phpMailer has connected to smtp.gmail.com from the wrong IP address, with the result that the reverseDNS lookup resolves to that of the other domain – and this is likely what Microsoft have picked up on.

Within Plesk (Tools & Tettings -> IP Addresses), the IP of what should be the correct domain is listed first, and is bold, suggesting that should be the default.

UPDATE:
Now I tried:

```<code>        $options = array(
            'socket' => array(
                'bindto' => '**the required IP**',
            ),
        );
        $socket_context = stream_context_create($options);
        $this->smtp_conn = stream_socket_client(
                        $host . ":" . $port, $errno, $errstr, $timeout, STREAM_CLIENT_CONNECT, $socket_context
        );
</code>```

This produced the following error, which narrows the problem specifically to not being able to bind the IP associated with the domain:

PHP Warning:  stream_socket_client(): failed to bind to 'domainIP:587', system said: Permission denied

Any help much appreciated.

答:
Fortunately a solution was found - while placing the bindto parameter within the options object passed to stream_context_create within PHPMailer's connect method definition was not permitted by PHP for an unknown reason - setting that directly when calling the method did work, like this:</p>

```<code>    $mail->SMTPOptions = array(
            'socket' => array(
            'bindto' => "specificIP:0",
            ),
    );
</code>```

Body:
I have a Plesk centos 6 cloud server that runs two domains on two different IPs. One of the domains has subdomains which send emails out via phpMailer, through a designated smtp server, in the case at hand, gmail.

Although I don't believe the problem lies or can be mitigated at the level of executing phpMailer, here is an example of that to demonstrate:

$mail = new PHPMailer;
$mail->SMTPDebug = false;
$mail->isSMTP();
$mail->Host = "smtp.gmail.com";
$mail->SMTPAuth = true;
$mail->CharSet = 'UTF-8';
$mail->Username = $GLOBALS['gmail'];
$mail->Password = $GLOBALS['email_password'];
$mail->SMTPSecure = "tls";
$mail->Port = 587;
$mail->From = $GLOBALS['gmail'];
$mail->FromName = $GLOBALS['sender'];
$mail->addReplyTo($GLOBALS['gmail'], "Reply");
$mail->isHTML(true);
$mail->addAddress($this->data['Email']);
$mail->Subject = "...";
$mail->Body = "...";
$mail->Send();

Now I see within the Smart Network Data Service at postmaster.live.com that both IPs have been blocked due to evidence of spamming.

Investigating I found what I suspect is the problem - that in the Received part of the email header, the sending subdomain is identified correctly by name, but the sending IP address is that of the other domain. Like this:

Received: from correct subdomain.domain.com (incorrect reverseDNS domain [incorrect IP])  by smtp.gmail.com ...

It appears that phpMailer has connected to smtp.gmail.com from the wrong IP address, with the result that the reverseDNS lookup resolves to that of the other domain – and this is likely what Microsoft have picked up on.

Within Plesk (Tools & Tettings -> IP Addresses), the IP of what should be the correct domain is listed first, and is bold, suggesting that should be the default.

UPDATE:
Now I tried:

        $options = array(
            'socket' => array(
                'bindto' => '**the required IP**',
            ),
        );
        $socket_context = stream_context_create($options);
        $this->smtp_conn = stream_socket_client(
                        $host . ":" . $port, $errno, $errstr, $timeout, STREAM_CLIENT_CONNECT, $socket_context
        );

This produced the following error, which narrows the problem specifically to not being able to bind the IP associated with the domain:

PHP Warning:  stream_socket_client(): failed to bind to 'domainIP:587', system said: Permission denied

Any help much appreciated.

Body:
Fortunately a solution was found - while placing the bindto parameter within the options object passed to stream_context_create within PHPMailer's connect method definition was not permitted by PHP for an unknown reason - setting that directly when calling the method did work, like this:

    $mail->SMTPOptions = array(
            'socket' => array(
            'bindto' => "specificIP:0",
            ),
    );


问:
Reset CSS badge content after ajax call
I have a page which contains some navigation tabs.  If there is a notification for that tab a badge is displayed.  When the tab is in focus, I want an ajax call to make a server request and if the response is successful, I want the badge to be reset to zero.  I can display the badge and the ajax call returns successfully (I have not included this in the code below) and then when I try to set the data attribute for the tab, the value doesn't change.

The relevant code is as follows:

```<code><div class="container-fluid">
    <br/>
    <div class="col-sm-10">
        <div class="panel with-nav-tabs panel-tab-block">
            <div class="panel-heading">
                <ul class="nav nav-tabs">
                    <li class="active">
                        <a data-toggle="tab" class="" href="#projects-tab">Projects</a>
                    </li>
                    <li>
                        <a data-toggle="tab" id="forum-notification-badge" class="notification-badge"
                        data-notification-badge="1" href="#forum-tab">Forum</a>
                    </li>
                </ul>
            </div>
            <div class="panel-body">
                <div class="tab-content">
                    <div id="projects-tab" class="tab-pane fade in active">
                        <div class="row">

                                <div class="col-sm-12">
                                    <div class="panel with-nav-tabs panel-tab-block">
                                        <h1>
                                            Projects
                                        </h1>

                                    </div>
                                </div>
                        </div>
                        <div class="row">
                            <div class="spacer-sml"></div>
                        </div>
                        <div class="row">
                            <div class="spacer-sml"></div>
                        </div>
                    </div>
                    <div id="forum-tab" class="tab-pane fade">
                        <div class="tab-block-content forum-posts">
                            <div class="">
                                <div class="col-sm-12">
                                    <h1>
                                        Forum
                                    </h1>
                                </div>

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

JQuery:

```<code>jQuery(document).ready(function( $ ) {

    $('#forum-notification-badge').on("focus", function() {
        var self = $(this);

        //Do ajax call if success reset the badge to zero
        self.data("notification-badge","0");
        console.log("set badge to zero");

    });

});
</code>```

css:

```<code>.nav {
    border: 1px;
    border-color: #2f70b1;
}
.nav-bar {
    margin-bottom: 0px !important;
}
.navbar-default {
    background-color: #1d3c5c;
    border-color: #000000;
    font-family: 'Open Sans', 'Helvetica Neue', Arial, sans-serif;
    -webkit-transition: all 0.35s;
    -moz-transition: all 0.35s;
    transition: all 0.35s;
    margin-bottom: 0px !important;
    border-radius: 0px;
}

.navbar-default .navbar-header .navbar-brand {
    color: #777;
    font-family: 'Open Sans', 'Helvetica Neue', Arial, sans-serif;
    font-weight: 700;
    text-transform: uppercase;
}

.navbar-default .navbar-header .navbar-brand:hover, .navbar-default .navbar-header .navbar-brand:focus{
    color: #777;
}

.navbar-default .navbar-header .navbar-toggle {
    font-weight: 700;
    font-size: 12px;
    color: #222222;
    text-transform: uppercase;
}

.navbar-default .nav>li>a, .navbar-default .nav>li>a:focus {
    text-transform: uppercase;
    font-weight: 700;
    font-size: 13px;
    color: #222222;
}

.navbar-default .nav>li>a:hover, .navbar-default .nav>li>a:focus:hover {

}

.navbar-default .nav>li.active>a, .navbar-default .nav>li.active>a:focus{
    color: #F05F40 !important;
    background-color: transparent;
}

.navbar-default .nav>li.active>a:hover, .navbar-default .nav>li.active>a:focus:hover{
    background-color: #1d3c5c;
}

@media ( min-width : 768px) {
    .navbar-default {
        background-color: #1d3c5c;

    }
    .navbar-default .navbar-header .navbar-brand {
        color: #ddd;
    }
    .navbar-default .navbar-header .navbar-brand:hover, .navbar-default .navbar-header .navbar-brand:focus
        {
        color: white;
    }
    .navbar-default .nav>li>a, .navbar-default .nav>li>a:focus {
        color: #ddd;
    }
    .navbar-default .nav>li>a:hover, .navbar-default .nav>li>a:focus:hover {
        color: white;
    }
    .navbar-default.affix {
        background-color: white;

    }
    .navbar-default.affix .navbar-header .navbar-brand {
        color: #F05F40;
        font-size: 14px;
    }
    .navbar-default.affix .navbar-header .navbar-brand:hover,
        .navbar-default.affix .navbar-header .navbar-brand:focus {
        color: #eb3812;
    }
    .navbar-default.affix .nav>li>a, .navbar-default.affix .nav>li>a:focus {
        color: #222222;
    }
    .navbar-default.affix .nav>li>a:hover, .navbar-default.affix .nav>li>a:focus:hover
        {
        color: #F05F40;
    }
}

.navbar-default .navbar-nav>li>a:focus, .navbar-default .navbar-nav>li>a:hover {
    background-color: #286090;
}
.panel.with-nav-tabs.panel-tab-block{
    box-shadow: none;
    -moz-box-shadow: none;
    -webkit-box-shadow: none;
}

.with-nav-tabs.panel-tab-block .nav-tabs > li > a,
.with-nav-tabs.panel-tab-block .nav-tabs > li > a:hover,
.with-nav-tabs.panel-tab-block .nav-tabs > li > a:focus {
    color: #ffffff;
    background-color: #999999;
}
.with-nav-tabs.panel-tab-block .nav-tabs > .open > a,
.with-nav-tabs.panel-tab-block .nav-tabs > .open > a:hover,
.with-nav-tabs.panel-tab-block .nav-tabs > .open > a:focus,
.with-nav-tabs.panel-tab-block .nav-tabs > li > a:hover,
.with-nav-tabs.panel-tab-block .nav-tabs > li > a:focus {
    color: #fff;
    background-color: #666666 ;

}
.with-nav-tabs.panel-tab-block .nav-tabs > li.active > a,
.with-nav-tabs.panel-tab-block .nav-tabs > li.active > a:hover,
.with-nav-tabs.panel-tab-block .nav-tabs > li.active > a:focus {
    color: #fff;
    background-color: #2f70b1;
    border-color: #2f70b1;
}
.with-nav-tabs.panel-tab-block .nav-tabs > li.dropdown .dropdown-menu {
    background-color: #428bca;
    border-color: #3071a9;
}
.with-nav-tabs.panel-tab-block .nav-tabs > li.dropdown .dropdown-menu > li > a {
    color: #fff;
}
.with-nav-tabs.panel-tab-block .nav-tabs > li.dropdown .dropdown-menu > li > a:hover,
.with-nav-tabs.panel-tab-block .nav-tabs > li.dropdown .dropdown-menu > li > a:focus {
    background-color: #3071a9;
}
.with-nav-tabs.panel-tab-block .nav-tabs > li.dropdown .dropdown-menu > .active > a,
.with-nav-tabs.panel-tab-block .nav-tabs > li.dropdown .dropdown-menu > .active > a:hover,
.with-nav-tabs.panel-tab-block .nav-tabs > li.dropdown .dropdown-menu > .active > a:focus {
    background-color: #4a9fe9;
}

.tab-block-content {
    color: #202020;
}

.notification-badge {
    position:relative;
    padding-right: 1em;
}

.notification-badge[data-notification-badge]:after {
   content:attr(data-notification-badge);
   position:absolute;
   top:-0.75em;
   right:-0.75em;
   font-size:0.75em;
   background:red;
   color:white;
   width:1.5em;
   height:1.5em;
   text-align:center;
   line-height:1.5em;
   border-radius:50%;
   box-shadow:0 0 1px #333;
}
</code>```

I have also created a jsfiddle

答:
The .data() method only updates an internal variable jQuery stores and not the HTML itself, you will need to use the .attr() method instead.

Code Snippet Demonstration:

jQuery(document).ready(function($) {

  $('#forum-notification-badge').on("focus", function() {
    var self = $(this);

    //Do ajax call if success reset the badge to zero
    self.attr("data-notification-badge", "0");
    console.log("set badge to zero");

  });

});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.nav {
  border: 1px;
  border-color: #2f70b1;
}

.nav-bar {
  margin-bottom: 0px !important;
}

.navbar-default {
  background-color: #1d3c5c;
  border-color: #000000;
  font-family: 'Open Sans', 'Helvetica Neue', Arial, sans-serif;
  -webkit-transition: all 0.35s;
  -moz-transition: all 0.35s;
  transition: all 0.35s;
  margin-bottom: 0px !important;
  border-radius: 0px;
}

.navbar-default .navbar-header .navbar-brand {
  color: #777;
  font-family: 'Open Sans', 'Helvetica Neue', Arial, sans-serif;
  font-weight: 700;
  text-transform: uppercase;
}

.navbar-default .navbar-header .navbar-brand:hover,
.navbar-default .navbar-header .navbar-brand:focus {
  color: #777;
}

.navbar-default .navbar-header .navbar-toggle {
  font-weight: 700;
  font-size: 12px;
  color: #222222;
  text-transform: uppercase;
}

.navbar-default .nav>li>a,
.navbar-default .nav>li>a:focus {
  text-transform: uppercase;
  font-weight: 700;
  font-size: 13px;
  color: #222222;
}

.navbar-default .nav>li>a:hover,
.navbar-default .nav>li>a:focus:hover {}

.navbar-default .nav>li.active>a,
.navbar-default .nav>li.active>a:focus {
  color: #F05F40 !important;
  background-color: transparent;
}

.navbar-default .nav>li.active>a:hover,
.navbar-default .nav>li.active>a:focus:hover {
  background-color: #1d3c5c;
}

@media ( min-width: 768px) {
  .navbar-default {
    background-color: #1d3c5c;
  }
  .navbar-default .navbar-header .navbar-brand {
    color: #ddd;
  }
  .navbar-default .navbar-header .navbar-brand:hover,
  .navbar-default .navbar-header .navbar-brand:focus {
    color: white;
  }
  .navbar-default .nav>li>a,
  .navbar-default .nav>li>a:focus {
    color: #ddd;
  }
  .navbar-default .nav>li>a:hover,
  .navbar-default .nav>li>a:focus:hover {
    color: white;
  }
  .navbar-default.affix {
    background-color: white;
  }
  .navbar-default.affix .navbar-header .navbar-brand {
    color: #F05F40;
    font-size: 14px;
  }
  .navbar-default.affix .navbar-header .navbar-brand:hover,
  .navbar-default.affix .navbar-header .navbar-brand:focus {
    color: #eb3812;
  }
  .navbar-default.affix .nav>li>a,
  .navbar-default.affix .nav>li>a:focus {
    color: #222222;
  }
  .navbar-default.affix .nav>li>a:hover,
  .navbar-default.affix .nav>li>a:focus:hover {
    color: #F05F40;
  }
}

.navbar-default .navbar-nav>li>a:focus,
.navbar-default .navbar-nav>li>a:hover {
  background-color: #286090;
}

.panel.with-nav-tabs.panel-tab-block {
  box-shadow: none;
  -moz-box-shadow: none;
  -webkit-box-shadow: none;
}

.with-nav-tabs.panel-tab-block .nav-tabs>li>a,
.with-nav-tabs.panel-tab-block .nav-tabs>li>a:hover,
.with-nav-tabs.panel-tab-block .nav-tabs>li>a:focus {
  color: #ffffff;
  background-color: #999999;
}

.with-nav-tabs.panel-tab-block .nav-tabs>.open>a,
.with-nav-tabs.panel-tab-block .nav-tabs>.open>a:hover,
.with-nav-tabs.panel-tab-block .nav-tabs>.open>a:focus,
.with-nav-tabs.panel-tab-block .nav-tabs>li>a:hover,
.with-nav-tabs.panel-tab-block .nav-tabs>li>a:focus {
  color: #fff;
  background-color: #666666;
}

.with-nav-tabs.panel-tab-block .nav-tabs>li.active>a,
.with-nav-tabs.panel-tab-block .nav-tabs>li.active>a:hover,
.with-nav-tabs.panel-tab-block .nav-tabs>li.active>a:focus {
  color: #fff;
  background-color: #2f70b1;
  border-color: #2f70b1;
}

.with-nav-tabs.panel-tab-block .nav-tabs>li.dropdown .dropdown-menu {
  background-color: #428bca;
  border-color: #3071a9;
}

.with-nav-tabs.panel-tab-block .nav-tabs>li.dropdown .dropdown-menu>li>a {
  color: #fff;
}

.with-nav-tabs.panel-tab-block .nav-tabs>li.dropdown .dropdown-menu>li>a:hover,
.with-nav-tabs.panel-tab-block .nav-tabs>li.dropdown .dropdown-menu>li>a:focus {
  background-color: #3071a9;
}

.with-nav-tabs.panel-tab-block .nav-tabs>li.dropdown .dropdown-menu>.active>a,
.with-nav-tabs.panel-tab-block .nav-tabs>li.dropdown .dropdown-menu>.active>a:hover,
.with-nav-tabs.panel-tab-block .nav-tabs>li.dropdown .dropdown-menu>.active>a:focus {
  background-color: #4a9fe9;
}

.tab-block-content {
  color: #202020;
}

.notification-badge {
  position: relative;
  padding-right: 1em;
}

.notification-badge[data-notification-badge]:after {
  content: attr(data-notification-badge);
  position: absolute;
  top: -0.75em;
  right: -0.75em;
  font-size: 0.75em;
  background: red;
  color: white;
  width: 1.5em;
  height: 1.5em;
  text-align: center;
  line-height: 1.5em;
  border-radius: 50%;
  box-shadow: 0 0 1px #333;
}</code>```

<link rel="stylesheet" type="text/css" href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">

            Projects

            Forum

                    Projects

                    Forum

```

Updated JSFiddle

Title: Reset CSS badge content after ajax call

Body:
I have a page which contains some navigation tabs.  If there is a notification for that tab a badge is displayed.  When the tab is in focus, I want an ajax call to make a server request and if the response is successful, I want the badge to be reset to zero.  I can display the badge and the ajax call returns successfully (I have not included this in the code below) and then when I try to set the data attribute for the tab, the value doesn't change.

The relevant code is as follows:

                        Projects

                        Forum

                                            Projects

                                        Forum

JQuery:

jQuery(document).ready(function( $ ) {

    $('#forum-notification-badge').on("focus", function() {
        var self = $(this);

        //Do ajax call if success reset the badge to zero
        self.data("notification-badge","0");
        console.log("set badge to zero");

    });

});

css:

.nav {
    border: 1px;
    border-color: #2f70b1;
}
.nav-bar {
    margin-bottom: 0px !important;
}
.navbar-default {
    background-color: #1d3c5c;
    border-color: #000000;
    font-family: 'Open Sans', 'Helvetica Neue', Arial, sans-serif;
    -webkit-transition: all 0.35s;
    -moz-transition: all 0.35s;
    transition: all 0.35s;
    margin-bottom: 0px !important;
    border-radius: 0px;
}

.navbar-default .navbar-header .navbar-brand {
    color: #777;
    font-family: 'Open Sans', 'Helvetica Neue', Arial, sans-serif;
    font-weight: 700;
    text-transform: uppercase;
}

.navbar-default .navbar-header .navbar-brand:hover, .navbar-default .navbar-header .navbar-brand:focus{
    color: #777;
}

.navbar-default .navbar-header .navbar-toggle {
    font-weight: 700;
    font-size: 12px;
    color: #222222;
    text-transform: uppercase;
}

.navbar-default .nav>li>a, .navbar-default .nav>li>a:focus {
    text-transform: uppercase;
    font-weight: 700;
    font-size: 13px;
    color: #222222;
}

.navbar-default .nav>li>a:hover, .navbar-default .nav>li>a:focus:hover {

}

.navbar-default .nav>li.active>a, .navbar-default .nav>li.active>a:focus{
    color: #F05F40 !important;
    background-color: transparent;
}

.navbar-default .nav>li.active>a:hover, .navbar-default .nav>li.active>a:focus:hover{
    background-color: #1d3c5c;
}

@media ( min-width : 768px) {
    .navbar-default {
        background-color: #1d3c5c;

    }
    .navbar-default .navbar-header .navbar-brand {
        color: #ddd;
    }
    .navbar-default .navbar-header .navbar-brand:hover, .navbar-default .navbar-header .navbar-brand:focus
        {
        color: white;
    }
    .navbar-default .nav>li>a, .navbar-default .nav>li>a:focus {
        color: #ddd;
    }
    .navbar-default .nav>li>a:hover, .navbar-default .nav>li>a:focus:hover {
        color: white;
    }
    .navbar-default.affix {
        background-color: white;

    }
    .navbar-default.affix .navbar-header .navbar-brand {
        color: #F05F40;
        font-size: 14px;
    }
    .navbar-default.affix .navbar-header .navbar-brand:hover,
        .navbar-default.affix .navbar-header .navbar-brand:focus {
        color: #eb3812;
    }
    .navbar-default.affix .nav>li>a, .navbar-default.affix .nav>li>a:focus {
        color: #222222;
    }
    .navbar-default.affix .nav>li>a:hover, .navbar-default.affix .nav>li>a:focus:hover
        {
        color: #F05F40;
    }
}

.navbar-default .navbar-nav>li>a:focus, .navbar-default .navbar-nav>li>a:hover {
    background-color: #286090;
}
.panel.with-nav-tabs.panel-tab-block{
    box-shadow: none;
    -moz-box-shadow: none;
    -webkit-box-shadow: none;
}

.with-nav-tabs.panel-tab-block .nav-tabs > li > a,
.with-nav-tabs.panel-tab-block .nav-tabs > li > a:hover,
.with-nav-tabs.panel-tab-block .nav-tabs > li > a:focus {
    color: #ffffff;
    background-color: #999999;
}
.with-nav-tabs.panel-tab-block .nav-tabs > .open > a,
.with-nav-tabs.panel-tab-block .nav-tabs > .open > a:hover,
.with-nav-tabs.panel-tab-block .nav-tabs > .open > a:focus,
.with-nav-tabs.panel-tab-block .nav-tabs > li > a:hover,
.with-nav-tabs.panel-tab-block .nav-tabs > li > a:focus {
    color: #fff;
    background-color: #666666 ;

}
.with-nav-tabs.panel-tab-block .nav-tabs > li.active > a,
.with-nav-tabs.panel-tab-block .nav-tabs > li.active > a:hover,
.with-nav-tabs.panel-tab-block .nav-tabs > li.active > a:focus {
    color: #fff;
    background-color: #2f70b1;
    border-color: #2f70b1;
}
.with-nav-tabs.panel-tab-block .nav-tabs > li.dropdown .dropdown-menu {
    background-color: #428bca;
    border-color: #3071a9;
}
.with-nav-tabs.panel-tab-block .nav-tabs > li.dropdown .dropdown-menu > li > a {
    color: #fff;
}
.with-nav-tabs.panel-tab-block .nav-tabs > li.dropdown .dropdown-menu > li > a:hover,
.with-nav-tabs.panel-tab-block .nav-tabs > li.dropdown .dropdown-menu > li > a:focus {
    background-color: #3071a9;
}
.with-nav-tabs.panel-tab-block .nav-tabs > li.dropdown .dropdown-menu > .active > a,
.with-nav-tabs.panel-tab-block .nav-tabs > li.dropdown .dropdown-menu > .active > a:hover,
.with-nav-tabs.panel-tab-block .nav-tabs > li.dropdown .dropdown-menu > .active > a:focus {
    background-color: #4a9fe9;
}

.tab-block-content {
    color: #202020;
}

.notification-badge {
    position:relative;
    padding-right: 1em;
}

.notification-badge[data-notification-badge]:after {
   content:attr(data-notification-badge);
   position:absolute;
   top:-0.75em;
   right:-0.75em;
   font-size:0.75em;
   background:red;
   color:white;
   width:1.5em;
   height:1.5em;
   text-align:center;
   line-height:1.5em;
   border-radius:50%;
   box-shadow:0 0 1px #333;
}

I have also created a jsfiddle

Body:
The .data() method only updates an internal variable jQuery stores and not the HTML itself, you will need to use the .attr() method instead.

Code Snippet Demonstration:

jQuery(document).ready(function($) {

  $('#forum-notification-badge').on("focus", function() {
    var self = $(this);

    //Do ajax call if success reset the badge to zero
    self.attr("data-notification-badge", "0");
    console.log("set badge to zero");

  });

});

.nav {
  border: 1px;
  border-color: #2f70b1;
}

.nav-bar {
  margin-bottom: 0px !important;
}

.navbar-default {
  background-color: #1d3c5c;
  border-color: #000000;
  font-family: 'Open Sans', 'Helvetica Neue', Arial, sans-serif;
  -webkit-transition: all 0.35s;
  -moz-transition: all 0.35s;
  transition: all 0.35s;
  margin-bottom: 0px !important;
  border-radius: 0px;
}

.navbar-default .navbar-header .navbar-brand {
  color: #777;
  font-family: 'Open Sans', 'Helvetica Neue', Arial, sans-serif;
  font-weight: 700;
  text-transform: uppercase;
}

.navbar-default .navbar-header .navbar-brand:hover,
.navbar-default .navbar-header .navbar-brand:focus {
  color: #777;
}

.navbar-default .navbar-header .navbar-toggle {
  font-weight: 700;
  font-size: 12px;
  color: #222222;
  text-transform: uppercase;
}

.navbar-default .nav>li>a,
.navbar-default .nav>li>a:focus {
  text-transform: uppercase;
  font-weight: 700;
  font-size: 13px;
  color: #222222;
}

.navbar-default .nav>li>a:hover,
.navbar-default .nav>li>a:focus:hover {}

.navbar-default .nav>li.active>a,
.navbar-default .nav>li.active>a:focus {
  color: #F05F40 !important;
  background-color: transparent;
}

.navbar-default .nav>li.active>a:hover,
.navbar-default .nav>li.active>a:focus:hover {
  background-color: #1d3c5c;
}

@media ( min-width: 768px) {
  .navbar-default {
    background-color: #1d3c5c;
  }
  .navbar-default .navbar-header .navbar-brand {
    color: #ddd;
  }
  .navbar-default .navbar-header .navbar-brand:hover,
  .navbar-default .navbar-header .navbar-brand:focus {
    color: white;
  }
  .navbar-default .nav>li>a,
  .navbar-default .nav>li>a:focus {
    color: #ddd;
  }
  .navbar-default .nav>li>a:hover,
  .navbar-default .nav>li>a:focus:hover {
    color: white;
  }
  .navbar-default.affix {
    background-color: white;
  }
  .navbar-default.affix .navbar-header .navbar-brand {
    color: #F05F40;
    font-size: 14px;
  }
  .navbar-default.affix .navbar-header .navbar-brand:hover,
  .navbar-default.affix .navbar-header .navbar-brand:focus {
    color: #eb3812;
  }
  .navbar-default.affix .nav>li>a,
  .navbar-default.affix .nav>li>a:focus {
    color: #222222;
  }
  .navbar-default.affix .nav>li>a:hover,
  .navbar-default.affix .nav>li>a:focus:hover {
    color: #F05F40;
  }
}

.navbar-default .navbar-nav>li>a:focus,
.navbar-default .navbar-nav>li>a:hover {
  background-color: #286090;
}

.panel.with-nav-tabs.panel-tab-block {
  box-shadow: none;
  -moz-box-shadow: none;
  -webkit-box-shadow: none;
}

.with-nav-tabs.panel-tab-block .nav-tabs>li>a,
.with-nav-tabs.panel-tab-block .nav-tabs>li>a:hover,
.with-nav-tabs.panel-tab-block .nav-tabs>li>a:focus {
  color: #ffffff;
  background-color: #999999;
}

.with-nav-tabs.panel-tab-block .nav-tabs>.open>a,
.with-nav-tabs.panel-tab-block .nav-tabs>.open>a:hover,
.with-nav-tabs.panel-tab-block .nav-tabs>.open>a:focus,
.with-nav-tabs.panel-tab-block .nav-tabs>li>a:hover,
.with-nav-tabs.panel-tab-block .nav-tabs>li>a:focus {
  color: #fff;
  background-color: #666666;
}

.with-nav-tabs.panel-tab-block .nav-tabs>li.active>a,
.with-nav-tabs.panel-tab-block .nav-tabs>li.active>a:hover,
.with-nav-tabs.panel-tab-block .nav-tabs>li.active>a:focus {
  color: #fff;
  background-color: #2f70b1;
  border-color: #2f70b1;
}

.with-nav-tabs.panel-tab-block .nav-tabs>li.dropdown .dropdown-menu {
  background-color: #428bca;
  border-color: #3071a9;
}

.with-nav-tabs.panel-tab-block .nav-tabs>li.dropdown .dropdown-menu>li>a {
  color: #fff;
}

.with-nav-tabs.panel-tab-block .nav-tabs>li.dropdown .dropdown-menu>li>a:hover,
.with-nav-tabs.panel-tab-block .nav-tabs>li.dropdown .dropdown-menu>li>a:focus {
  background-color: #3071a9;
}

.with-nav-tabs.panel-tab-block .nav-tabs>li.dropdown .dropdown-menu>.active>a,
.with-nav-tabs.panel-tab-block .nav-tabs>li.dropdown .dropdown-menu>.active>a:hover,
.with-nav-tabs.panel-tab-block .nav-tabs>li.dropdown .dropdown-menu>.active>a:focus {
  background-color: #4a9fe9;
}

.tab-block-content {
  color: #202020;
}

.notification-badge {
  position: relative;
  padding-right: 1em;
}

.notification-badge[data-notification-badge]:after {
  content: attr(data-notification-badge);
  position: absolute;
  top: -0.75em;
  right: -0.75em;
  font-size: 0.75em;
  background: red;
  color: white;
  width: 1.5em;
  height: 1.5em;
  text-align: center;
  line-height: 1.5em;
  border-radius: 50%;
  box-shadow: 0 0 1px #333;
}

<link rel="stylesheet" type="text/css" href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script type="text/javascript" src="//maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>

<div class="container-fluid">
  <br/>
  <div class="col-sm-10">
    <div class="panel with-nav-tabs panel-tab-block">
      <div class="panel-heading">
        <ul class="nav nav-tabs">
          <li class="active">
            <a data-toggle="tab" class="" href="#projects-tab">Projects</a>
          </li>
          <li>
            <a data-toggle="tab" id="forum-notification-badge" class="notification-badge" data-notification-badge="1" href="#forum-tab">Forum</a>
          </li>
        </ul>
      </div>
      <div class="panel-body">
        <div class="tab-content">
          <div id="projects-tab" class="tab-pane fade in active">
            <div class="row">

              <div class="col-sm-12">
                <div class="panel with-nav-tabs panel-tab-block">
                  <h1>
                    Projects
                  </h1>

                </div>
              </div>

            </div>
            <div class="row">
              <div class="spacer-sml"></div>
            </div>
            <div class="row">
              <div class="spacer-sml"></div>
            </div>
          </div>
          <div id="forum-tab" class="tab-pane fade">
            <div class="tab-block-content forum-posts">
              <div class="">
                <div class="col-sm-12">
                  <h1>
                    Forum
                  </h1>
                </div>

              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</div>

Updated JSFiddle


问:
Passing Parameters into a TestNG XML
I'm using a combination of Maven with TestNG to run my automation tests and for each test/test set, I currently have a separate TestNG XML file for the same. My issue is when it comes to scalability. How can I reduce the number of TestNG XML files used?

Typically, each test set of mine has like only one class in it. So, I was wondering is there any way I can pass a parameter or something while executing the test call to the TestNG XML to reduce the number of XML files.

Thanks in advance.

P.S. I cant club multiple tests and group them in one as each tests are triggered via another framework. These needs to be ran separately upon requirement. Any other solutions/suggestions are also welcome.

答: Found a workaround for the same. I created a batch file to accept parameter and based on the input parameters passed to the batch file, it creates the TestNG xml i require on runtime and thereby reducing the number of TestNG Xml. </p>

Title: Passing Parameters into a TestNG XML


问:
Wildcard search using Marklogic java API
Following is the code snippet for reference. I have 3 questions,

1) How to view the query that is framed in the following code to be displayed in the log? In the Log it is displayed as Junk value.

2) Once the JAVA API is trigger can we see the query that is passed in the Marklogic Logs? This can help why our wildcarded search is not working with required arguments.

3) The "wildcarded" / "exact" search options are not working / do data returned through JAVA API calls. But through Xquery from Query console data is returned.

Code Snippet:

```<code>String[] options = new String[]{"case-insensitive"};
        // BUILD query
        StructuredQueryDefinition query = sqb.and(sqb.value(sqb.jsonProperty(DataConstants.DOMAIN), FragmentScope.DOCUMENTS,options,9.0,Domain.Provider.name()));
        query = sqb.and(sqb.value(sqb.jsonProperty(DataConstants.subDomain), FragmentScope.DOCUMENTS,options,9.0,chRequest.getDomain()));
</code>```

Using exact option

```<code>options = new String []{"exact"};
        query = sqb.and(query,sqb.value(sqb.jsonProperty(field.getField()), FragmentScope.DOCUMENTS,options,9.0,field.getFieldValue().get(0)));
</code>```

Using wildcarded option

```<code>options = new String []{"wildcarded"};
        query = sqb.and(query,sqb.value(sqb.jsonProperty(field.getField()), FragmentScope.DOCUMENTS,options,9.0,field.getFieldValue().get(0)+"*"));
System.out.println("----query>>.-----"+query);
        ……
        ……
        StructuredQueryBuilder sqb = queryManager.newStructuredQueryBuilder();
        StructuredQueryDefinition criteria = getQueryDefinitionCriteria(cashRequest, sqb);
        SearchHandle searchHandle = queryManager.search(sqb.and(criteria), new SearchHandle(), pageNumber);
        GSONHandle handle = new GSONHandle();
        MatchDocumentSummary summaryArr[] = searchHandle.getMatchResults();
        System.out.println("summaryArr[] >>> "+summaryArr);
</code>```

Sample Log :
  ----query>>.-----com.marklogic.client.query.StructuredQueryBuilder$AndQuery***@247d44b4***
  summaryArr[] >>>
  [Lcom.marklogic.client.query.MatchDocumentSummary;@f3e6876
  summaryArr[].length >>> 50

答:
How to view the query that is framed in the following code to be
  displayed in the log?

Call query.serialize()

Once the JAVA API is trigger can we see the query that is passed in the Marklogic Logs?

See Debugging /search Queries With Logging.  Also consider using a network snooping tool like wireshark to see the network communication.  You can also set the Java system property com.marklogic.client.okhttp.httplogginginterceptor.level to body to see most REST (HTTP) requests & responses in the Java STDOUT.  Just beware that you can't use that with streaming handles (like InputStreamHandle).  Luckily, you're not using one of those here.

The "wildcarded" / "exact" search options are not working / do data returned through JAVA API calls. But through Xquery from Query console data is returned.

It looks like data is returned or you wouldn't see in your output that summaryArr[].length >>> 50.   In any case, I assume you mean the wrong data is returned.

Without more details it's hard to help troubleshoot.  We don't know what your getQueryDefinitionCriteria method does.  And we don't know what code you're running in qconsole.  Hopefully the above debugging options will help you track down the issue.  If not, please share with us your code for query console and your final generated structured query (that you get with the debugging calls above).

Body:
Following is the code snippet for reference. I have 3 questions,

1) How to view the query that is framed in the following code to be displayed in the log? In the Log it is displayed as Junk value.

2) Once the JAVA API is trigger can we see the query that is passed in the Marklogic Logs? This can help why our wildcarded search is not working with required arguments.

3) The "wildcarded" / "exact" search options are not working / do data returned through JAVA API calls. But through Xquery from Query console data is returned.

Code Snippet:

String[] options = new String[]{"case-insensitive"};
        // BUILD query
        StructuredQueryDefinition query = sqb.and(sqb.value(sqb.jsonProperty(DataConstants.DOMAIN), FragmentScope.DOCUMENTS,options,9.0,Domain.Provider.name()));
        query = sqb.and(sqb.value(sqb.jsonProperty(DataConstants.subDomain), FragmentScope.DOCUMENTS,options,9.0,chRequest.getDomain()));

Using exact option

options = new String []{"exact"};
        query = sqb.and(query,sqb.value(sqb.jsonProperty(field.getField()), FragmentScope.DOCUMENTS,options,9.0,field.getFieldValue().get(0)));

Using wildcarded option

options = new String []{"wildcarded"};
        query = sqb.and(query,sqb.value(sqb.jsonProperty(field.getField()), FragmentScope.DOCUMENTS,options,9.0,field.getFieldValue().get(0)+"*"));
System.out.println("----query>>.-----"+query);
        ……
        ……
        StructuredQueryBuilder sqb = queryManager.newStructuredQueryBuilder();
        StructuredQueryDefinition criteria = getQueryDefinitionCriteria(cashRequest, sqb);
        SearchHandle searchHandle = queryManager.search(sqb.and(criteria), new SearchHandle(), pageNumber);
        GSONHandle handle = new GSONHandle();
        MatchDocumentSummary summaryArr[] = searchHandle.getMatchResults();
        System.out.println("summaryArr[] >>> "+summaryArr);

Sample Log :
  ----query>>.-----com.marklogic.client.query.StructuredQueryBuilder$AndQuery***@247d44b4***
  summaryArr[] >>>
  [Lcom.marklogic.client.query.MatchDocumentSummary;@f3e6876
  summaryArr[].length >>> 50


问:
Use of # a.k.a. read-macro
Reading book "Let Over Lambda" by Doug Hoyte, I found the following description of #. sign, a.k.a. read-macro:

A basic read macro that comes built in with COMMON LISP is the #. read-time eval macro. This read macro lets you embed objects into the forms you read that can't be serialised, but can be created with a bit of lisp code.

It's from Chapter 4, most part of the book can be found here:
http://letoverlambda.com/index.cl/toc

This is example from the book that shows how the same expression may be read differently every time:

```<code>* '(football-game
     (game-started-at
       #.(get-internal-real-time))
     (coin-flip
       #.(if (zerop (random 2)) 'heads 'tails)))

(FOOTBALL-GAME
  (GAME-STARTED-AT 187)
  (COIN-FLIP HEADS))

* '(football-game
     (game-started-at
       #.(get-internal-real-time))
     (coin-flip
   #.(if (zerop (random 2)) 'heads 'tails)))

(FOOTBALL-GAME
  (GAME-STARTED-AT 309)
  (COIN-FLIP TAILS))
</code>```

Next, author demonstrates some hardcore tricks, creating variations with # macro.

So, it turns out that #' is also some kind of reading macro, and it's usually used before symbols that represent names of functions. But is it necessary, and what's exactly his job there?

I can put symbol for higher-order functions with #' or without it:

```<code>CL-USER> (defun test nil t)
TEST
CL-USER> (funcall #'test)
T
CL-USER> (funcall 'test)
T
</code>```

with the same success.

答:
The experience shown me that in a big system composed of many parts, the "'" vs. the "#'" idiom makes patching easier.
The reason is that the function object associated with the symbol is looked for every time it is encountered and this in every environment. Once and as soon as you've loaded (interactively, of course) a new definition (most likely, a patch) it is used the next time it is encountered. The performance cost is really small, but the advantage of the flexibility is huge. An it is really nice to imagine your customer's face when trying again the application saying "Wow! it works now!" :-)</p>

Title: Use of # a.k.a. read-macro

Body:
Reading book "Let Over Lambda" by Doug Hoyte, I found the following description of #. sign, a.k.a. read-macro:

A basic read macro that comes built in with COMMON LISP is the #. read-time eval macro. This read macro lets you embed objects into the forms you read that can't be serialised, but can be created with a bit of lisp code.

It's from Chapter 4, most part of the book can be found here:
http://letoverlambda.com/index.cl/toc

This is example from the book that shows how the same expression may be read differently every time:

* '(football-game
     (game-started-at
       #.(get-internal-real-time))
     (coin-flip
       #.(if (zerop (random 2)) 'heads 'tails)))

(FOOTBALL-GAME
  (GAME-STARTED-AT 187)
  (COIN-FLIP HEADS))

* '(football-game
     (game-started-at
       #.(get-internal-real-time))
     (coin-flip
   #.(if (zerop (random 2)) 'heads 'tails)))

(FOOTBALL-GAME
  (GAME-STARTED-AT 309)
  (COIN-FLIP TAILS))

Next, author demonstrates some hardcore tricks, creating variations with # macro.

So, it turns out that #' is also some kind of reading macro, and it's usually used before symbols that represent names of functions. But is it necessary, and what's exactly his job there?

I can put symbol for higher-order functions with #' or without it:

CL-USER> (defun test nil t)
TEST
CL-USER> (funcall #'test)
T
CL-USER> (funcall 'test)
T

with the same success.


问:
HTML2Canvas converting overflowed content to image
I have a div which is pretty overflowed. It basically includes a big organization chart. What I want to do is exporting whole content of div rather than visible part with html2canvas library but I couldn't achieve it so far. Following piece of code doesn't render full content. Is there a way to achieve it?

```<code>function export(){
    html2canvas( [ document.getElementById('diagram') ], {
        onrendered: function(canvas) {

            var dataUrl = canvas.toDataURL();
            window.open(dataUrl, "toDataURL() image", "width=800, height=800");
            //Canvas2Image.saveAsPNG(canvas);
        }
     });
}
</code>```

I am using BasicPrimitives library to generate organization charts. It takes a div and insert all elements to it. Since my chart is moderately big, it overflows from its container.
Xhtml code is as follows:

```<code><rich:panel style="float: left; width: 100%;">
     <div style="float: left; height:600px; margin-left: 1%;  width: 19%; border-style: dotted; border-width:1px;">
          Some irrelevant content
     </div>
     <div id="diagram" class='diagram' style="float: right; height:600px;  width: 59%; border-style: dotted; border-width:1px;">
          This is the div all charts are dynamically inserted
     </div>
     <div style="float: left; height:600px; margin-left: 1%;  width: 19%; border-style: dotted; border-width:1px;">
          Some more irrelevant content
     </div>
</rich:panel>
</code>```

答:
Give a try to dom-to-image, it works better for me since I have to set specific size, and show and element that hides for some screen size:

```<code>function convertCanvasAndSend(idElement, nameImage) {
var element = document.getElementById(idElement);
var styleOrig = element.getAttribute("style");
element.setAttribute("style", "width: 1400px; height: 480px;");
element.querySelector("ANY_HIDDEN_YOU NEED").setAttribute("style", "display: block;");
domtoimage.toBlob(element)
.then(function (blob) {
    window.saveAs(blob, nameImage + '.png');
    element.setAttribute("style", styleOrig);
    element.querySelector("ANY_HIDDEN_YOU NEED").setAttribute("style", styleOrigInnDiv);
});
</code>```

}

Body:
I have a div which is pretty overflowed. It basically includes a big organization chart. What I want to do is exporting whole content of div rather than visible part with html2canvas library but I couldn't achieve it so far. Following piece of code doesn't render full content. Is there a way to achieve it?

function export(){
    html2canvas( [ document.getElementById('diagram') ], {
        onrendered: function(canvas) {

            var dataUrl = canvas.toDataURL();
            window.open(dataUrl, "toDataURL() image", "width=800, height=800");
            //Canvas2Image.saveAsPNG(canvas);
        }
     });
}

I am using BasicPrimitives library to generate organization charts. It takes a div and insert all elements to it. Since my chart is moderately big, it overflows from its container.
Xhtml code is as follows:

<rich:panel style="float: left; width: 100%;">

          Some irrelevant content

          This is the div all charts are dynamically inserted

          Some more irrelevant content

</rich:panel>

Body:
Give a try to dom-to-image, it works better for me since I have to set specific size, and show and element that hides for some screen size:

function convertCanvasAndSend(idElement, nameImage) {
var element = document.getElementById(idElement);
var styleOrig = element.getAttribute("style");
element.setAttribute("style", "width: 1400px; height: 480px;");
element.querySelector("ANY_HIDDEN_YOU NEED").setAttribute("style", "display: block;");
domtoimage.toBlob(element)
.then(function (blob) {
    window.saveAs(blob, nameImage + '.png');
    element.setAttribute("style", styleOrig);
    element.querySelector("ANY_HIDDEN_YOU NEED").setAttribute("style", styleOrigInnDiv);
});

}


答:
EDIT

Since you posted 2.7 this is the 2.7 solution:

```<code>file = open("./Downloads/lamp-post.csv", "r")
data = [line.decode("utf-16", "replace") for line in file]
</code>```

Ignoring undecodeable characters:

```<code>file = open("./Downloads/lamp-post.csv", "r")
data = [line.decode("utf-16", "ignore") for line in file]
</code>```

Title: python: unicode problem

Body:
I am trying to decode a string I took from file:

file = open ("./Downloads/lamp-post.csv", 'r')
data = file.readlines()
data[0]

'\xff\xfeK\x00e\x00y\x00w\x00o\x00r\x00d\x00\t\x00C\x00o\x00m\x00p\x00e\x00t\x00i\x00t\x00i\x00o\x00n\x00\t\x00G\x00l\x00o\x00b\x00a\x00l\x00
  \x00M\x00o\x00n\x00t\x00h\x00l\x00y\x00
  \x00S\x00e\x00a\x00r\x00c\x00h\x00e\x00s\x00\t\x00D\x00e\x00c\x00
  \x002\x000\x001\x000\x00\t\x00N\x00o\x00v\x00
  \x002\x000\x001\x000\x00\t\x00O\x00c\x00t\x00
  \x002\x000\x001\x000\x00\t\x00S\x00e\x00p\x00
  \x002\x000\x001\x000\x00\t\x00A\x00u\x00g\x00
  \x002\x000\x001\x000\x00\t\x00J\x00u\x00l\x00
  \x002\x000\x001\x000\x00\t\x00J\x00u\x00n\x00
  \x002\x000\x001\x000\x00\t\x00M\x00a\x00y\x00
  \x002\x000\x001\x000\x00\t\x00A\x00p\x00r\x00
  \x002\x000\x001\x000\x00\t\x00M\x00a\x00r\x00
  \x002\x000\x001\x000\x00\t\x00F\x00e\x00b\x00
  \x002\x000\x001\x000\x00\t\x00J\x00a\x00n\x00
  \x002\x000\x001\x000\x00\t\x00A\x00d\x00
  \x00s\x00h\x00a\x00r\x00e\x00\t\x00S\x00e\x00a\x00r\x00c\x00h\x00
  \x00s\x00h\x00a\x00r\x00e\x00\t\x00E\x00s\x00t\x00i\x00m\x00a\x00t\x00e\x00d\x00
  \x00A\x00v\x00g\x00.\x00
  \x00C\x00P\x00C\x00\t\x00E\x00x\x00t\x00r\x00a\x00c\x00t\x00e\x00d\x00
  \x00F\x00r\x00o\x00m\x00
  \x00W\x00e\x00b\x00
  \x00P\x00a\x00g\x00e\x00\t\x00L\x00o\x00c\x00a\x00l\x00
  \x00M\x00o\x00n\x00t\x00h\x00l\x00y\x00
  \x00S\x00e\x00a\x00r\x00c\x00h\x00e\x00s\x00\n'

Adding ignore do not really help...:

In [69]: data[2]
  Out[69]: u'\u6700\u6100\u7200\u6400\u6500\u6e00\u2000\u6c00\u6100\u6d00\u7000\u2000\u7000\u6f00\u7300\u7400\u0900\u3000\u2e00\u3900\u3400\u0900\u3800\u3800\u3000\u0900\u2d00\u0900\u3300\u3200\u3000\u0900\u3300\u3900\u3000\u0900\u3300\u3900\u3000\u0900\u3400\u3800\u3000\u0900\u3500\u3900\u3000\u0900\u3500\u3900\u3000\u0900\u3700\u3200\u3000\u0900\u3700\u3200\u3000\u0900\u3300\u3900\u3000\u0900\u3300\u3200\u3000\u0900\u3200\u3600\u3000\u0900\u2d00\u0900\u2d00\u0900\ua300\u3200\u2e00\u3100\u3800\u0900\u2d00\u0900\u3400\u3800\u3000\u0a00'

In [70]: data[2].decode("utf-8",
  "replace")
  ---------------------------------------------------------------------------
  Traceback (most recent call last)

/Users/oleg/ in
  ()

/opt/local/lib/python2.5/encodings/utf_8.py
  in decode(input, errors)
       14
       15 def decode(input, errors='strict'):
  ---> 16     return codecs.utf_8_decode(input, errors,
  True)
       17
       18 class IncrementalEncoder(codecs.IncrementalEncoder):

:
  'ascii' codec can't encode characters
  in position 0-87: ordinal not in
  range(128)

In [71]:

Body:
EDIT

Since you posted 2.7 this is the 2.7 solution:

file = open("./Downloads/lamp-post.csv", "r")
data = [line.decode("utf-16", "replace") for line in file]

Ignoring undecodeable characters:

file = open("./Downloads/lamp-post.csv", "r")
data = [line.decode("utf-16", "ignore") for line in file]


问:
Why am i getting the error "Unparseable date" from SimpleDateFormat?
Im trying to parse a Date-String without timezone to a new Date with time-Zone but im getting the error:

java.text.ParseException: Unparseable date: "2017-11-17 10:49:39.772 "

Here´s my code:

```<code> String date = "2017-11-17 10:49:39.772 "
 SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS Z");
 sdf.setTimeZone(TimeZone.getTimeZone("Europe/Amsterdam"));
 sdf.parse(date);  //here´s the error
 return date.getTime();
</code>```

Any suggestions?

答: You explicitly said in your SimpleDateFormat that you require a timezone offset at the end (the Z parameter), yet your string is missing the offset. You'd need something like +0000 at the end.

Body:
Im trying to parse a Date-String without timezone to a new Date with time-Zone but im getting the error:

java.text.ParseException: Unparseable date: "2017-11-17 10:49:39.772 "

Here´s my code:

 String date = "2017-11-17 10:49:39.772 "
 SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS Z");
 sdf.setTimeZone(TimeZone.getTimeZone("Europe/Amsterdam"));
 sdf.parse(date);  //here´s the error
 return date.getTime();

Any suggestions?


问:
 element not working between div and input
Below is the code that I am using. For some reason I cannot get the br in between the div.chatBox and input to show. Can anyone give me any suggestions.

```<code><div class="container-fluid col-xs-12">
    <div class="row">
        <br>
        <div class="chatBox col-xs-5 col-xs-offset-3" id="chatBox">
        </div>

        <br>

        <input type="text" class="col-xs-offset-4 col-xs-3">
    </div>
</div>
</code>```

答:
According to bootstrap guidieline your div elements should have a row class.
 And then you could just add styles as margin of 1em for them instead of using breaklines.

Title: <br> element not working between div and input

Body:
Below is the code that I am using. For some reason I cannot get the br in between the div.chatBox and input to show. Can anyone give me any suggestions.

        <input type="text" class="col-xs-offset-4 col-xs-3">


问:
Use sed to find extract information and print in specific order
I'm currently having some struggle to figure out a sed command that can extract information and then print it in a specific order. For example,
if I have a text document looking like this:

```<code>kashd[,]->0123asdj01234/
jflskdvnd1234/asdasd[,]->0123asdasd
kashd[,]->0123asdj01234/
jflskdvnd1234/asdasd[,]->0123asdasd
kashd[,]->0123asdj01234/
jflskdvnd1234/asdasd[,]->0123asdasd
</code>```

then I want to extract the following pars of each line:

```<code>[,]->0132
</code>```

(any 4 random digits) and

```<code>0132/
</code>```

So far, I have the command:

```<code>sed 's/^.*\(\[,\]->[0-9]\{4\}\|[0-9]\{4\}\/\).*\(\[,\]->[0-9]\{4\}\|[0-9]\{4\}\/\).*$/\1      \2/; '
</code>```

This command does extract all matches, but my problem is that I don't know how to change the order because right now it prints the order it's found:

(if command run on the example text above)

```<code>[,]->0123        1234/
1234/        [,]->0123
[,]->0123        1234/
1234/        [,]->0123
1234/        [,]->0123
</code>```

but I want it to be sorted like this:

```<code>[,]->0123        1234/
[,]->0123        1234/
[,]->0123        1234/
[,]->0123        1234/
[,]->0123        1234/
</code>```

Also, I'm only allowed to use sed.

答:
Because you don't know which pattern will show up first in the line, I think the cleanest way is using the hold space.

Here is how I would do it in sed:

```<code>$ sed -E 'h;s/.*([[:digit:]]{4}\/).*/\1/;x;s/.*(\[,\]->[[:digit:]]{4}).*/\1/;G;s/\n/\t/' infile
[,]->0123       1234/
[,]->0123       1234/
[,]->0123       1234/
[,]->0123       1234/
[,]->0123       1234/
[,]->0123       1234/
</code>```

Expanded and explained:

```<code>h                                   # Copy pattern space to hold space
s/.*([[:digit:]]{4}\/).*/\1/        # Remove everything but dddd/ pattern
x                                   # Swap pattern and hold space
s/.*(\[,\]->[[:digit:]]{4}).*/\1/   # Remove everything but [,]->dddd pattern
G                                   # Append hold space to pattern space
s/\n/\t/                            # Replace line break with tab
</code>```

The -E option (or -r in older GNU sed) allows us to not escape () and {}. The command would also work without it, but then we'd have to use \(\) and \{\} instead.

Alternatively, if you wanted to use your command: you can check if a line does not start with [, and if so, you can swap the to blocks of non-spaces. If you add this to your command

```<code>/^\[/!s/^\([^ ]*\)\( *\)\([^ ]*\)$/\3\2\1/
</code>```

it should work.

Body:
I'm currently having some struggle to figure out a sed command that can extract information and then print it in a specific order. For example,
if I have a text document looking like this:

kashd[,]->0123asdj01234/
jflskdvnd1234/asdasd[,]->0123asdasd
kashd[,]->0123asdj01234/
jflskdvnd1234/asdasd[,]->0123asdasd
kashd[,]->0123asdj01234/
jflskdvnd1234/asdasd[,]->0123asdasd

then I want to extract the following pars of each line:

[,]->0132

(any 4 random digits) and

0132/

So far, I have the command:

sed 's/^.*\(\[,\]->[0-9]\{4\}\|[0-9]\{4\}\/\).*\(\[,\]->[0-9]\{4\}\|[0-9]\{4\}\/\).*$/\1      \2/; '

This command does extract all matches, but my problem is that I don't know how to change the order because right now it prints the order it's found:

(if command run on the example text above)

[,]->0123        1234/
1234/        [,]->0123
[,]->0123        1234/
1234/        [,]->0123
1234/        [,]->0123

but I want it to be sorted like this:

[,]->0123        1234/
[,]->0123        1234/
[,]->0123        1234/
[,]->0123        1234/
[,]->0123        1234/

Also, I'm only allowed to use sed.

Body:
Because you don't know which pattern will show up first in the line, I think the cleanest way is using the hold space.

Here is how I would do it in sed:

$ sed -E 'h;s/.*([[:digit:]]{4}\/).*/\1/;x;s/.*(\[,\]->[[:digit:]]{4}).*/\1/;G;s/\n/\t/' infile
[,]->0123       1234/
[,]->0123       1234/
[,]->0123       1234/
[,]->0123       1234/
[,]->0123       1234/
[,]->0123       1234/

Expanded and explained:

h                                   # Copy pattern space to hold space
s/.*([[:digit:]]{4}\/).*/\1/        # Remove everything but dddd/ pattern
x                                   # Swap pattern and hold space
s/.*(\[,\]->[[:digit:]]{4}).*/\1/   # Remove everything but [,]->dddd pattern
G                                   # Append hold space to pattern space
s/\n/\t/                            # Replace line break with tab

The -E option (or -r in older GNU sed) allows us to not escape () and {}. The command would also work without it, but then we'd have to use \(\) and \{\} instead.

Alternatively, if you wanted to use your command: you can check if a line does not start with [, and if so, you can swap the to blocks of non-spaces. If you add this to your command

/^\[/!s/^\([^ ]*\)\( *\)\([^ ]*\)$/\3\2\1/

it should work.


问:
convert Promise based function to an observable based function
What is the simplest way to do something like this in an observable approach way?</p>

```<code>async function promiseBased {
    await // wait for some jobs to be done
}

await promisebased();
// then do other jobs
</code>```

答: You can use Observable.fromPromise to get an observable to promise and observable.toPromise to get a promise from an observable</p>

Body:
What is the simplest way to do something like this in an observable approach way?

async function promiseBased {
    await // wait for some jobs to be done
}

await promisebased();
// then do other jobs