问:
why my code fail to render jQuery template?
I am using jQuery tempalte in my project and now i found that a thing not worked i not know what's goes wrong in my code.

can anyone show me where i am goes wrong.

```<code> <script id="ajaxresult" type="text/html">
  <li>
                        <h3>
                            <a href="{{= url}}">{{= title}}</a></h3>
                        <p>{{= content}}</p>
                        <div class="url">{{= url}}</div>
                    </li>
    </script>

   var title = $("#txtsrch").val();
    var resp = GetAjaxResponse("/home/blah", { topic: title, pagenum: fpage + 1 });
    $("#ajaxresult").render(JSON.parse(resp)).appendTo("#result ul");
    fpage = fpage + 1;
</code>```

when i try this code i found that i got the error render is not a function

can anyone show me where my code have a bug or any other good way i can use to do this thing

OwnerDisplayName: delete my account

Body:
I am using jQuery tempalte in my project and now i found that a thing not worked i not know what's goes wrong in my code.

can anyone show me where i am goes wrong.

   var title = $("#txtsrch").val();
    var resp = GetAjaxResponse("/home/blah", { topic: title, pagenum: fpage + 1 });
    $("#ajaxresult").render(JSON.parse(resp)).appendTo("#result ul");
    fpage = fpage + 1;

when i try this code i found that i got the error render is not a function

can anyone show me where my code have a bug or any other good way i can use to do this thing

Body:
For a start, you seem to have pasted HTML code directly into your <script> tag, and put your JavaScript outside of the <script> tag.

<script> tags can only contain JavaScript. At a guess, I’d say your HTML code should look more like this:

<ul id="ajaxresult">
    <li>
        <h3><a href="{{= url}}">{{= title}}</a></h3>
        <p>{{= content}}</p>
        <div class="url">{{= url}}</div>
    </li>
</ul>

I’ve no idea what’s going on in your JavaScript though. As Calum asked in his comment, which part of jQuery are you trying to use?


来源: stackexchange

问:
Mat-select panel min-width
I'm trying to customize mat-select with multiple checkboxes.
for some reason the panel get wrong min-width as below:

and I don't know where its calculating this min-width.
also I tried to add panelClass and override the min-width from this class,
for example:

```<code><mat-select #multipleSelect (selectionChange)="selectItem($event.value)" panelClass="multiple-panel" multiple>

&.multiple-panel {
   min-width: 200px !important;
}
</code>```

but when opening the dropdown its open with the original width (like in the pic) and after few millisecond"jump" to the custom min-width defined on the panel class.

I find the mat-select very hard to style. anybody knows how to solve this problem?

答:
I used another approach.
Just added this piece of code to global style.

```<code>.mat-select-panel {
// some your code
  &.ng-animating {
       visibility: hidden;
    }
  }
</code>```

You can try this solution on
DEMO StackBlitz.

Hack with opacity did not fix jumping width when select is closing.

ContentLicense: CC BY-SA 4.0

Title: Mat-select panel min-width

Body:
I'm trying to customize mat-select with multiple checkboxes.
for some reason the panel get wrong min-width as below:

and I don't know where its calculating this min-width.
also I tried to add panelClass and override the min-width from this class,
for example:

<mat-select #multipleSelect (selectionChange)="selectItem($event.value)" panelClass="multiple-panel" multiple>

&.multiple-panel {
   min-width: 200px !important;
}

but when opening the dropdown its open with the original width (like in the pic) and after few millisecond"jump" to the custom min-width defined on the panel class.

I find the mat-select very hard to style. anybody knows how to solve this problem?

Body:
I used another approach.
Just added this piece of code to global style.

.mat-select-panel {
// some your code
  &.ng-animating {
       visibility: hidden;
    }
  }

You can try this solution on
DEMO StackBlitz.

Hack with opacity did not fix jumping width when select is closing.


问:
Formatting csv row made from dictionary
I am writing appending new dictionary entries to a csv as they are made. This works completely fine, however the formatting is funky. I am recording the trades my automated strategy makes. It records the timestamp, the trade, and the price.

Here is my function that records a new dictionary entry and appends to my csv:

```<code>def record_example(x):
    now = datetime.now()
    unix = int(mktime(now.timetuple()))
    price = 8110

    log.example[unix] = [unix, x, price]

    with open('example.csv', 'a') as e:
        writer = csv.DictWriter(e, fieldnames=log.example)
        writer.writerow(log.example)

        e.close()
</code>```

I call the function w/:

```<code>record('buy')
</code>```

this creates the dictionary as it should:

```<code>{1559052353: [1559052353, 'buy', 8110]}
</code>```

however the entry into the csv now looks like with it only filling A1:

```<code>"[1559052353, 'buy', 8110]"
</code>```

when I am trying to get it to look like: (so that I can import the csv into another .py file and plot trade performance)

```<code>1559052353, buy, 8110
</code>```

so that 1559052353 will be in A1, buy in A2, and 8110 in A3 for example

I have tried ''.join(split(',') for each row in csv yet get error message.. thanks so much if you can help!

答:
with your code you get header to be 1559052353 and the value is the whole list (converted to str, that's why you get also the double quotes)

I believe you want to have fieldnames unix,x,price and values 1559052353,buy,8110

```<code>with open('example.csv', 'a') as e:
    header = ['unix', 'x', 'price']
    writer = csv.DictWriter(e, fieldnames=header)
    writer.writeheader()
    writer.writerow(dict(zip(header, log.example[unix])))
</code>```

note when using with context manager you don't need to call e.close()
you may want to make log.example[unix] to be a dict, not list.
also, maybe replace x in header with something else

Title: Formatting csv row made from dictionary

Body:
I am writing appending new dictionary entries to a csv as they are made. This works completely fine, however the formatting is funky. I am recording the trades my automated strategy makes. It records the timestamp, the trade, and the price.

Here is my function that records a new dictionary entry and appends to my csv:

def record_example(x):
    now = datetime.now()
    unix = int(mktime(now.timetuple()))
    price = 8110

    log.example[unix] = [unix, x, price]

    with open('example.csv', 'a') as e:
        writer = csv.DictWriter(e, fieldnames=log.example)
        writer.writerow(log.example)

        e.close()

I call the function w/:

record('buy')

this creates the dictionary as it should:

{1559052353: [1559052353, 'buy', 8110]}

however the entry into the csv now looks like with it only filling A1:

"[1559052353, 'buy', 8110]"

when I am trying to get it to look like: (so that I can import the csv into another .py file and plot trade performance)

1559052353, buy, 8110

so that 1559052353 will be in A1, buy in A2, and 8110 in A3 for example

I have tried ''.join(split(',') for each row in csv yet get error message.. thanks so much if you can help!

Body:
with your code you get header to be 1559052353 and the value is the whole list (converted to str, that's why you get also the double quotes)

I believe you want to have fieldnames unix,x,price and values 1559052353,buy,8110

with open('example.csv', 'a') as e:
    header = ['unix', 'x', 'price']
    writer = csv.DictWriter(e, fieldnames=header)
    writer.writeheader()
    writer.writerow(dict(zip(header, log.example[unix])))

note when using with context manager you don't need to call e.close()
you may want to make log.example[unix] to be a dict, not list.
also, maybe replace x in header with something else


问:
Nodejs Database configuration based on accessed domain
I have two domains abc.com and xyz.com pointing to the same NodeJS server. Based on the domain I want to load the configuration that will persist for that domain i.e. for xyz.com I wanna connect to Database1 and for abc.com I wanna connect to Database2.

How do I go about doing this? Is it even possible or recommended to do so?

I started with loading the configuration on the first request by getting the hostname from req.hostname. Is there any better way to do this?

答:
Multiple strategies -

1. Deploy the same code multiple times but on different ports.

Your reverse proxy sends the request to the correct server. I do this currently by hosting multiple ghost blogs on the same vps. One runs on port 3000, another on 3010.

Pros - Less fragile setup, easier scaling, application need not be aware of operational environment. If one domain comes under attack, the other is not automatically a casualty.

Cons - Might not be possible in resource constrained environments. Deployments can involve repetitive work.

2. Read the hostname

Great option if the feature set is pretty much the same but only the domain name changes. You read the configuration file as you stated depending on the hostname.

Pros - Easier deployment, great option for resource constrained environments.

Cons - Unnecessarily tight coupling, all domains will become unavailable in case of server errors, scaling could be an issue.

Personally, I prefer deploying on different ports unless and until the code requires depending on hostnames. If you are just building a product where some unique identifier needs to be present in the URL like mycompany.slack.com then using subdomains in dns might be a better idea.


问:
TinyMCE 5: Disabled editor but allow to copy text
How to disable the Editor but allow the user to copy the text?

When I set disabled to true it's now possible to select and copy text.

```<code><Editor disabled={true} />
</code>```

答:
This is not how TinyMCE's read only mode works - in that mode the editor is truly read only and will not allow you to select the text in the editor.  If you wanted different behavior you would need to suggest that to the TinyMCE developers via their GitHub Issue Tracker:

https://github.com/tinymce/tinymce/issues

Body:
How to disable the Editor but allow the user to copy the text?

When I set disabled to true it's now possible to select and copy text.

<Editor disabled={true} />


问:
collect numbers and convert them to date in angularjs
I have 3 scopes in angularjs, one for year, one for month and one for day coming from 3 input boxes. I want to combine them as date, the following code insert the date correctly but with 22:00:00 added to it like  2019-06-01 22:00:00.000.
How to insert the date only without time

HTML

```<code><div class="col-md-1">
    <div class="form-group has-error">
        <label class="title_lable">Year:</label>
        <input id="code" type="number" class="form-control input-sm"
               ng-model="year">
    </div>
</div>
<div class="col-md-2">
    <div class="form-group has-error">
        <label class="title_lable">Latin Description:</label>
        <input type="text" class="form-control input-sm"
               ng-model="latindesc">
    </div>
</div>
<div class="col-md-2">
    <div class="form-group">
        <label class="title_lable">Local Description:</label>
        <input type="text" class="form-control input-sm"
               ng-model="localdesc">
    </div>
</div>
<div class="col-md-1">
    <div class="form-group">
        <label class="title_lable">Month:</label>
        <select ng-show="lang==1" class="form-control input-sm"
                ng-model="month"
                ng-options="m.mnthid as m.mnthanm for m in months">
        </select>
        <select ng-show="lang==0" class="form-control input-sm"
                ng-model="month"
                ng-options="m.mnthid as m.mnthenm for m in months">
        </select>
    </div>
</div>
<div class="col-md-1">
    <div class="form-group">
        <label class="title_lable">Day:</label>
        <input type="number" class="form-control input-sm" ng-model="day">
    </div>
</div>
</code>```

Angular

```<code>var dFrom = new Date($scope.month + '/' + ($scope.day + 1) + '/' + $scope.year );
        var days = $scope.ndays;
        console.log(days);
        var todate = new Date($scope.month + '/' + ($scope.day +1) + '/' + $scope.year);
        todate = addDays(todate, days - 1);
        console.log(todate);

        var vacation = {
            Sys_Key: $scope.syskey,
            Vac_Code: $scope.code,
            L_Desc: $scope.latindesc,
            A_Desc: $scope.localdesc,
            V_Start_Date: $scope.day,
            V_Month: $scope.month,
            V_Days_Count: $scope.ndays,
            V_Year: $scope.year,
            From_Date: dFrom,
            To_Date: todate
        }
</code>```

```<code>function addDays(startDate, numberOfDays) {
    var returnDate = new Date(
        startDate.getFullYear(),
        startDate.getMonth(),
        startDate.getDate() + numberOfDays,
        startDate.getHours(),
        startDate.getMinutes(),
        startDate.getSeconds()
    );
    return returnDate;
}
</code>```

答:
the code insert the date correctly but with 22:00:00 added to it like 2019-06-01 22:00:00.000. How to insert the date only without time

Under-the-hood the date is parsed to 00:00 hours UTC time. The standard .toString method displays it as local time.

var d = new Date("2019-06-01");

console.log(d.toString());

console.log(d.toISOString());```
</div>
</div>
</p>

<p>If you want it parsed to local time append "T00:00"</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>var d = new Date("2019-06-01T00:00");

console.log(d.toString());

console.log(d.toISOString());</code>```

When the time zone offset is absent, date-only forms are interpreted as a UTC time and date-time forms are interpreted as local time.

For more information, see

MDN JavaScript Reference - Date.parse()

Body:
I have 3 scopes in angularjs, one for year, one for month and one for day coming from 3 input boxes. I want to combine them as date, the following code insert the date correctly but with 22:00:00 added to it like  2019-06-01 22:00:00.000.
How to insert the date only without time

HTML

        Year:
        <input id="code" type="number" class="form-control input-sm"
               ng-model="year">

        Latin Description:
        <input type="text" class="form-control input-sm"
               ng-model="latindesc">

        Local Description:
        <input type="text" class="form-control input-sm"
               ng-model="localdesc">

        Month:
        <select ng-show="lang==1" class="form-control input-sm"
                ng-model="month"
                ng-options="m.mnthid as m.mnthanm for m in months">
        </select>
        <select ng-show="lang==0" class="form-control input-sm"
                ng-model="month"
                ng-options="m.mnthid as m.mnthenm for m in months">
        </select>

        Day:
        <input type="number" class="form-control input-sm" ng-model="day">

Angular

var dFrom = new Date($scope.month + '/' + ($scope.day + 1) + '/' + $scope.year );
        var days = $scope.ndays;
        console.log(days);
        var todate = new Date($scope.month + '/' + ($scope.day +1) + '/' + $scope.year);
        todate = addDays(todate, days - 1);
        console.log(todate);

        var vacation = {
            Sys_Key: $scope.syskey,
            Vac_Code: $scope.code,
            L_Desc: $scope.latindesc,
            A_Desc: $scope.localdesc,
            V_Start_Date: $scope.day,
            V_Month: $scope.month,
            V_Days_Count: $scope.ndays,
            V_Year: $scope.year,
            From_Date: dFrom,
            To_Date: todate
        }

function addDays(startDate, numberOfDays) {
    var returnDate = new Date(
        startDate.getFullYear(),
        startDate.getMonth(),
        startDate.getDate() + numberOfDays,
        startDate.getHours(),
        startDate.getMinutes(),
        startDate.getSeconds()
    );
    return returnDate;
}

Body:
the code insert the date correctly but with 22:00:00 added to it like 2019-06-01 22:00:00.000. How to insert the date only without time

Under-the-hood the date is parsed to 00:00 hours UTC time. The standard .toString method displays it as local time.

var d = new Date("2019-06-01");

console.log(d.toString());

console.log(d.toISOString());

If you want it parsed to local time append "T00:00"

var d = new Date("2019-06-01T00:00");

console.log(d.toString());

console.log(d.toISOString());

When the time zone offset is absent, date-only forms are interpreted as a UTC time and date-time forms are interpreted as local time.

For more information, see

MDN JavaScript Reference - Date.parse()


问:
How can I create a UML graph by code and I can search characters in graph?
I want to create a program flow graph, but I don't want to draw it by Mouse. I can draw a simple graph by markdown or mermaid, but they are too simple.

For example:

this is generated by Typora Mermaid. All items are html.

But I want to modify more details. For example, font highlighting, adding parentheses in content, etc. I also want to generate graphics that look better.

Another Example:

This is generated by graphviz, if I export it as svg, I can retrieve characters.

But after I insert it in Typora, and export markdown as a.html. However, I can't search characters from svg in a.html, because its label is img. I'm not familiar with HTML, I don't know how to handle this.

I want to find a tool that can render dot language into html, and can work with markdown, How to achieve it? Or any better choices?

答:
I think I should just generate a svg file by dot. A good way to add it in markdown is using html label:<object type="image/svg+xml" data="test.svg"></object>. And chrome would render it.

I'm not sure whether this question is able to keep, but I will keep it until someone asks me to delete it or it's a repeating question.

Here is how I search in a svg.


问:
Alternative to VS for editing RS reports?
VS works I guess, but it's definitely pretty clunky in a lot of ways, and I was just wondering if there was some third-party alternative that's better.</p>

答: Not that I'm aware of, at least in the general case.  There are third party tools that will spit out .rdl files that can be used by SSRS, but none I'm aware of that act as a general purpose .rdl editor.</p>

ContentLicense: CC BY-SA 3.0


问:
How to reload code when HTTP server is running?
When starting an http server using HTTP.serve there is apparently no way to reload the code that is actually handling the HTTP request.
In the example below I would like to have the modifications in my_httphandler taken into account without having to restart the server.
For the moment I need to stop the server from the REPL by pressing CTRL+C twice and then run the script again.

Is there a workaround ?

```<code>module MyModule

using HTTP
using Mux
using JSON
using Sockets

function my_httphandler(req::HTTP.Request)
    return HTTP.Response(200, "Hello world")
end

const MY_ROUTER = HTTP.Router()
HTTP.@register(MY_ROUTER, "GET", "/*", my_httphandler)

HTTP.serve(MY_ROUTER, Sockets.localhost, 8081)

end
</code>```

答: Revise.jl lets you automatically update code in a live Julia session. You may be especially interested in entr; see Revise's documentation for details.

Body:
When starting an http server using HTTP.serve there is apparently no way to reload the code that is actually handling the HTTP request.
In the example below I would like to have the modifications in my_httphandler taken into account without having to restart the server.
For the moment I need to stop the server from the REPL by pressing CTRL+C twice and then run the script again.

Is there a workaround ?

module MyModule

using HTTP
using Mux
using JSON
using Sockets

function my_httphandler(req::HTTP.Request)
    return HTTP.Response(200, "Hello world")
end

const MY_ROUTER = HTTP.Router()
HTTP.@register(MY_ROUTER, "GET", "/*", my_httphandler)

HTTP.serve(MY_ROUTER, Sockets.localhost, 8081)

end


问:
How to fix the 'expected right parenthesis' happening in the 4th line : tau0*(t[j+1]-t[j]) in winbugs
I need to estimate four parameters using winbugs: tau[i], mu1[i],mu2[i]and tau0[i].

When I click check the model, it shows expected right parenthesis between tau0* and (t[j+1]-t[j]) in the 4th line.
When I delete the (t[j+1]-t[j]), it shows the same expected right parenthesis between c and <-(1-step( tau[i]-t[j]))

```<code>model
{
#likelihood
   for(i in 1:n){
    for(j in 1:m){
 x[i,j]~ dnorm( mu[i,j],  tau0*(t[j+1]-t[j]))
 mu[i,j]<- mu1*(t[j+1]-t[j])*a+mu1*(tau[i]-t[j])*b+mu2*(t[j+1]-tau[i])*b+mu2*(t[j+1]-t[j])*c
 sigma <-1/sqrt(tau0)
 a<-step( tau[i]-t[ j+1] )
 b<-(step(tau[i]- t[j])-(step(tau[i]- t[j+1]))
 c<-(1-step( tau[i]-t[j]))
}
#prior
   tau[i]~dnorm(mutau,tautau)
   mutau~dorm(0,  0.001)
   tautau~dgamma(0.01, 0.01)
   sigmatau<-1/sqrt(tautau)
   mu1[i]~dnorm(mumu1, tau1)
   mumu1~dorm(0, 0.001)
   tau1~dgamma(0.01,0.01)
   sigmatau1<-1/sqrt(tau1)
   mu2[i]~dnorm(mumu2, tau2)
   mumu2~dorm(0, 0.001)
   tau2~dgamma(0.01,0.01)
   sigmatau2<-1/sqrt(tau2)

   tau0[i]~dgamma(alpha,beta)
   sigmatau0<-1/tau0
  }
}
DATA
list(n=5, m=16,   mutau=0, tautau=1,  mumu1=0, tau1=1,   mumu2=0, tau2=1, alpha=0.01, beta=0.01 )
</code>```

I expected the right model syntax

答:
b<-(step(tau[i]- t[j])-(step(tau[i]- t[j+1]))

```<code>(
    step(
            tau[i]- t[j]
        )
    -
    (
    step(
            tau[i]- t[j+1]
        )
    )
</code>```

4 brackets opening, 3 brackets closing.
First bracket is not closed.

Body:
I need to estimate four parameters using winbugs: tau[i], mu1[i],mu2[i]and tau0[i].

When I click check the model, it shows expected right parenthesis between tau0* and (t[j+1]-t[j]) in the 4th line.
When I delete the (t[j+1]-t[j]), it shows the same expected right parenthesis between c and <-(1-step( tau[i]-t[j]))

model
{
#likelihood
   for(i in 1:n){
    for(j in 1:m){
 x[i,j]~ dnorm( mu[i,j],  tau0*(t[j+1]-t[j]))
 mu[i,j]<- mu1*(t[j+1]-t[j])*a+mu1*(tau[i]-t[j])*b+mu2*(t[j+1]-tau[i])*b+mu2*(t[j+1]-t[j])*c
 sigma <-1/sqrt(tau0)
 a<-step( tau[i]-t[ j+1] )
 b<-(step(tau[i]- t[j])-(step(tau[i]- t[j+1]))
 c<-(1-step( tau[i]-t[j]))
}
#prior
   tau[i]~dnorm(mutau,tautau)
   mutau~dorm(0,  0.001)
   tautau~dgamma(0.01, 0.01)
   sigmatau<-1/sqrt(tautau)
   mu1[i]~dnorm(mumu1, tau1)
   mumu1~dorm(0, 0.001)
   tau1~dgamma(0.01,0.01)
   sigmatau1<-1/sqrt(tau1)
   mu2[i]~dnorm(mumu2, tau2)
   mumu2~dorm(0, 0.001)
   tau2~dgamma(0.01,0.01)
   sigmatau2<-1/sqrt(tau2)

   tau0[i]~dgamma(alpha,beta)
   sigmatau0<-1/tau0
  }
}
DATA
list(n=5, m=16,   mutau=0, tautau=1,  mumu1=0, tau1=1,   mumu2=0, tau2=1, alpha=0.01, beta=0.01 )

I expected the right model syntax

Body:
b<-(step(tau[i]- t[j])-(step(tau[i]- t[j+1]))

(
    step(
            tau[i]- t[j]
        )
    -
    (
    step(
            tau[i]- t[j+1]
        )
    )

4 brackets opening, 3 brackets closing.
First bracket is not closed.


问:
Fastest way to perform complex search on pandas dataframe
I am trying to figure out the fastest way to perform search and sort on a pandas dataframe. Below are before and after dataframes of what I am trying to accomplish.

Before:

```<code>flightTo  flightFrom  toNum  fromNum  toCode  fromCode
   ABC       DEF       123     456     8000    8000
   DEF       XYZ       456     893     9999    9999
   AAA       BBB       473     917     5555    5555
   BBB       CCC       917     341     5555    5555
</code>```

After search/sort:

```<code>flightTo  flightFrom  toNum  fromNum  toCode  fromCode
   ABC       XYZ       123     893     8000    9999
   AAA       CCC       473     341     5555    5555
</code>```

In this example I am essentially trying to filter out 'flights' that exist in between end destinations. This should be done by using some sort of drop duplicates method but what leaves me confused is how to handle all of the columns. Would a binary search be the best way to accomplish this? Hints appreciated, trying hard to figure this out.

possible edge case:

What if the data is switched up and our end connections are in the same column?

```<code>flight1  flight2      1Num    2Num     1Code   2Code
   ABC       DEF       123     456     8000    8000
   XYZ       DEF       893     456     9999    9999
</code>```

After search/sort:

```<code>flight1  flight2      1Num    2Num     1Code   2Code
   ABC       XYZ       123     893     8000    9999
</code>```

This case logically shouldn't happen. After all how can you go DEF-ABC and DEF-XYZ? You can't, but the 'endpoints' would still be ABC-XYZ

答:
This is network problem , so we using networkx , notice , here you can have more than two stops , which means you can have some case like NY-DC-WA-NC

```<code>import networkx as nx
G=nx.from_pandas_edgelist(df, 'flightTo', 'flightFrom')

# create the nx object from pandas dataframe

l=list(nx.connected_components(G))

# then we get the list of components which as tied to each other ,
# in a net work graph , they are linked
L=[dict.fromkeys(y,x) for x, y in enumerate(l)]

# then from the above we can create our map dict ,
# since every components connected to each other ,
# then we just need to pick of of them as key , then map with others

d={k: v for d in L for k, v in d.items()}

# create the dict for groupby , since we need _from as first item and _to as last item
grouppd=dict(zip(df.columns.tolist(),['first','last']*3))
df.groupby(df.flightTo.map(d)).agg(grouppd) # then using agg with dict yield your output

Out[22]:
         flightTo flightFrom  toNum  fromNum  toCode  fromCode
flightTo
0             ABC        XYZ    123      893    8000      9999
1             AAA        CCC    473      341    5555      5555
</code>```

Installation networkx

Pip: pip install networkx

Anaconda: conda install -c anaconda networkx

Body:
I am trying to figure out the fastest way to perform search and sort on a pandas dataframe. Below are before and after dataframes of what I am trying to accomplish.

Before:

flightTo  flightFrom  toNum  fromNum  toCode  fromCode
   ABC       DEF       123     456     8000    8000
   DEF       XYZ       456     893     9999    9999
   AAA       BBB       473     917     5555    5555
   BBB       CCC       917     341     5555    5555

After search/sort:

flightTo  flightFrom  toNum  fromNum  toCode  fromCode
   ABC       XYZ       123     893     8000    9999
   AAA       CCC       473     341     5555    5555

In this example I am essentially trying to filter out 'flights' that exist in between end destinations. This should be done by using some sort of drop duplicates method but what leaves me confused is how to handle all of the columns. Would a binary search be the best way to accomplish this? Hints appreciated, trying hard to figure this out.

possible edge case:

What if the data is switched up and our end connections are in the same column?

flight1  flight2      1Num    2Num     1Code   2Code
   ABC       DEF       123     456     8000    8000
   XYZ       DEF       893     456     9999    9999

After search/sort:

flight1  flight2      1Num    2Num     1Code   2Code
   ABC       XYZ       123     893     8000    9999

This case logically shouldn't happen. After all how can you go DEF-ABC and DEF-XYZ? You can't, but the 'endpoints' would still be ABC-XYZ

Body:
This is network problem , so we using networkx , notice , here you can have more than two stops , which means you can have some case like NY-DC-WA-NC

import networkx as nx
G=nx.from_pandas_edgelist(df, 'flightTo', 'flightFrom')

# create the nx object from pandas dataframe

l=list(nx.connected_components(G))

# then we get the list of components which as tied to each other ,
# in a net work graph , they are linked
L=[dict.fromkeys(y,x) for x, y in enumerate(l)]

# then from the above we can create our map dict ,
# since every components connected to each other ,
# then we just need to pick of of them as key , then map with others

d={k: v for d in L for k, v in d.items()}

# create the dict for groupby , since we need _from as first item and _to as last item
grouppd=dict(zip(df.columns.tolist(),['first','last']*3))
df.groupby(df.flightTo.map(d)).agg(grouppd) # then using agg with dict yield your output

Out[22]:
         flightTo flightFrom  toNum  fromNum  toCode  fromCode
flightTo
0             ABC        XYZ    123      893    8000      9999
1             AAA        CCC    473      341    5555      5555

Installation networkx

Pip: pip install networkx

Anaconda: conda install -c anaconda networkx


问:
.NET Core multi authentications with dynamic policy provider authorization
.NET Core 2.0 API:

First I tried to use IAuthorizationPolicyProvider to have dynamic policies:

```<code>public class MyAuthorizationPolicyProvider: IAuthorizationPolicyProvider
{
    internal const string PolicyPrefix = "MyJwt";

    public Task<AuthorizationPolicy> GetDefaultPolicyAsync()
    {
        return Task.FromResult<AuthorizationPolicy>(new AuthorizationPolicyBuilder(Array.Empty<string>()).RequireAuthenticatedUser().Build());
    }

    public Task<AuthorizationPolicy> GetPolicyAsync(string policyName)
    {
        if(!policyName.StartsWith(PolicyPrefix, StringComparison.OrdinalIgnoreCase))
            return Task.FromResult<AuthorizationPolicy>((AuthorizationPolicy)null);

        var authorizationPolicyBuilder = new AuthorizationPolicyBuilder(Array.Empty<string>());
        authorizationPolicyBuilder.AddRequirements((IAuthorizationRequirement)new MyAuthorizationRequirement(policyName.Substring(PolicyPrefix.Length)));
        return Task.FromResult<AuthorizationPolicy>(authorizationPolicyBuilder.Build());
    }
}

public class MyAuthorizationHandler: AuthorizationHandler<MyAuthorizationRequirement>
{

    protected override Task HandleRequirementAsync(AuthorizationHandlerContext context, MyAuthorizationRequirement requirement)
    {
        if(!context.User.Identity.IsAuthenticated)
        {
            context.Fail();
            return Task.CompletedTask;
        }

        if(SomeLibrary.IsContextValid(context, requirement))
            context.Succeed((IAuthorizationRequirement)requirement);
        else
            context.Fail();

        return Task.CompletedTask;
    }
}
</code>```

And Add Authentication:

```<code>services.AddAuthentication(options =>
    {
        options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
        options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;

    }).AddJwtBearer(options =>
    {
        options.TokenValidationParameters = GetTokenValidationParameters();
    });

    services.AddSingleton<IAuthorizationHandler, MyAuthorizationHandler>();
    services.AddSingleton<IAuthorizationPolicyProvider, MyAuthorizationPolicyProvider>();
</code>```

And My Authorize attribute:

```<code>public class MyAuthorizeAttribute: AuthorizeAttribute
{

    internal const string PolicyPrefix = "MyJwt";

    public MyAuthorizeAttribute(string permission)
    {
        this.Permission = permission;
    }

    public string Permission
    {
        get
        {
            if(this.Policy.Length < PolicyPrefix.Length)
                return (string)null;
            return this.Policy.Substring(PolicyPrefix.Length);
        }
        set
        {
            this.Policy = PolicyPrefix + value;
        }
    }
}
</code>```

And i used: [MyAuthorize("anythings")]

So far everything was good. Now I need to add a new authentication (I mean both work together).

So I changed the MyAuthorizationPolicyProvider to support new policies:

```<code>public class MyAuthorizationPolicyProvider: IAuthorizationPolicyProvider
    {
        internal const string PolicyPrefix = "MyJwt";

        public Task<AuthorizationPolicy> GetDefaultPolicyAsync()
        {
            return Task.FromResult<AuthorizationPolicy>(new AuthorizationPolicyBuilder(Array.Empty<string>()).RequireAuthenticatedUser().Build());
        }

        public Task<AuthorizationPolicy> GetPolicyAsync(string policyName)
        {

             if(policyName == "newpolicy") //here
                return AddNewPolicy();

            if(!policyName.StartsWith(PolicyPrefix, StringComparison.OrdinalIgnoreCase))
                return Task.FromResult<AuthorizationPolicy>((AuthorizationPolicy)null);

            var authorizationPolicyBuilder = new AuthorizationPolicyBuilder(Array.Empty<string>());
            authorizationPolicyBuilder.AddRequirements((IAuthorizationRequirement)new MyAuthorizationRequirement(policyName.Substring(PolicyPrefix.Length)));
            return Task.FromResult<AuthorizationPolicy>(authorizationPolicyBuilder.Build());
        }
    }
</code>```

And Change Add Authentication:

```<code>services.AddAuthentication(options =>
    {
        options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
        options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;

    }).AddJwtBearer(JwtBearerDefaults.AuthenticationScheme, options =>
    {
        options.TokenValidationParameters = GetTokenValidationParameters();
    })
    .AddJwtBearer("newSchema", options =>
    {
        options.TokenValidationParameters = GetNewSchemaTokenValidationParameters();
    });

    services.AddSingleton<IAuthorizationHandler, MyAuthorizationHandler>();
    services.AddSingleton<IAuthorizationHandler, MyNewAuthorizationHandler>();
    services.AddSingleton<IAuthorizationPolicyProvider, MyAuthorizationPolicyProvider>();
</code>```

And MyNewAuthorizationHandler is:

```<code>public class MyNewAuthorizationHandler: AuthorizationHandler<MyNewAuthorizationRequirement>
{

    protected override Task HandleRequirementAsync(AuthorizationHandlerContext context, MyNewAuthorizationRequirement requirement)
    {
        if(!context.User.Identity.IsAuthenticated)
        {
            context.Fail();
            return Task.CompletedTask;
        }

        if(SomeNewLibrary.IsContextValid(context, requirement))
            context.Succeed((IAuthorizationRequirement)requirement);
        else
            context.Fail();

        return Task.CompletedTask;
    }
}
</code>```

And I use [Authorize(Policy = "newpolicy")]

Now The first authentication works fine with MyAuthorizationHandler but the second authentication failed in MyNewAuthorizationHandler because the user is not authenticated and this line return failed: if(!context.User.Identity.IsAuthenticated)

What I missed?

How could I have multi authentication and in the same time use IAuthorizationPolicyProvider for add policies dynamically?

I know if I change AddAuthentication to:

```<code>services.AddAuthentication(options =>
{
    options.DefaultAuthenticateScheme = "newSchema"; //here
    options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;

}).AddJwtBearer(JwtBearerDefaults.AuthenticationScheme, options =>
{
    options.TokenValidationParameters = GetTokenValidationParameters();
})
.AddJwtBearer("newSchema", options =>
{
    options.TokenValidationParameters = GetNewSchemaTokenValidationParameters();
});
</code>```

Then the second one works fine and first one failed, How could I make both schema authenticated?

答:
After some search here is what I found: multiple-authorization-policy-providers.

First change MyAuthorizationPolicyProvider to support all other policies:

```<code>public class MyAuthorizationPolicyProvider: IAuthorizationPolicyProvider
{
    private readonly DefaultAuthorizationPolicyProvider _fallbackPolicyProvider;
    internal const string PolicyPrefix = "MyJwt";

    public MyAuthorizationPolicyProvider(IOptions<AuthorizationOptions> options)
    {
        _fallbackPolicyProvider = new DefaultAuthorizationPolicyProvider(options);
    }

    public Task<AuthorizationPolicy> GetDefaultPolicyAsync()
    {
        return Task.FromResult<AuthorizationPolicy>(new AuthorizationPolicyBuilder(Array.Empty<string>()).RequireAuthenticatedUser().Build());
    }

    public Task<AuthorizationPolicy> GetPolicyAsync(string policyName)
    {

        if(!policyName.StartsWith(PolicyPrefix, StringComparison.OrdinalIgnoreCase))
            return _fallbackPolicyProvider.GetPolicyAsync(policyName); //here return back to static policies

        var authorizationPolicyBuilder = new AuthorizationPolicyBuilder(Array.Empty<string>());
        authorizationPolicyBuilder.AddRequirements((IAuthorizationRequirement)new MyAuthorizationRequirement(policyName.Substring(PolicyPrefix.Length)));
        return Task.FromResult<AuthorizationPolicy>(authorizationPolicyBuilder.Build());
    }
}
</code>```

Then modify the way of adding authentications:

```<code>services.AddAuthentication(options =>
{
    options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
    options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;

}).AddJwtBearer(JwtBearerDefaults.AuthenticationScheme, options =>
{
    options.TokenValidationParameters = GetTokenValidationParameters();
})
.AddJwtBearer("newSchema", options =>
{
    options.TokenValidationParameters = GetNewSchemaTokenValidationParameters();
});

services.AddAuthorization(options =>
{
    options.DefaultPolicy = new AuthorizationPolicyBuilder()
        .RequireAuthenticatedUser()
        .AddAuthenticationSchemes("newSchema") //add new schemas here
        .Build();

    //here: add static policies as much as you want
    options.AddPolicy("newpolicy", new AuthorizationPolicyBuilder()
        .RequireAuthenticatedUser()
        .AddAuthenticationSchemes("newSchema")
        .AddRequirements(new MyNewAuthorizationRequirement("newpolicy"))
        .Build());

});

services.AddSingleton<IAuthorizationHandler, MyAuthorizationHandler>();
services.AddSingleton<IAuthorizationHandler, MyNewAuthorizationHandler>();
services.AddSingleton<IAuthorizationPolicyProvider, MyAuthorizationPolicyProvider>();
</code>```

Body:
.NET Core 2.0 API:

First I tried to use IAuthorizationPolicyProvider to have dynamic policies:

public class MyAuthorizationPolicyProvider: IAuthorizationPolicyProvider
{
    internal const string PolicyPrefix = "MyJwt";

    public Task<AuthorizationPolicy> GetDefaultPolicyAsync()
    {
        return Task.FromResult<AuthorizationPolicy>(new AuthorizationPolicyBuilder(Array.Empty<string>()).RequireAuthenticatedUser().Build());
    }

    public Task<AuthorizationPolicy> GetPolicyAsync(string policyName)
    {
        if(!policyName.StartsWith(PolicyPrefix, StringComparison.OrdinalIgnoreCase))
            return Task.FromResult<AuthorizationPolicy>((AuthorizationPolicy)null);

        var authorizationPolicyBuilder = new AuthorizationPolicyBuilder(Array.Empty<string>());
        authorizationPolicyBuilder.AddRequirements((IAuthorizationRequirement)new MyAuthorizationRequirement(policyName.Substring(PolicyPrefix.Length)));
        return Task.FromResult<AuthorizationPolicy>(authorizationPolicyBuilder.Build());
    }
}

public class MyAuthorizationHandler: AuthorizationHandler<MyAuthorizationRequirement>
{

    protected override Task HandleRequirementAsync(AuthorizationHandlerContext context, MyAuthorizationRequirement requirement)
    {
        if(!context.User.Identity.IsAuthenticated)
        {
            context.Fail();
            return Task.CompletedTask;
        }

        if(SomeLibrary.IsContextValid(context, requirement))
            context.Succeed((IAuthorizationRequirement)requirement);
        else
            context.Fail();

        return Task.CompletedTask;
    }
}

And Add Authentication:

services.AddAuthentication(options =>
    {
        options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
        options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;

    }).AddJwtBearer(options =>
    {
        options.TokenValidationParameters = GetTokenValidationParameters();
    });

    services.AddSingleton<IAuthorizationHandler, MyAuthorizationHandler>();
    services.AddSingleton<IAuthorizationPolicyProvider, MyAuthorizationPolicyProvider>();

And My Authorize attribute:

public class MyAuthorizeAttribute: AuthorizeAttribute
{

    internal const string PolicyPrefix = "MyJwt";

    public MyAuthorizeAttribute(string permission)
    {
        this.Permission = permission;
    }

    public string Permission
    {
        get
        {
            if(this.Policy.Length < PolicyPrefix.Length)
                return (string)null;
            return this.Policy.Substring(PolicyPrefix.Length);
        }
        set
        {
            this.Policy = PolicyPrefix + value;
        }
    }
}

And i used: [MyAuthorize("anythings")]

So far everything was good. Now I need to add a new authentication (I mean both work together).

So I changed the MyAuthorizationPolicyProvider to support new policies:

public class MyAuthorizationPolicyProvider: IAuthorizationPolicyProvider
    {
        internal const string PolicyPrefix = "MyJwt";

        public Task<AuthorizationPolicy> GetDefaultPolicyAsync()
        {
            return Task.FromResult<AuthorizationPolicy>(new AuthorizationPolicyBuilder(Array.Empty<string>()).RequireAuthenticatedUser().Build());
        }

        public Task<AuthorizationPolicy> GetPolicyAsync(string policyName)
        {

             if(policyName == "newpolicy") //here
                return AddNewPolicy();

            if(!policyName.StartsWith(PolicyPrefix, StringComparison.OrdinalIgnoreCase))
                return Task.FromResult<AuthorizationPolicy>((AuthorizationPolicy)null);

            var authorizationPolicyBuilder = new AuthorizationPolicyBuilder(Array.Empty<string>());
            authorizationPolicyBuilder.AddRequirements((IAuthorizationRequirement)new MyAuthorizationRequirement(policyName.Substring(PolicyPrefix.Length)));
            return Task.FromResult<AuthorizationPolicy>(authorizationPolicyBuilder.Build());
        }
    }

And Change Add Authentication:

services.AddAuthentication(options =>
    {
        options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
        options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;

    }).AddJwtBearer(JwtBearerDefaults.AuthenticationScheme, options =>
    {
        options.TokenValidationParameters = GetTokenValidationParameters();
    })
    .AddJwtBearer("newSchema", options =>
    {
        options.TokenValidationParameters = GetNewSchemaTokenValidationParameters();
    });

    services.AddSingleton<IAuthorizationHandler, MyAuthorizationHandler>();
    services.AddSingleton<IAuthorizationHandler, MyNewAuthorizationHandler>();
    services.AddSingleton<IAuthorizationPolicyProvider, MyAuthorizationPolicyProvider>();

And MyNewAuthorizationHandler is:

public class MyNewAuthorizationHandler: AuthorizationHandler<MyNewAuthorizationRequirement>
{

    protected override Task HandleRequirementAsync(AuthorizationHandlerContext context, MyNewAuthorizationRequirement requirement)
    {
        if(!context.User.Identity.IsAuthenticated)
        {
            context.Fail();
            return Task.CompletedTask;
        }

        if(SomeNewLibrary.IsContextValid(context, requirement))
            context.Succeed((IAuthorizationRequirement)requirement);
        else
            context.Fail();

        return Task.CompletedTask;
    }
}

And I use [Authorize(Policy = "newpolicy")]

Now The first authentication works fine with MyAuthorizationHandler but the second authentication failed in MyNewAuthorizationHandler because the user is not authenticated and this line return failed: if(!context.User.Identity.IsAuthenticated)

What I missed?

How could I have multi authentication and in the same time use IAuthorizationPolicyProvider for add policies dynamically?

I know if I change AddAuthentication to:

services.AddAuthentication(options =>
{
    options.DefaultAuthenticateScheme = "newSchema"; //here
    options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;

}).AddJwtBearer(JwtBearerDefaults.AuthenticationScheme, options =>
{
    options.TokenValidationParameters = GetTokenValidationParameters();
})
.AddJwtBearer("newSchema", options =>
{
    options.TokenValidationParameters = GetNewSchemaTokenValidationParameters();
});

Then the second one works fine and first one failed, How could I make both schema authenticated?

Body:
After some search here is what I found: multiple-authorization-policy-providers.

First change MyAuthorizationPolicyProvider to support all other policies:

public class MyAuthorizationPolicyProvider: IAuthorizationPolicyProvider
{
    private readonly DefaultAuthorizationPolicyProvider _fallbackPolicyProvider;
    internal const string PolicyPrefix = "MyJwt";

    public MyAuthorizationPolicyProvider(IOptions<AuthorizationOptions> options)
    {
        _fallbackPolicyProvider = new DefaultAuthorizationPolicyProvider(options);
    }

    public Task<AuthorizationPolicy> GetDefaultPolicyAsync()
    {
        return Task.FromResult<AuthorizationPolicy>(new AuthorizationPolicyBuilder(Array.Empty<string>()).RequireAuthenticatedUser().Build());
    }

    public Task<AuthorizationPolicy> GetPolicyAsync(string policyName)
    {

        if(!policyName.StartsWith(PolicyPrefix, StringComparison.OrdinalIgnoreCase))
            return _fallbackPolicyProvider.GetPolicyAsync(policyName); //here return back to static policies

        var authorizationPolicyBuilder = new AuthorizationPolicyBuilder(Array.Empty<string>());
        authorizationPolicyBuilder.AddRequirements((IAuthorizationRequirement)new MyAuthorizationRequirement(policyName.Substring(PolicyPrefix.Length)));
        return Task.FromResult<AuthorizationPolicy>(authorizationPolicyBuilder.Build());
    }
}

Then modify the way of adding authentications:

services.AddAuthentication(options =>
{
    options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
    options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;

}).AddJwtBearer(JwtBearerDefaults.AuthenticationScheme, options =>
{
    options.TokenValidationParameters = GetTokenValidationParameters();
})
.AddJwtBearer("newSchema", options =>
{
    options.TokenValidationParameters = GetNewSchemaTokenValidationParameters();
});

services.AddAuthorization(options =>
{
    options.DefaultPolicy = new AuthorizationPolicyBuilder()
        .RequireAuthenticatedUser()
        .AddAuthenticationSchemes("newSchema") //add new schemas here
        .Build();

    //here: add static policies as much as you want
    options.AddPolicy("newpolicy", new AuthorizationPolicyBuilder()
        .RequireAuthenticatedUser()
        .AddAuthenticationSchemes("newSchema")
        .AddRequirements(new MyNewAuthorizationRequirement("newpolicy"))
        .Build());

});

services.AddSingleton<IAuthorizationHandler, MyAuthorizationHandler>();
services.AddSingleton<IAuthorizationHandler, MyNewAuthorizationHandler>();
services.AddSingleton<IAuthorizationPolicyProvider, MyAuthorizationPolicyProvider>();


问:
For loop with "Find" function
I have a dataset across two worksheets with approx. 59k rows in each.

I need to take a part number from sheet 1, defined as "wsBomb" and reference this against sheet 2, defined as "wsEam". Once you have this, there is an offset of 8 to get the supplier number and copy this back into "wsBomb".

I have this process working for the first piece of data. I am struggling to get this to work within a loop.

Edit

The findnextfunction has been implemented and is looping through and changing the part number as required. However, this is only referencing cell L2 and not incrementing:

Sub Macro1()

    Set wbTrying = Workbooks("RME EAM")
    Set wsBomb = wbTrying.Worksheets("Bomb")
    Set wsEam = wbTrying.Worksheets("EAM")

    rowCounterPartNumber = 2

    Set wf = Application.WorksheetFunction

    Set rng1 = wsBomb.Range("E" & rowCounterPartNumber)
    filterStr = wf.Transpose(rng1)

    Dim partNumber As Range
    Set partNumber = wsEam.Range("L:L").Find(What:=rng1.Value, LookIn:=xlValues, lookat:=xlWhole)
    Dim partNo

    For Each partNo In partNumber
        If Not partNo Is Nothing Then

            Do
                wsBomb.Range("D" & rowCounterPartNumber).Value = partNumber.Offset(, -8)
                rowCounterPartNumber = rowCounterPartNumber + 1
                Set partNumber = wsEam.Range("L2:L60000").FindNext(partNumber)

                If partNo Is Nothing Then
                    GoTo finished

                End If
            Loop While partNo <> ""
        End If

finished:

    Next

End Sub
```

Current output:

All part numbers are the same

The issue appears to be in the Set partNumber = wsEam.Range("L:L").Find(What:=rng1.Value, LookIn:=xlValues, lookat:=xlWhole) section, as the rowCounterPartNumber does not increment for column E or L.

I think is due to these being defined outside the loop.

答:
Try this:</p>

```<code>Sub Macro1()

Set wbTrying = Workbooks("RME EAM")
Set wsBomb = wbTrying.Worksheets("Bomb")
Set wsEam = wbTrying.Worksheets("EAM")

Dim s As String
rowCounterPartNumber = 2

Set wf = Application.WorksheetFunction

Set rng1 = wsBomb.Range("E" & rowCounterPartNumber)
filterStr = wf.Transpose(rng1)

Dim partNumber As Range
Set partNumber = wsEam.Range("L:L").Find(What:=rng1.Value, LookIn:=xlValues, lookat:=xlWhole)

If Not partNumber Is Nothing Then 'if found
    s = partNumber.Address        'store address of first found cell
    Do
        wsBomb.Range("D" & rowCounterPartNumber).Value = partNumber.Offset(, -8)
        rowCounterPartNumber = rowCounterPartNumber + 1
        Set partNumber = wsEam.Range("L:L").FindNext(partNumber)
    Loop Until partNumber.Address = s  'repeat until back to first found cell
End If

End Sub
</code>```

Title: For loop with "Find" function

Body:
I have a dataset across two worksheets with approx. 59k rows in each.

I need to take a part number from sheet 1, defined as "wsBomb" and reference this against sheet 2, defined as "wsEam". Once you have this, there is an offset of 8 to get the supplier number and copy this back into "wsBomb".

I have this process working for the first piece of data. I am struggling to get this to work within a loop.

Edit

The findnextfunction has been implemented and is looping through and changing the part number as required. However, this is only referencing cell L2 and not incrementing:

Sub Macro1()

    Set wbTrying = Workbooks("RME EAM")
    Set wsBomb = wbTrying.Worksheets("Bomb")
    Set wsEam = wbTrying.Worksheets("EAM")

    rowCounterPartNumber = 2

    Set wf = Application.WorksheetFunction

    Set rng1 = wsBomb.Range("E" & rowCounterPartNumber)
    filterStr = wf.Transpose(rng1)

    Dim partNumber As Range
    Set partNumber = wsEam.Range("L:L").Find(What:=rng1.Value, LookIn:=xlValues, lookat:=xlWhole)
    Dim partNo

    For Each partNo In partNumber
        If Not partNo Is Nothing Then

            Do
                wsBomb.Range("D" & rowCounterPartNumber).Value = partNumber.Offset(, -8)
                rowCounterPartNumber = rowCounterPartNumber + 1
                Set partNumber = wsEam.Range("L2:L60000").FindNext(partNumber)

                If partNo Is Nothing Then
                    GoTo finished

                End If
            Loop While partNo <> ""
        End If

finished:

    Next

End Sub

Current output:

All part numbers are the same

The issue appears to be in the Set partNumber = wsEam.Range("L:L").Find(What:=rng1.Value, LookIn:=xlValues, lookat:=xlWhole) section, as the rowCounterPartNumber does not increment for column E or L.

I think is due to these being defined outside the loop.

Body:
Try this:

Sub Macro1()

Set wbTrying = Workbooks("RME EAM")
Set wsBomb = wbTrying.Worksheets("Bomb")
Set wsEam = wbTrying.Worksheets("EAM")

Dim s As String
rowCounterPartNumber = 2

Set wf = Application.WorksheetFunction

Set rng1 = wsBomb.Range("E" & rowCounterPartNumber)
filterStr = wf.Transpose(rng1)

Dim partNumber As Range
Set partNumber = wsEam.Range("L:L").Find(What:=rng1.Value, LookIn:=xlValues, lookat:=xlWhole)

If Not partNumber Is Nothing Then 'if found
    s = partNumber.Address        'store address of first found cell
    Do
        wsBomb.Range("D" & rowCounterPartNumber).Value = partNumber.Offset(, -8)
        rowCounterPartNumber = rowCounterPartNumber + 1
        Set partNumber = wsEam.Range("L:L").FindNext(partNumber)
    Loop Until partNumber.Address = s  'repeat until back to first found cell
End If

End Sub


问:
What tools do you use to develop C++ applications on Linux?
I develop C++ applications in a Linux environment.  The tools I use every day include Eclipse with the CDT plugin, gdb and valgrind.

What tools do other people use?  Is there anything out there for Linux that rivals the slickness of Microsoft Visual Studio?

答:
g++

emacs

bash command line

gdb-mode in emacs (type M-X gdb)

make

OwnerDisplayName: Clayton

ContentLicense: CC BY-SA 2.5

OwnerDisplayName: Colin


问:
Multiple Upload tool, script or plugin?

I'm trying to make an upload function in this website I'm working on, but till now no succes.

I tried using Plupload, but can't get it to work. Same goes for Uploadify, can't find any tutorial or good explanation in how to install these plugins in your webpage.

Does anybody know a good and easy to use multiple upload tool I can easily implement in the page?

Thanks in advance!

答:
Well, from the comments on the question:

It doesn't get much easier than
  Uploadify.

See here for detailed instructions: http://www.uploadify.com/documentation/

Title: Multiple Upload tool, script or plugin?


问:
Is there a callBack to SetContentView in Android?
Is there any callBack to setContentView in Android, since i'm doing a heavy operation right after setContentView line, and it seems to skip that setContentView.

So i was thinking of moving the heavyOperation to the callBack of setContentView.

Thanks

EDIT:

Pseudo Code:

AudioRecord Finishes
SetContentView(1) //To show a "Processing" screen with no buttons
FFT analysis
SetContentView(2) //On FFT analysis DONE.

In my case "SetContentView(1)" NEVER occurs.

EDIT # 2:
I did the heavy operation in another Thread, and used Handler to send a Message after heavy operation finishes to treat it as a callBack.

Thanks for all the help guys

答:
I was facing a quite similar problem a day ago, but I figured it out. (I know your problem is solved, just offering a different approach which doesn't require a handler or callback.

Most Suitable for running U.I. functions :
If you need to do something like this :runTask() then
setContentView()  (or any other ui function) you can run the task on different thread by using AsyncTask or you can set a timer for when the task is completed (if your task takes a certain time), the User Interface functions will be called.
But since the Timer class, runs the functions on a different thread, you can not run the setContentView() inside it. So you can use a runOnUiThread(Runnable action) method inside the overloaded run() function of Timer class. You just need to define a function that returns a runnable. Define your Ui operations in the runnable action.

Hope it helps someone.


问:
JavaFX TableView editable(true) don't work
I have this code:

```<code>public static void main(String[] ar){ launch(ar); }

@Override
public void start(Stage primaryStage){

    TableView<Foo> tableView = new TableView<>();
    tableView.setColumnResizePolicy(TableView.UNCONSTRAINED_RESIZE_POLICY);
    tableView.setPlaceholder(new Label("No data"));
    tableView.setEditable(true);

    TableColumn<Foo, String> colText = new TableColumn<>("Text");
    colText.setCellValueFactory(new PropertyValueFactory<>("text"));

    tableView.getColumns().add(colText);

    List<Foo> listFoo = new ArrayList<>(Arrays.asList(new Foo("1"), new Foo("2"), new Foo("3")));

    tableView.setItems(FXCollections.observableArrayList(listFoo));

    primaryStage.setScene(new Scene(tableView));
    primaryStage.show();

}

public class Foo{

    private String text;

    public Foo(String txt){ text = txt; }

    public String getText(){ return text; }

    public void setText(String text){ this.text = text; }

}
</code>```

I try to make the cells of table editable: tableView.setEditable(true);, but it don't work.

How can I make cells of table editable or to have posibility to copy the value from cell into clipboard.

答:
For a TableCell to be editable, 3 conditions need to be fulfilled:

The containing TableView is editable

The containing TableColumn is editable

The cell itself is editable

In your case the 3rd condition is not fulfilled, since the cells created by the default cellFactory are not editable. You need to assign a cellFactory that allows for editing. Furthermore note that unless the cellValueFactory returns an object implementing WritableValue, you also need to use the onEditCommit handler to store the data in the item:

```<code>colText.setCellFactory(TextFieldTableCell.forTableColumn());
colText.setOnEditCommit(evt -> evt.getRowValue().setText(evt.getNewValue()));
</code>```

Body:
I have this code:

public static void main(String[] ar){ launch(ar); }

@Override
public void start(Stage primaryStage){

    TableView<Foo> tableView = new TableView<>();
    tableView.setColumnResizePolicy(TableView.UNCONSTRAINED_RESIZE_POLICY);
    tableView.setPlaceholder(new Label("No data"));
    tableView.setEditable(true);

    TableColumn<Foo, String> colText = new TableColumn<>("Text");
    colText.setCellValueFactory(new PropertyValueFactory<>("text"));

    tableView.getColumns().add(colText);

    List<Foo> listFoo = new ArrayList<>(Arrays.asList(new Foo("1"), new Foo("2"), new Foo("3")));

    tableView.setItems(FXCollections.observableArrayList(listFoo));

    primaryStage.setScene(new Scene(tableView));
    primaryStage.show();

}

public class Foo{

    private String text;

    public Foo(String txt){ text = txt; }

    public String getText(){ return text; }

    public void setText(String text){ this.text = text; }

}

I try to make the cells of table editable: tableView.setEditable(true);, but it don't work.

How can I make cells of table editable or to have posibility to copy the value from cell into clipboard.

Body:
For a TableCell to be editable, 3 conditions need to be fulfilled:

The containing TableView is editable

The containing TableColumn is editable

The cell itself is editable

In your case the 3rd condition is not fulfilled, since the cells created by the default cellFactory are not editable. You need to assign a cellFactory that allows for editing. Furthermore note that unless the cellValueFactory returns an object implementing WritableValue, you also need to use the onEditCommit handler to store the data in the item:

colText.setCellFactory(TextFieldTableCell.forTableColumn());
colText.setOnEditCommit(evt -> evt.getRowValue().setText(evt.getNewValue()));


问:
How bind validation to RadioButton WPF
I have some problem with Radiobutton binding to show validation.

I create two RadioButtons

```<code><StackPanel Grid.Column="2" Grid.Row="1" Orientation="Horizontal" VerticalAlignment="Top" Margin="0,13,0,0">
    <RadioButton IsChecked="{Binding EndUser, Mode=TwoWay}" Content="End User" />
    <RadioButton IsChecked="{Binding AppDeveloper, Mode=TwoWay}" Margin="15,0,0,0" Content="App Developer"/>
</StackPanel>
</code>```

for my logic I should take 1 name from 2.

I write the logic

```<code>[Required]
    public string Role
    {
        get => role;
        set
        {
            Set(ref role, value);
            RaisePropertyChanged("EndUser");
            RaisePropertyChanged("AppDeveloper");
        }
    }

    public bool EndUser
    {
        get => Role.Contains("EndUser");
        set => Role = "EndUser";
    }

    public bool AppDeveloper
    {
        get => Role.Contains("AppDeveloper");
        set => Role = "AppDeveloper";
    }
</code>```

the problem is how show [Required] in a form, and if i choose 1 of them, the validation will be true (validation work right if it's need i show the validation code)

I find this Validation Rule for Radio buttons wpf ,but this example doesn't work for me, broke all logic(doesn't send to me anything) and doesn't mark my field.

how write the

```<code> <Binding.ValidationRules>
     <DataErrorValidationRule />
 </Binding.ValidationRules>
</code>```

for radiobutton fields like in TextBox and mark it red?

my button  which disable if the fields is not valid

```<code><Button x:Name="SignInButton" Command="{Binding SignInCommand}" Grid.Row="4" Grid.Column="1" Grid.ColumnSpan="2"  Content="Sign In" >
        <Button.Style>
            <Style TargetType="{x:Type Button}">
                <Setter Property="Background" Value="MidnightBlue"/>
                <Setter Property="Foreground" Value="White"/>
                <Setter Property="FontSize" Value="16"/>
                <Setter Property="FontWeight" Value="Bold"/>
                <Setter Property="Width" Value="100"/>
                <Setter Property="Height" Value="40"/>
                <Setter Property="Template">
                    <Setter.Value>
                        <ControlTemplate TargetType="{x:Type Button}">
                            <Border Background="{TemplateBinding Background}" CornerRadius="10">
                                <ContentPresenter HorizontalAlignment="Center" VerticalAlignment="Center" Height="23" Margin="24,5,24,4"/>
                            </Border>
                        </ControlTemplate>
                    </Setter.Value>
                </Setter>
                <Setter Property="IsEnabled" Value="False"/>
                <Style.Triggers>
                    <MultiDataTrigger>
                        <MultiDataTrigger.Conditions>
                            <Condition Binding="{Binding Path=(Validation.HasError), ElementName=Password}" Value="False"/>
                            <Condition Binding="{Binding Path=(Validation.HasError), ElementName=Login}" Value="False"/>
                            <Condition Binding="{Binding Path=(Validation.HasError), ElementName=Role}" Value="False"/>
                        </MultiDataTrigger.Conditions>
                        <Setter Property="IsEnabled" Value="True"/>
                    </MultiDataTrigger>

                    <Trigger Property="IsMouseOver" Value="True">
                        <Setter Property="Background" Value="#FF280895"/>
                    </Trigger>
                </Style.Triggers>
            </Style>
        </Button.Style>
    </Button>
</code>```

in MultiDataTrigger i write the rule, if  Validation.HasError for the field the button is disable

答:
You could for example put a Border around the RadioButtons and use a Style with a DataTrigger that binds to the Role property:

```<code><Border Grid.Column="2" Grid.Row="1" BorderBrush="Red" Margin="0,13,0,0">
    <StackPanel Orientation="Horizontal" VerticalAlignment="Top">
        <RadioButton IsChecked="{Binding EndUser, Mode=TwoWay}" Content="End User" />
        <RadioButton IsChecked="{Binding AppDeveloper, Mode=TwoWay}" Margin="15,0,0,0" Content="App Developer"/>
    </StackPanel>
    <Border.Style>
        <Style TargetType="Border">
            <Style.Triggers>
                <DataTrigger Binding="{Binding Role}" Value="{x:Null}">
                    <Setter Property="BorderThickness" Value="1" />
                </DataTrigger>
            </Style.Triggers>
        </Style>
    </Border.Style>
</Border>
</code>```

You should then make the setter of the Role private and make sure to raise the PropertyChanged event for the involved properties:

```<code>private string role;
[Required]
public string Role
{
    get => role;
    private set
    {
        role = value;
        RaisePropertyChanged("Role");
    }
}

public bool EndUser
{
    get => Role == "EndUser";
    set
    {
        Role = "EndUser";
        RaisePropertyChanged("EndUser");
        RaisePropertyChanged("AppDeveloper");
    }
}

public bool AppDeveloper
{
    get => Role == "AppDeveloper";
    set
    {
        Role = "AppDeveloper";
        RaisePropertyChanged("AppDeveloper");
        RaisePropertyChanged("EndUser");
    }
}
</code>```

Title: How bind validation to RadioButton WPF

Body:
I have some problem with Radiobutton binding to show validation.

I create two RadioButtons

<StackPanel Grid.Column="2" Grid.Row="1" Orientation="Horizontal" VerticalAlignment="Top" Margin="0,13,0,0">
    <RadioButton IsChecked="{Binding EndUser, Mode=TwoWay}" Content="End User" />
    <RadioButton IsChecked="{Binding AppDeveloper, Mode=TwoWay}" Margin="15,0,0,0" Content="App Developer"/>
</StackPanel>

for my logic I should take 1 name from 2.

I write the logic

[Required]
    public string Role
    {
        get => role;
        set
        {
            Set(ref role, value);
            RaisePropertyChanged("EndUser");
            RaisePropertyChanged("AppDeveloper");
        }
    }

    public bool EndUser
    {
        get => Role.Contains("EndUser");
        set => Role = "EndUser";
    }

    public bool AppDeveloper
    {
        get => Role.Contains("AppDeveloper");
        set => Role = "AppDeveloper";
    }

the problem is how show [Required] in a form, and if i choose 1 of them, the validation will be true (validation work right if it's need i show the validation code)

I find this Validation Rule for Radio buttons wpf ,but this example doesn't work for me, broke all logic(doesn't send to me anything) and doesn't mark my field.

how write the

 <Binding.ValidationRules>
     <DataErrorValidationRule />
 </Binding.ValidationRules>

for radiobutton fields like in TextBox and mark it red?

my button  which disable if the fields is not valid

<Button x:Name="SignInButton" Command="{Binding SignInCommand}" Grid.Row="4" Grid.Column="1" Grid.ColumnSpan="2"  Content="Sign In" >
        <Button.Style>

            </Style>
        </Button.Style>
    </Button>

in MultiDataTrigger i write the rule, if  Validation.HasError for the field the button is disable

Body:
You could for example put a Border around the RadioButtons and use a Style with a DataTrigger that binds to the Role property:

<Border Grid.Column="2" Grid.Row="1" BorderBrush="Red" Margin="0,13,0,0">
    <StackPanel Orientation="Horizontal" VerticalAlignment="Top">
        <RadioButton IsChecked="{Binding EndUser, Mode=TwoWay}" Content="End User" />
        <RadioButton IsChecked="{Binding AppDeveloper, Mode=TwoWay}" Margin="15,0,0,0" Content="App Developer"/>
    </StackPanel>
    <Border.Style>
        <Style TargetType="Border">
            <Style.Triggers>
                <DataTrigger Binding="{Binding Role}" Value="{x:Null}">
                    <Setter Property="BorderThickness" Value="1" />
                </DataTrigger>
            </Style.Triggers>
        </Style>
    </Border.Style>
</Border>

You should then make the setter of the Role private and make sure to raise the PropertyChanged event for the involved properties:

private string role;
[Required]
public string Role
{
    get => role;
    private set
    {
        role = value;
        RaisePropertyChanged("Role");
    }
}

public bool EndUser
{
    get => Role == "EndUser";
    set
    {
        Role = "EndUser";
        RaisePropertyChanged("EndUser");
        RaisePropertyChanged("AppDeveloper");
    }
}

public bool AppDeveloper
{
    get => Role == "AppDeveloper";
    set
    {
        Role = "AppDeveloper";
        RaisePropertyChanged("AppDeveloper");
        RaisePropertyChanged("EndUser");
    }
}


问:
Mongodb avoid duplicate entries
I am newbie to mongodb. May I know how to avoid duplicate entries. In relational tables, we use primary key to avoid it. May I know how to specify it in Mongodb using java?</p>

答:
using pymongo it looks like:

```<code>mycol.create_index("id", unique=True)
</code>```

where myCol is the collection in the DB

```<code>#!/usr/bin/env python
# -*- coding: utf-8 -*-
import pymongo

myclient = pymongo.MongoClient("mongodb://localhost:27017/")
mydb = myclient["mydatabase"]
mycol = mydb["customers"]
mycol.create_index("id", unique=True)
mydict = {"name": "xoce", "address": "Highway to hell 666", "id": 1}
x = mycol.insert_one(mydict)
</code>```

Title: Mongodb avoid duplicate entries

Body:
using pymongo it looks like:

mycol.create_index("id", unique=True)

where myCol is the collection in the DB

#!/usr/bin/env python
# -*- coding: utf-8 -*-
import pymongo

myclient = pymongo.MongoClient("mongodb://localhost:27017/")
mydb = myclient["mydatabase"]
mycol = mydb["customers"]
mycol.create_index("id", unique=True)
mydict = {"name": "xoce", "address": "Highway to hell 666", "id": 1}
x = mycol.insert_one(mydict)


问:
Vertical Axis in chart repeating values - SQL Reporting Services 2008
Hi i have the following problem.

I'm doing a chart in SSRS 2008. I'm doing a count and the result of the count is 2.

Because of the little count the chart is repeating th values on the Y axis. This is not happening when the count is 50 for example.

How can i get rid of the repeating values 1 1 and 2 2. Of course if i set the interval to 1 the problem is fixed but if the count is 50 the interval will show from 0 to 50(0, 1, 2 ... 50 and i don't want that)

I hope someone has the answer, thank you.

答:
You can set the interval property of the Y axis to resolve the issue. To set the interval property

Right click on the Y axis.

Go to Axis Properties

In Axis Options you will find “Interval” under “set axis scale and style” section.

Click on fx button and replace the value =IIF( Fields!columnname.Value < 10,  1,  0)

Click OK -> OK

That’s all.


问:
How to place autocomplete menu above the text input?
Is there any way to display the Autocomplete result set above the text input?

The problem is that I am using it in a lighbox application. The background element being set to 100% of the pages' height and width, it will naturally not expand with its content. So if the content above the text box increases so much that the input is forced towards the bottom of the page, and then the user types something into it, the autocomplete menu appears, and the input being towards the end of the page, the menu causes scrollbars to appear

Since the background element (dark colored) won't expand to accommodate it, as the menu is absolutely positioned, it looks visually ugly that the bottom of the page appears white (consistent with the actual page's color) while the top of the page dark.

So is there anyway to accomplish this, that prior to the autocomplete menu appearing, the position of the input should be checked. If it is, say, at more than 300px from the top, then the menu should appear above the input? This is the code:

```<code><!DOCTYPE html>
<html>
<head>
<title>Filter</title>
<link type="text/css" href="ui/ui.css" rel="stylesheet" />
        <script type="text/javascript" src="jquery.js"></script>
        <script type="text/javascript" src="ui.js"></script>
<style>
div.filtertab { display: inline-block; height: 30px; background:url(filter.png); border-radius: 5px; position: relative;  margin: 10px 45px 10px 8px; cursor: pointer; -moz-user-select: none; box-shadow: 4px 2px 2px #aaaaaa; }

div.filtertab span.filtertext { position: relative;  margin-top: 4px; margin-left: 11px; margin-right: 1px;font-family:cursive,"Comic Sans"; font-size: 0.9em; float: left; display: inline-block; }

span.arrow { display: inline-block; border-top: 5px solid transparent; width: 0px; height: 0px; border-bottom: 5px solid transparent; border-right: 8.66px solid transparent; border-left: 8.66px solid #333333; margin-left: 7px; margin-top: 10.5px; }

.dateheaders { background: url(select.png); width: 120px; height: 28px; position: absolute; top: 0px; left: 0px; border-radius: 5px; cursor: pointer; display: inline-block; z-index: 55; }

.toheader { left: 183px }

.spandatew { font-weight: bold; position: relative; top: 2px; left: 6px; color: white; font-family: "lucida grande",tahoma,verdana,arial,sans-serif; font-weight: bold; color: white; font-size: 0.8em; }

div.arrow { height: 0px; width: 0px; position: absolute; display: inline-block; border-bottom: 5px solid transparent; border-right: 5px solid transparent; border-left: 5px solid transparent; border-top: 5px solid white;  right: 8px; top: 12px; }

input#from,input#to {width:107px;height:20px; position: relative; top: -30px; opacity: 0.01; cursor: pointer; }

input#from { left: 22px; }

input#to { left: 79px; }

div#ui-datepicker-div { left: -10px; }

div#diva1 {  width: 190px; position: absolute; display: none; z-index: 10; outline: none;}

div#diva2 {  width: 190px; position: absolute; display: none; z-index: 10; outline: none;}

#datecontainer { position: relative; width: 400px; height: 30px; background: red; left: 10px; }

.inpdiv { position: relative; margin-top: 6px; margin-left: 7px; background: #E2E6FF;  border-radius: 3px;  margin-bottom: 5px; display inline-block; float: left; margin-right: 3px; }

.inpdiv span.content { position: relative; top: 1px; left: 2px; padding: 2px 5px 6px 2px; font-size: 0.9em; display: inline-block; font-family: cursive,"Comic Sans";}

.inpdiv span.cancel { display: inline-block; border-radius: 3px; position: relative; top: 5px; margin: 3px 3px 3px 4px; height: 12px; width:12px; background: #bdbbae; cursor: pointer; }

.letter { position: absolute; display: inline-block; right: 4.4px; top: 4.7px; cursor: pointer; FONT-FAMILY: SANS-SERIF; FONT-SIZE: 0.9EM; }

div.friends { width: 400px;   position: relative;  overflow: hidden; border: 1px solid #4496e7; border-radius: 5px; cursor: text; height: 35px; height: auto !important; min-height: 35px;  left: 5px; }
div.friends2 { margin-top: 10px; }

div.friendsc { position: relative; top: 100px; left: 350px; width: 410px;  padding: 10px 0px; height: auto !important; height: 80px; min-height: 80px; background: green;}

div.clear { clear: both; width: 100%; height: 10px; }

button { position: absolute; top: 300px; left: 450px; }

input { position: relative; margin: 9px 0px 10px 10px; border: 0px solid white; float: left; max-width: 382px; }

div#outerfilter { width: 900px; background: grey;  position: relative; min-height: 400px; max-height: 500px; margin:auto; top: 10px; overflow: auto; padding-bottom: 20px; }
div#innerfilter { position: relative; top: 0px; left: 0px; width: 880px; min-height: 400px;background: #eaeaea; }
.filtersection { position: relative; float: left; width: 440px; min-height: 400px; height: auto !important; }
</style>
<script type="text/javascript">
$(document).ready(function(){
(function($){

$.fn.autoGrowInput = function(o) {

            o = $.extend({
                maxWidth: 1000,
                minWidth: 0,
                comfortZone: 70
            }, o);

            this.filter('input:text').each(function(){

                var minWidth = o.minWidth || $(this).width(),
                    val = '',
                    input = $(this),
                    testSubject = $('<tester/>').css({
                        position: 'absolute',
                        top: -9999,
                        left: -9999,
                        width: 'auto',
                        fontSize: input.css('fontSize'),
                        fontFamily: input.css('fontFamily'),
                        fontWeight: input.css('fontWeight'),
                        letterSpacing: input.css('letterSpacing'),
                        whiteSpace: 'nowrap'
                    }),
                    check = function() {

                        if (val === (val = input.val())) {return;}

                        // Enter new content into testSubject
                        var escaped = val.replace(/&/g, '&').replace(/\s/g,' ').replace(/</g, '<').replace(/>/g, '>');
                        testSubject.html(escaped);

                        // Calculate new width + whether to change
                        var testerWidth = testSubject.width(),
                            newWidth = Math.min((testerWidth + o.comfortZone) >= minWidth ? testerWidth + o.comfortZone : minWidth, o.maxWidth - 1),
                            currentWidth = input.width(),
                            isValidWidthChange = (newWidth < currentWidth && newWidth >= minWidth)
                                                 || (newWidth > minWidth && newWidth < o.maxWidth);

                        // Animate width
                        if (isValidWidthChange) {
                            input.width(newWidth);
                        }

                    };

                testSubject.insertAfter(input);

                $(this).bind('keyup keydown blur update', check);

            });

            return this;

        };

    })(jQuery);

arr = ["Soumyashree Chakraborty", "Payel","Jinia","Soujinia","Apoorva","Mona","Shamarpita","Pratik","Pranendra","Bhushan","Bijesh","Salma","Swift","Anushka","Radhe","Amol","Bardha","Sujata","Rohit","Amit","Anuradha","Amrita","Ajay","Sumil","Sachin","Sourav","Anmol","Britannia","Anamika","Priyanka"];
$("span.letter").live('click',function() {
$(this).parent().parent().find("input").focus();
$(this).parent().remove();
  });

options = {
            source: arr.slice(0,5),
            minLength: 1,
            select: function(event,ui) {
            $('<span class = "inpdiv"><span class = "content">'+ui.item.value+'</span><span class = "cancel"></span><span class="letter">X</span></span>').replaceAll(this);
            $("<input type='text' size='3' />").appendTo(curautocomp).focus();
            event.preventDefault();
            },
            focus: function(e,ui) {
            e.preventDefault();
            },
            autoFocus: true,
            delay: 0
            };
$("input").live("focus", function (event) {
curautocomp = $(this).parent();
$(this).autocomplete(options);
$(this).autoGrowInput({
    comfortZone: 5,
    minWidth: 15,
    maxWidth: 382
});
});

});
</script>
</head>
<body>
<div id = 'outerfilter'>
<div id = 'innerfilter'>
<div class = 'filtersection'>
<div class="filtertab"><span class="filtertext">Filter by Forum</span><span class='arrow'></span></div>
<br />
<div class = "friends">
<input type = "text" size = "2" value = "" />
</div>
<div class="filtertab"><span class="filtertext">Not Asked by</span><span class='arrow'></span></div>
<br />
<div class = "friends">
<input type = "text" size = "2" value = "" />
</div>
<div class="filtertab"><span class="filtertext">Has No Answer by</span><span class='arrow'></span></div>
<br />
<div class = "friends">
<input type = "text" size = "2" value = "" />
</div>
<div class="filtertab"><span class="filtertext">No of Answers</span><span class='arrow'></span></div>
<br />
<div class = "friends">
<input type = "text" size = "2" value = "" />
</div>
</div>
<div class = 'filtersection'>
<div class="filtertab"><span class="filtertext">Asked by</span><span class='arrow'></span></div>
<br />
<div class = "friends">
<input type = "text" size = "2" value = "" />
</div>
<div class="filtertab"><span class="filtertext">Has Answer by</span><span class='arrow'></span></div>
<br />
<div class = "friends">
<input type = "text" size = "2" value = "" />
</div>
<div class="filtertab"><span class="filtertext">Filter by Date</span><span class='arrow'></span></div>
<br />
<div id = 'datecontainer'>
<div class = 'dateheaders fromheader'>
<span class = 'spandatew'>Select a date</span>
<div class = 'arrow'></div>
</div>
<div class = 'dateheaders toheader'>
<span class = 'spandatew'>Select a date</span>
<div class = 'arrow'></div>
</div>
<div id = 'diva1'></div>
<div id = 'diva2'></div>
</div>
</div>
<div class = 'clear'></div>
</div>
</div>
</body>
</html>
</code>```

答:
```<code>$( "#input_box input" ).autocomplete({
      position: { my: "left bottom", at: "left top"},
      source: availableTags
    });
</code>```

This code means "left bottom" of autocomplete menu(my) should be placed at "left top" of input box(at).

Try Demo to understand this : https://www.plus2net.com/jquery/msg-demo/autocomplete-position.php

Body:
Is there any way to display the Autocomplete result set above the text input?

The problem is that I am using it in a lighbox application. The background element being set to 100% of the pages' height and width, it will naturally not expand with its content. So if the content above the text box increases so much that the input is forced towards the bottom of the page, and then the user types something into it, the autocomplete menu appears, and the input being towards the end of the page, the menu causes scrollbars to appear

Since the background element (dark colored) won't expand to accommodate it, as the menu is absolutely positioned, it looks visually ugly that the bottom of the page appears white (consistent with the actual page's color) while the top of the page dark.

So is there anyway to accomplish this, that prior to the autocomplete menu appearing, the position of the input should be checked. If it is, say, at more than 300px from the top, then the menu should appear above the input? This is the code:

<!DOCTYPE html>

<title>Filter</title>
<link type="text/css" href="ui/ui.css" rel="stylesheet" />

Filter by Forum

<input type = "text" size = "2" value = "" />

Not Asked by

<input type = "text" size = "2" value = "" />

Has No Answer by

<input type = "text" size = "2" value = "" />

No of Answers

<input type = "text" size = "2" value = "" />

Asked by

<input type = "text" size = "2" value = "" />

Has Answer by

<input type = "text" size = "2" value = "" />

Filter by Date

Select a date

Select a date

Body:
$( "#input_box input" ).autocomplete({
      position: { my: "left bottom", at: "left top"},
      source: availableTags
    });

This code means "left bottom" of autocomplete menu(my) should be placed at "left top" of input box(at).

Try Demo to understand this : https://www.plus2net.com/jquery/msg-demo/autocomplete-position.php


问:
Unity how to use native dll or convert to managed
I am trying to use a native c++ UWP component in a unity project for hololens.

I have successfully used a managed dll, but I can;t figure out how to use this native dll/

I want to either convert the dll to a managed dll or find some way to use a native dll.

答:
Did you tried this: Wrap native DLL for C# (the 2nd code block is interesting)?

Converting the dll is not possible afaik. You can convert the c++ code into c# and then create a managed dll but importing a native dll would be easier.

EDIT: Should mention that i don't mean the question in particular, just the 2nd code block, where the dll gets imported.


问:
How to re render component on goBack icon press in header
I am trying to re render the component after goBack press . By using goBack I am able to go back page ,but that page is not getting refresh. How I can solve it ?
After goBack I have to call some api ,and now after back non of the function is getting call . I can only call if page will refresh or rerender .

Example , from page 1 header am clicking back arrow icon (i.e goBack fucntion) to go on Page 1 and after going page 1 it should refresh .

```<code><View style={{ flexDirection: 'row' }} hasSubtitle={!!subtitle}>
            <Left style={{ flexGrow: 1 ,top: -10}}>
              <Button transparent onPress={() => {
                this.props.navigation.goBack();
              }}>
                <Icon name="arrow-back"/>
              </Button>
            </Left>
            <Body
              style={{ textAlign: 'center', width: '100%', flexGrow: 2, alignItems: 'center', justifyContent: 'center' }}>
            {!!title && <Title style={{ color: '#000' }}>{title}</Title>}
            {!!subtitle &&
            <Subtitle style={{ color: '#000' }}>
              {icon && <IconSmall icon={icon} type="MaterialCommunityIcons"/>}
              {subtitle}
            </Subtitle>}
            </Body>
            <Right style={{ flexGrow: 1, marginTop: 2 }}></Right>
          </View>
</code>```

Thanks

答: You can pass a callback function to this component or page and then when you click on button to go back you should execute this callback function that will execute the api request! You can execute the callback before execute this.props.navigation.goBack();

Body:
I am trying to re render the component after goBack press . By using goBack I am able to go back page ,but that page is not getting refresh. How I can solve it ?
After goBack I have to call some api ,and now after back non of the function is getting call . I can only call if page will refresh or rerender .

Example , from page 1 header am clicking back arrow icon (i.e goBack fucntion) to go on Page 1 and after going page 1 it should refresh .

<View style={{ flexDirection: 'row' }} hasSubtitle={!!subtitle}>
            <Left style={{ flexGrow: 1 ,top: -10}}>
              <Button transparent onPress={() => {
                this.props.navigation.goBack();
              }}>
                <Icon name="arrow-back"/>
              </Button>
            </Left>

            {!!title && <Title style={{ color: '#000' }}>{title}</Title>}
            {!!subtitle &&
            <Subtitle style={{ color: '#000' }}>
              {icon && <IconSmall icon={icon} type="MaterialCommunityIcons"/>}
              {subtitle}
            </Subtitle>}

            <Right style={{ flexGrow: 1, marginTop: 2 }}></Right>
          </View>

Thanks


问:
How to limit the number of call record in CDR file
My call records are getting store in /var/log/asterisk/cdr-csv/Master.csv file. i want to limit the number of call to be stored ni this file, after that it should start form the beginning,
so for this what could be procedure</p>

答:
You can't limit number of records by asterisk

But you easy can rotate files by using logrotate linux utility.

For that you should create file /etc/logrotate.d/asterisk_cdr

```<code>/var/log/asterisk/cdr-csv/*csv {
missingok
rotate 5
size 2000k
create 0640 asterisk asterisk
}
</code>```

For more info see documentation for logrotated

Body:
You can't limit number of records by asterisk

But you easy can rotate files by using logrotate linux utility.

For that you should create file /etc/logrotate.d/asterisk_cdr

/var/log/asterisk/cdr-csv/*csv {
missingok
rotate 5
size 2000k
create 0640 asterisk asterisk
}

For more info see documentation for logrotated


问:
Use Sqlite & Knex with Node Module
im building a desktop app with electron and use for that JS and jQuery. All of them are installed as modules and used with "require" . it works perfect.

Now i want my database with sqlite and knex and try to start the node server with the knex and sqlite db together with the app.

but the problem is, that knex cant find the sqlite module.

can someone help me?

```<code>HERE is the start

console.log('SQL - Datenbank-Server gestartet');

let express = require('express');
let app = express();

let knex = require('knex');

let server = app.listen(8286, function () {
console.log('DB Server running on port 8286');
});

let connection = knex({
client: 'sqlite3',
connection: {
    filename: './finanzverwaltung.db'
}
});

HERE is the Failure
 Server gestartet.
SQL - Datenbank-Server gestartet
Knex: run
$ npm install sqlite3 --save
Cannot find module 'F:\Projekte\finanzverwaltung\node_modules\sqlite3\lib\binding\node-v70-win32-x64\node_sqlite3.node'
Require stack:
- F:\Projekte\finanzverwaltung\node_modules\sqlite3\lib\sqlite3.js
- F:\Projekte\finanzverwaltung\node_modules\knex\lib\dialects\sqlite3\index.js
- F:\Projekte\finanzverwaltung\node_modules\knex\lib\knex.js
- F:\Projekte\finanzverwaltung\node_modules\knex\lib\index.js
- F:\Projekte\finanzverwaltung\node_modules\knex\knex.js
- F:\Projekte\finanzverwaltung\app\server\sql_server.js
Error: Cannot find module 'F:\Projekte\finanzverwaltung\node_modules\sqlite3\lib\binding\node-v70-win32-x64\node_sqlite3.node'
Require stack:
- F:\Projekte\finanzverwaltung\node_modules\sqlite3\lib\sqlite3.js
- F:\Projekte\finanzverwaltung\node_modules\knex\lib\dialects\sqlite3\index.js
- F:\Projekte\finanzverwaltung\node_modules\knex\lib\knex.js
- F:\Projekte\finanzverwaltung\node_modules\knex\lib\index.js
- F:\Projekte\finanzverwaltung\node_modules\knex\knex.js
- F:\Projekte\finanzverwaltung\app\server\sql_server.js
    at Function.Module._resolveFilename (internal/modules/cjs/loader.js:659:15)
    at Function.Module._load (internal/modules/cjs/loader.js:577:27)
    at Module.require (internal/modules/cjs/loader.js:715:19)
    at require (internal/modules/cjs/helpers.js:14:16)
    at Object.<anonymous> (F:\Projekte\finanzverwaltung\node_modules\sqlite3\lib\sqlite3.js:4:15)
    at Module._compile (internal/modules/cjs/loader.js:808:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:820:10)
    at Module.load (internal/modules/cjs/loader.js:677:32)
    at tryModuleLoad (internal/modules/cjs/loader.js:609:12)
    at Function.Module._load (internal/modules/cjs/loader.js:601:3)
    at Module.require (internal/modules/cjs/loader.js:715:19)
    at require (internal/modules/cjs/helpers.js:14:16)
    at Client_SQLite3._driver (F:\Projekte\finanzverwaltung\node_modules\knex\lib\dialects\sqlite3\index.js:44:12)
    at Client_SQLite3.initializeDriver (F:\Projekte\finanzverwaltung\node_modules\knex\lib\client.js:253:26)
    at Client_SQLite3.Client (F:\Projekte\finanzverwaltung\node_modules\knex\lib\client.js:84:10)
    at new Client_SQLite3 (F:\Projekte\finanzverwaltung\node_modules\knex\lib\dialects\sqlite3\index.js:31:19)
F:\Projekte\finanzverwaltung\node_modules\knex\lib\client.js:257
      throw new Error(`${message}\n${e.message}`);
      ^

Error: Knex: run
$ npm install sqlite3 --save
Cannot find module 'F:\Projekte\finanzverwaltung\node_modules\sqlite3\lib\binding\node-v70-win32-x64\node_sqlite3.node'
Require stack:
- F:\Projekte\finanzverwaltung\node_modules\sqlite3\lib\sqlite3.js
- F:\Projekte\finanzverwaltung\node_modules\knex\lib\dialects\sqlite3\index.js
- F:\Projekte\finanzverwaltung\node_modules\knex\lib\knex.js
- F:\Projekte\finanzverwaltung\node_modules\knex\lib\index.js
- F:\Projekte\finanzverwaltung\node_modules\knex\knex.js
- F:\Projekte\finanzverwaltung\app\server\sql_server.js
    at Client_SQLite3.initializeDriver (F:\Projekte\finanzverwaltung\node_modules\knex\lib\client.js:257:13)
    at Client_SQLite3.Client (F:\Projekte\finanzverwaltung\node_modules\knex\lib\client.js:84:10)
    at new Client_SQLite3 (F:\Projekte\finanzverwaltung\node_modules\knex\lib\dialects\sqlite3\index.js:31:19)
    at Knex (F:\Projekte\finanzverwaltung\node_modules\knex\lib\knex.js:57:42)
    at Object.<anonymous> (F:\Projekte\finanzverwaltung\app\server\sql_server.js:12:18)
    at Module._compile (internal/modules/cjs/loader.js:808:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:820:10)
    at Module.load (internal/modules/cjs/loader.js:677:32)
    at tryModuleLoad (internal/modules/cjs/loader.js:609:12)
    at Function.Module._load (internal/modules/cjs/loader.js:601:3)
    at Function.Module.runMain (internal/modules/cjs/loader.js:873:10)
    at internal/main/run_main_module.js:21:11
</code>```

答:
So finally i did it - and the solution is to use the electron-builder...</p>

```<code>"postinstall": "electron-builder install-app-deps"
</code>```

Title: Use Sqlite & Knex with Node Module

Body:
im building a desktop app with electron and use for that JS and jQuery. All of them are installed as modules and used with "require" . it works perfect.

Now i want my database with sqlite and knex and try to start the node server with the knex and sqlite db together with the app.

but the problem is, that knex cant find the sqlite module.

can someone help me?

HERE is the start

console.log('SQL - Datenbank-Server gestartet');

let express = require('express');
let app = express();

let knex = require('knex');

let server = app.listen(8286, function () {
console.log('DB Server running on port 8286');
});

let connection = knex({
client: 'sqlite3',
connection: {
    filename: './finanzverwaltung.db'
}
});

HERE is the Failure
 Server gestartet.
SQL - Datenbank-Server gestartet
Knex: run
$ npm install sqlite3 --save
Cannot find module 'F:\Projekte\finanzverwaltung\node_modules\sqlite3\lib\binding\node-v70-win32-x64\node_sqlite3.node'
Require stack:
- F:\Projekte\finanzverwaltung\node_modules\sqlite3\lib\sqlite3.js
- F:\Projekte\finanzverwaltung\node_modules\knex\lib\dialects\sqlite3\index.js
- F:\Projekte\finanzverwaltung\node_modules\knex\lib\knex.js
- F:\Projekte\finanzverwaltung\node_modules\knex\lib\index.js
- F:\Projekte\finanzverwaltung\node_modules\knex\knex.js
- F:\Projekte\finanzverwaltung\app\server\sql_server.js
Error: Cannot find module 'F:\Projekte\finanzverwaltung\node_modules\sqlite3\lib\binding\node-v70-win32-x64\node_sqlite3.node'
Require stack:
- F:\Projekte\finanzverwaltung\node_modules\sqlite3\lib\sqlite3.js
- F:\Projekte\finanzverwaltung\node_modules\knex\lib\dialects\sqlite3\index.js
- F:\Projekte\finanzverwaltung\node_modules\knex\lib\knex.js
- F:\Projekte\finanzverwaltung\node_modules\knex\lib\index.js
- F:\Projekte\finanzverwaltung\node_modules\knex\knex.js
- F:\Projekte\finanzverwaltung\app\server\sql_server.js
    at Function.Module._resolveFilename (internal/modules/cjs/loader.js:659:15)
    at Function.Module._load (internal/modules/cjs/loader.js:577:27)
    at Module.require (internal/modules/cjs/loader.js:715:19)
    at require (internal/modules/cjs/helpers.js:14:16)
    at Object.<anonymous> (F:\Projekte\finanzverwaltung\node_modules\sqlite3\lib\sqlite3.js:4:15)
    at Module._compile (internal/modules/cjs/loader.js:808:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:820:10)
    at Module.load (internal/modules/cjs/loader.js:677:32)
    at tryModuleLoad (internal/modules/cjs/loader.js:609:12)
    at Function.Module._load (internal/modules/cjs/loader.js:601:3)
    at Module.require (internal/modules/cjs/loader.js:715:19)
    at require (internal/modules/cjs/helpers.js:14:16)
    at Client_SQLite3._driver (F:\Projekte\finanzverwaltung\node_modules\knex\lib\dialects\sqlite3\index.js:44:12)
    at Client_SQLite3.initializeDriver (F:\Projekte\finanzverwaltung\node_modules\knex\lib\client.js:253:26)
    at Client_SQLite3.Client (F:\Projekte\finanzverwaltung\node_modules\knex\lib\client.js:84:10)
    at new Client_SQLite3 (F:\Projekte\finanzverwaltung\node_modules\knex\lib\dialects\sqlite3\index.js:31:19)
F:\Projekte\finanzverwaltung\node_modules\knex\lib\client.js:257
      throw new Error(`${message}\n${e.message}`);
      ^

Error: Knex: run
$ npm install sqlite3 --save
Cannot find module 'F:\Projekte\finanzverwaltung\node_modules\sqlite3\lib\binding\node-v70-win32-x64\node_sqlite3.node'
Require stack:
- F:\Projekte\finanzverwaltung\node_modules\sqlite3\lib\sqlite3.js
- F:\Projekte\finanzverwaltung\node_modules\knex\lib\dialects\sqlite3\index.js
- F:\Projekte\finanzverwaltung\node_modules\knex\lib\knex.js
- F:\Projekte\finanzverwaltung\node_modules\knex\lib\index.js
- F:\Projekte\finanzverwaltung\node_modules\knex\knex.js
- F:\Projekte\finanzverwaltung\app\server\sql_server.js
    at Client_SQLite3.initializeDriver (F:\Projekte\finanzverwaltung\node_modules\knex\lib\client.js:257:13)
    at Client_SQLite3.Client (F:\Projekte\finanzverwaltung\node_modules\knex\lib\client.js:84:10)
    at new Client_SQLite3 (F:\Projekte\finanzverwaltung\node_modules\knex\lib\dialects\sqlite3\index.js:31:19)
    at Knex (F:\Projekte\finanzverwaltung\node_modules\knex\lib\knex.js:57:42)
    at Object.<anonymous> (F:\Projekte\finanzverwaltung\app\server\sql_server.js:12:18)
    at Module._compile (internal/modules/cjs/loader.js:808:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:820:10)
    at Module.load (internal/modules/cjs/loader.js:677:32)
    at tryModuleLoad (internal/modules/cjs/loader.js:609:12)
    at Function.Module._load (internal/modules/cjs/loader.js:601:3)
    at Function.Module.runMain (internal/modules/cjs/loader.js:873:10)
    at internal/main/run_main_module.js:21:11

Body:
So finally i did it - and the solution is to use the electron-builder...

"postinstall": "electron-builder install-app-deps"


问:
How make request GET in angular?
i need request GET from angular to spring java, but i get  error 415

```<code>zone.js:3243 GET http://localhost:8080/user/friend/1 415
</code>```

this is my code in spring java to the endpoint

```<code> @RequestMapping(
            value = "/friend/{idUser}",
            method = RequestMethod.GET,
            consumes = "application/json",
            produces = "application/json")
    public ResponseEntity<List<Friendship>> getFriend(@PathVariable Long idUser) {
        return new ResponseEntity<List<Friendship>>(userServiceImpl.getFriends(idUser), HttpStatus.OK);
    }
</code>```

and this is my code in angular, to request the data from backend

```<code>getFriends(idUser) {
        console.log('UNA', idUser);
        const config = new HttpHeaders().set('Content-Type', 'application/json');
        const url = 'http://localhost:8080/user/friend/' + idUser;
        const body = JSON.stringify({"idOwner": idUser});
        return this.http.get<Object[]>(url);
    }
</code>```

答:
You missing config in the http get so your code should be </p>

```<code>return this.http.get<Object[]>(url, config);
</code>```

Title: How make request GET in angular?

Body:
i need request GET from angular to spring java, but i get  error 415

zone.js:3243 GET http://localhost:8080/user/friend/1 415

this is my code in spring java to the endpoint

 @RequestMapping(
            value = "/friend/{idUser}",
            method = RequestMethod.GET,
            consumes = "application/json",
            produces = "application/json")
    public ResponseEntity<List<Friendship>> getFriend(@PathVariable Long idUser) {
        return new ResponseEntity<List<Friendship>>(userServiceImpl.getFriends(idUser), HttpStatus.OK);
    }

and this is my code in angular, to request the data from backend

getFriends(idUser) {
        console.log('UNA', idUser);
        const config = new HttpHeaders().set('Content-Type', 'application/json');
        const url = 'http://localhost:8080/user/friend/' + idUser;
        const body = JSON.stringify({"idOwner": idUser});
        return this.http.get<Object[]>(url);
    }

Body:
You missing config in the http get so your code should be

return this.http.get<Object[]>(url, config);